1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86ShuffleDecodeConstantPool.h"
22 #include "X86TargetMachine.h"
23 #include "X86TargetObjectFile.h"
24 #include "llvm/ADT/SmallBitVector.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/Analysis/EHPersonalities.h"
30 #include "llvm/CodeGen/IntrinsicLowering.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/WinEHFuncInfo.h"
38 #include "llvm/IR/CallSite.h"
39 #include "llvm/IR/CallingConv.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalAlias.h"
44 #include "llvm/IR/GlobalVariable.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/Intrinsics.h"
47 #include "llvm/MC/MCAsmInfo.h"
48 #include "llvm/MC/MCContext.h"
49 #include "llvm/MC/MCExpr.h"
50 #include "llvm/MC/MCSymbol.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Target/TargetOptions.h"
56 #include "X86IntrinsicsInfo.h"
62 #define DEBUG_TYPE "x86-isel"
64 STATISTIC(NumTailCalls, "Number of tail calls");
66 static cl::opt<bool> ExperimentalVectorWideningLegalization(
67 "x86-experimental-vector-widening-legalization", cl::init(false),
68 cl::desc("Enable an experimental vector type legalization through widening "
69 "rather than promotion."),
72 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
73 const X86Subtarget &STI)
74 : TargetLowering(TM), Subtarget(STI) {
75 bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
76 X86ScalarSSEf64 = Subtarget.hasSSE2();
77 X86ScalarSSEf32 = Subtarget.hasSSE1();
78 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
80 // Set up the TargetLowering object.
82 // X86 is weird. It always uses i8 for shift amounts and setcc results.
83 setBooleanContents(ZeroOrOneBooleanContent);
84 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
85 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
87 // For 64-bit, since we have so many registers, use the ILP scheduler.
88 // For 32-bit, use the register pressure specific scheduling.
89 // For Atom, always use ILP scheduling.
90 if (Subtarget.isAtom())
91 setSchedulingPreference(Sched::ILP);
92 else if (Subtarget.is64Bit())
93 setSchedulingPreference(Sched::ILP);
95 setSchedulingPreference(Sched::RegPressure);
96 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
97 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
99 // Bypass expensive divides on Atom when compiling with O2.
100 if (TM.getOptLevel() >= CodeGenOpt::Default) {
101 if (Subtarget.hasSlowDivide32())
102 addBypassSlowDiv(32, 8);
103 if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
104 addBypassSlowDiv(64, 16);
107 if (Subtarget.isTargetKnownWindowsMSVC()) {
108 // Setup Windows compiler runtime calls.
109 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
110 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
111 setLibcallName(RTLIB::SREM_I64, "_allrem");
112 setLibcallName(RTLIB::UREM_I64, "_aullrem");
113 setLibcallName(RTLIB::MUL_I64, "_allmul");
114 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
115 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
116 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
117 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
118 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
121 if (Subtarget.isTargetDarwin()) {
122 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
123 setUseUnderscoreSetJmp(false);
124 setUseUnderscoreLongJmp(false);
125 } else if (Subtarget.isTargetWindowsGNU()) {
126 // MS runtime is weird: it exports _setjmp, but longjmp!
127 setUseUnderscoreSetJmp(true);
128 setUseUnderscoreLongJmp(false);
130 setUseUnderscoreSetJmp(true);
131 setUseUnderscoreLongJmp(true);
134 // Set up the register classes.
135 addRegisterClass(MVT::i8, &X86::GR8RegClass);
136 addRegisterClass(MVT::i16, &X86::GR16RegClass);
137 addRegisterClass(MVT::i32, &X86::GR32RegClass);
138 if (Subtarget.is64Bit())
139 addRegisterClass(MVT::i64, &X86::GR64RegClass);
141 for (MVT VT : MVT::integer_valuetypes())
142 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
144 // We don't accept any truncstore of integer registers.
145 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
146 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
147 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
148 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
149 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
150 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
152 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
154 // SETOEQ and SETUNE require checking two conditions.
155 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
156 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
157 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
158 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
159 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
160 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
162 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
164 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
165 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
166 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
168 if (Subtarget.is64Bit()) {
169 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512())
170 // f32/f64 are legal, f80 is custom.
171 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
173 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
174 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
175 } else if (!Subtarget.useSoftFloat()) {
176 // We have an algorithm for SSE2->double, and we turn this into a
177 // 64-bit FILD followed by conditional FADD for other targets.
178 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
179 // We have an algorithm for SSE2, and we turn this into a 64-bit
180 // FILD or VCVTUSI2SS/SD for other targets.
181 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
184 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
186 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
187 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
189 if (!Subtarget.useSoftFloat()) {
190 // SSE has no i16 to fp conversion, only i32.
191 if (X86ScalarSSEf32) {
192 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
193 // f32 and f64 cases are Legal, f80 case is not
194 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
196 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
197 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
200 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
201 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
204 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
206 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
207 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
209 if (!Subtarget.useSoftFloat()) {
210 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
211 // are Legal, f80 is custom lowered.
212 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
213 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
215 if (X86ScalarSSEf32) {
216 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
217 // f32 and f64 cases are Legal, f80 case is not
218 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
220 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
221 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
224 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
225 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Expand);
226 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Expand);
229 // Handle FP_TO_UINT by promoting the destination to a larger signed
231 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
232 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
233 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
235 if (Subtarget.is64Bit()) {
236 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
237 // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
238 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
239 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
241 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
242 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
244 } else if (!Subtarget.useSoftFloat()) {
245 // Since AVX is a superset of SSE3, only check for SSE here.
246 if (Subtarget.hasSSE1() && !Subtarget.hasSSE3())
247 // Expand FP_TO_UINT into a select.
248 // FIXME: We would like to use a Custom expander here eventually to do
249 // the optimal thing for SSE vs. the default expansion in the legalizer.
250 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
252 // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
253 // With SSE3 we can use fisttpll to convert to a signed i64; without
254 // SSE, we're stuck with a fistpll.
255 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
257 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
260 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
261 if (!X86ScalarSSEf64) {
262 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
263 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
264 if (Subtarget.is64Bit()) {
265 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
266 // Without SSE, i64->f64 goes through memory.
267 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
269 } else if (!Subtarget.is64Bit())
270 setOperationAction(ISD::BITCAST , MVT::i64 , Custom);
272 // Scalar integer divide and remainder are lowered to use operations that
273 // produce two results, to match the available instructions. This exposes
274 // the two-result form to trivial CSE, which is able to combine x/y and x%y
275 // into a single instruction.
277 // Scalar integer multiply-high is also lowered to use two-result
278 // operations, to match the available instructions. However, plain multiply
279 // (low) operations are left as Legal, as there are single-result
280 // instructions for this in x86. Using the two-result multiply instructions
281 // when both high and low results are needed must be arranged by dagcombine.
282 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
283 setOperationAction(ISD::MULHS, VT, Expand);
284 setOperationAction(ISD::MULHU, VT, Expand);
285 setOperationAction(ISD::SDIV, VT, Expand);
286 setOperationAction(ISD::UDIV, VT, Expand);
287 setOperationAction(ISD::SREM, VT, Expand);
288 setOperationAction(ISD::UREM, VT, Expand);
290 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
291 setOperationAction(ISD::ADDC, VT, Custom);
292 setOperationAction(ISD::ADDE, VT, Custom);
293 setOperationAction(ISD::SUBC, VT, Custom);
294 setOperationAction(ISD::SUBE, VT, Custom);
297 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
298 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
299 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
300 MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
301 setOperationAction(ISD::BR_CC, VT, Expand);
302 setOperationAction(ISD::SELECT_CC, VT, Expand);
304 if (Subtarget.is64Bit())
305 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
306 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
307 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
308 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
309 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
311 setOperationAction(ISD::FREM , MVT::f32 , Expand);
312 setOperationAction(ISD::FREM , MVT::f64 , Expand);
313 setOperationAction(ISD::FREM , MVT::f80 , Expand);
314 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
316 // Promote the i8 variants and force them on up to i32 which has a shorter
318 setOperationPromotedToType(ISD::CTTZ , MVT::i8 , MVT::i32);
319 setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
320 if (!Subtarget.hasBMI()) {
321 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
322 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
323 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Legal);
324 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Legal);
325 if (Subtarget.is64Bit()) {
326 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
327 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Legal);
331 if (Subtarget.hasLZCNT()) {
332 // When promoting the i8 variants, force them to i32 for a shorter
334 setOperationPromotedToType(ISD::CTLZ , MVT::i8 , MVT::i32);
335 setOperationPromotedToType(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
337 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
338 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
339 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
340 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
341 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
342 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
343 if (Subtarget.is64Bit()) {
344 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
345 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
349 // Special handling for half-precision floating point conversions.
350 // If we don't have F16C support, then lower half float conversions
351 // into library calls.
352 if (Subtarget.useSoftFloat() || !Subtarget.hasF16C()) {
353 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
354 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
357 // There's never any support for operations beyond MVT::f32.
358 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
359 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
360 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
361 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
363 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
364 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
365 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
366 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
367 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
368 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
370 if (Subtarget.hasPOPCNT()) {
371 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
373 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
374 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
375 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
376 if (Subtarget.is64Bit())
377 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
380 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
382 if (!Subtarget.hasMOVBE())
383 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
385 // These should be promoted to a larger select which is supported.
386 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
387 // X86 wants to expand cmov itself.
388 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
389 setOperationAction(ISD::SELECT, VT, Custom);
390 setOperationAction(ISD::SETCC, VT, Custom);
392 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
393 if (VT == MVT::i64 && !Subtarget.is64Bit())
395 setOperationAction(ISD::SELECT, VT, Custom);
396 setOperationAction(ISD::SETCC, VT, Custom);
397 setOperationAction(ISD::SETCCE, VT, Custom);
399 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
400 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
401 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
402 // support continuation, user-level threading, and etc.. As a result, no
403 // other SjLj exception interfaces are implemented and please don't build
404 // your own exception handling based on them.
405 // LLVM/Clang supports zero-cost DWARF exception handling.
406 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
407 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
408 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
409 if (TM.Options.ExceptionModel == ExceptionHandling::SjLj)
410 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
413 for (auto VT : { MVT::i32, MVT::i64 }) {
414 if (VT == MVT::i64 && !Subtarget.is64Bit())
416 setOperationAction(ISD::ConstantPool , VT, Custom);
417 setOperationAction(ISD::JumpTable , VT, Custom);
418 setOperationAction(ISD::GlobalAddress , VT, Custom);
419 setOperationAction(ISD::GlobalTLSAddress, VT, Custom);
420 setOperationAction(ISD::ExternalSymbol , VT, Custom);
421 setOperationAction(ISD::BlockAddress , VT, Custom);
423 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
424 for (auto VT : { MVT::i32, MVT::i64 }) {
425 if (VT == MVT::i64 && !Subtarget.is64Bit())
427 setOperationAction(ISD::SHL_PARTS, VT, Custom);
428 setOperationAction(ISD::SRA_PARTS, VT, Custom);
429 setOperationAction(ISD::SRL_PARTS, VT, Custom);
432 if (Subtarget.hasSSE1())
433 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
435 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
437 // Expand certain atomics
438 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
439 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
440 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
441 setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Custom);
442 setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Custom);
443 setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Custom);
444 setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Custom);
445 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
448 if (Subtarget.hasCmpxchg16b()) {
449 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
452 // FIXME - use subtarget debug flags
453 if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
454 !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
455 TM.Options.ExceptionModel != ExceptionHandling::SjLj) {
456 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
459 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
460 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
462 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
463 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
465 setOperationAction(ISD::TRAP, MVT::Other, Legal);
466 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
468 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
469 setOperationAction(ISD::VASTART , MVT::Other, Custom);
470 setOperationAction(ISD::VAEND , MVT::Other, Expand);
471 bool Is64Bit = Subtarget.is64Bit();
472 setOperationAction(ISD::VAARG, MVT::Other, Is64Bit ? Custom : Expand);
473 setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
475 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
476 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
478 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
480 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
481 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
482 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
484 if (!Subtarget.useSoftFloat() && X86ScalarSSEf64) {
485 // f32 and f64 use SSE.
486 // Set up the FP register classes.
487 addRegisterClass(MVT::f32, &X86::FR32RegClass);
488 addRegisterClass(MVT::f64, &X86::FR64RegClass);
490 for (auto VT : { MVT::f32, MVT::f64 }) {
491 // Use ANDPD to simulate FABS.
492 setOperationAction(ISD::FABS, VT, Custom);
494 // Use XORP to simulate FNEG.
495 setOperationAction(ISD::FNEG, VT, Custom);
497 // Use ANDPD and ORPD to simulate FCOPYSIGN.
498 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
500 // We don't support sin/cos/fmod
501 setOperationAction(ISD::FSIN , VT, Expand);
502 setOperationAction(ISD::FCOS , VT, Expand);
503 setOperationAction(ISD::FSINCOS, VT, Expand);
506 // Lower this to MOVMSK plus an AND.
507 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
508 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
510 // Expand FP immediates into loads from the stack, except for the special
512 addLegalFPImmediate(APFloat(+0.0)); // xorpd
513 addLegalFPImmediate(APFloat(+0.0f)); // xorps
514 } else if (UseX87 && X86ScalarSSEf32) {
515 // Use SSE for f32, x87 for f64.
516 // Set up the FP register classes.
517 addRegisterClass(MVT::f32, &X86::FR32RegClass);
518 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
520 // Use ANDPS to simulate FABS.
521 setOperationAction(ISD::FABS , MVT::f32, Custom);
523 // Use XORP to simulate FNEG.
524 setOperationAction(ISD::FNEG , MVT::f32, Custom);
526 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
528 // Use ANDPS and ORPS to simulate FCOPYSIGN.
529 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
530 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
532 // We don't support sin/cos/fmod
533 setOperationAction(ISD::FSIN , MVT::f32, Expand);
534 setOperationAction(ISD::FCOS , MVT::f32, Expand);
535 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
537 // Special cases we handle for FP constants.
538 addLegalFPImmediate(APFloat(+0.0f)); // xorps
539 addLegalFPImmediate(APFloat(+0.0)); // FLD0
540 addLegalFPImmediate(APFloat(+1.0)); // FLD1
541 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
542 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
544 if (!TM.Options.UnsafeFPMath) {
545 setOperationAction(ISD::FSIN , MVT::f64, Expand);
546 setOperationAction(ISD::FCOS , MVT::f64, Expand);
547 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
550 // f32 and f64 in x87.
551 // Set up the FP register classes.
552 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
553 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
555 for (auto VT : { MVT::f32, MVT::f64 }) {
556 setOperationAction(ISD::UNDEF, VT, Expand);
557 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
559 if (!TM.Options.UnsafeFPMath) {
560 setOperationAction(ISD::FSIN , VT, Expand);
561 setOperationAction(ISD::FCOS , VT, Expand);
562 setOperationAction(ISD::FSINCOS, VT, Expand);
565 addLegalFPImmediate(APFloat(+0.0)); // FLD0
566 addLegalFPImmediate(APFloat(+1.0)); // FLD1
567 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
568 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
569 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
570 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
571 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
572 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
575 // We don't support FMA.
576 setOperationAction(ISD::FMA, MVT::f64, Expand);
577 setOperationAction(ISD::FMA, MVT::f32, Expand);
579 // Long double always uses X87, except f128 in MMX.
581 if (Subtarget.is64Bit() && Subtarget.hasMMX()) {
582 addRegisterClass(MVT::f128, &X86::FR128RegClass);
583 ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
584 setOperationAction(ISD::FABS , MVT::f128, Custom);
585 setOperationAction(ISD::FNEG , MVT::f128, Custom);
586 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
589 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
590 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
591 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
593 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
594 addLegalFPImmediate(TmpFlt); // FLD0
596 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
599 APFloat TmpFlt2(+1.0);
600 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
602 addLegalFPImmediate(TmpFlt2); // FLD1
603 TmpFlt2.changeSign();
604 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
607 if (!TM.Options.UnsafeFPMath) {
608 setOperationAction(ISD::FSIN , MVT::f80, Expand);
609 setOperationAction(ISD::FCOS , MVT::f80, Expand);
610 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
613 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
614 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
615 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
616 setOperationAction(ISD::FRINT, MVT::f80, Expand);
617 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
618 setOperationAction(ISD::FMA, MVT::f80, Expand);
621 // Always use a library call for pow.
622 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
623 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
624 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
626 setOperationAction(ISD::FLOG, MVT::f80, Expand);
627 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
628 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
629 setOperationAction(ISD::FEXP, MVT::f80, Expand);
630 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
631 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
632 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
634 // Some FP actions are always expanded for vector types.
635 for (auto VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32,
636 MVT::v2f64, MVT::v4f64, MVT::v8f64 }) {
637 setOperationAction(ISD::FSIN, VT, Expand);
638 setOperationAction(ISD::FSINCOS, VT, Expand);
639 setOperationAction(ISD::FCOS, VT, Expand);
640 setOperationAction(ISD::FREM, VT, Expand);
641 setOperationAction(ISD::FPOWI, VT, Expand);
642 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
643 setOperationAction(ISD::FPOW, VT, Expand);
644 setOperationAction(ISD::FLOG, VT, Expand);
645 setOperationAction(ISD::FLOG2, VT, Expand);
646 setOperationAction(ISD::FLOG10, VT, Expand);
647 setOperationAction(ISD::FEXP, VT, Expand);
648 setOperationAction(ISD::FEXP2, VT, Expand);
651 // First set operation action for all vector types to either promote
652 // (for widening) or expand (for scalarization). Then we will selectively
653 // turn on ones that can be effectively codegen'd.
654 for (MVT VT : MVT::vector_valuetypes()) {
655 setOperationAction(ISD::SDIV, VT, Expand);
656 setOperationAction(ISD::UDIV, VT, Expand);
657 setOperationAction(ISD::SREM, VT, Expand);
658 setOperationAction(ISD::UREM, VT, Expand);
659 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
660 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
661 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
662 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
663 setOperationAction(ISD::FMA, VT, Expand);
664 setOperationAction(ISD::FFLOOR, VT, Expand);
665 setOperationAction(ISD::FCEIL, VT, Expand);
666 setOperationAction(ISD::FTRUNC, VT, Expand);
667 setOperationAction(ISD::FRINT, VT, Expand);
668 setOperationAction(ISD::FNEARBYINT, VT, Expand);
669 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
670 setOperationAction(ISD::MULHS, VT, Expand);
671 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
672 setOperationAction(ISD::MULHU, VT, Expand);
673 setOperationAction(ISD::SDIVREM, VT, Expand);
674 setOperationAction(ISD::UDIVREM, VT, Expand);
675 setOperationAction(ISD::CTPOP, VT, Expand);
676 setOperationAction(ISD::CTTZ, VT, Expand);
677 setOperationAction(ISD::CTLZ, VT, Expand);
678 setOperationAction(ISD::ROTL, VT, Expand);
679 setOperationAction(ISD::ROTR, VT, Expand);
680 setOperationAction(ISD::BSWAP, VT, Expand);
681 setOperationAction(ISD::SETCC, VT, Expand);
682 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
683 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
684 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
685 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
686 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
687 setOperationAction(ISD::TRUNCATE, VT, Expand);
688 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
689 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
690 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
691 setOperationAction(ISD::SELECT_CC, VT, Expand);
692 for (MVT InnerVT : MVT::vector_valuetypes()) {
693 setTruncStoreAction(InnerVT, VT, Expand);
695 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
696 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
698 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
699 // types, we have to deal with them whether we ask for Expansion or not.
700 // Setting Expand causes its own optimisation problems though, so leave
702 if (VT.getVectorElementType() == MVT::i1)
703 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
705 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
706 // split/scalarized right now.
707 if (VT.getVectorElementType() == MVT::f16)
708 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
712 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
713 // with -msoft-float, disable use of MMX as well.
714 if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
715 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
716 // No operations on x86mmx supported, everything uses intrinsics.
719 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
720 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
722 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
723 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
724 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
725 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
726 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
727 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
728 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
729 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
732 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
733 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
735 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
736 // registers cannot be used even for integer operations.
737 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
738 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
739 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
740 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
742 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
743 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
744 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
745 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
746 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
747 setOperationAction(ISD::MULHU, MVT::v16i8, Custom);
748 setOperationAction(ISD::MULHS, MVT::v16i8, Custom);
749 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
750 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
751 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
752 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
753 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
755 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
756 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
757 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
758 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
760 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
761 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
762 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
763 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
765 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
766 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
767 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
768 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
769 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
771 setOperationAction(ISD::CTPOP, MVT::v16i8, Custom);
772 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
773 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
774 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
776 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
777 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
778 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
779 // ISD::CTTZ v2i64 - scalarization is faster.
781 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
782 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
783 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
784 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
785 setOperationAction(ISD::VSELECT, VT, Custom);
786 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
789 // We support custom legalizing of sext and anyext loads for specific
790 // memory vector types which we can load as a scalar (or sequence of
791 // scalars) and extend in-register to a legal 128-bit vector type. For sext
792 // loads these must work with a single scalar load.
793 for (MVT VT : MVT::integer_vector_valuetypes()) {
794 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
795 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
796 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
797 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
798 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
799 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
800 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
801 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
802 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
805 for (auto VT : { MVT::v2f64, MVT::v2i64 }) {
806 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
807 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
808 setOperationAction(ISD::VSELECT, VT, Custom);
810 if (VT == MVT::v2i64 && !Subtarget.is64Bit())
813 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
814 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
817 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
818 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
819 setOperationPromotedToType(ISD::AND, VT, MVT::v2i64);
820 setOperationPromotedToType(ISD::OR, VT, MVT::v2i64);
821 setOperationPromotedToType(ISD::XOR, VT, MVT::v2i64);
822 setOperationPromotedToType(ISD::LOAD, VT, MVT::v2i64);
823 setOperationPromotedToType(ISD::SELECT, VT, MVT::v2i64);
826 // Custom lower v2i64 and v2f64 selects.
827 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
828 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
830 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
831 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
833 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
835 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
836 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
837 // As there is no 64-bit GPR available, we need build a special custom
838 // sequence to convert from v2i32 to v2f32.
839 if (!Subtarget.is64Bit())
840 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
842 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
843 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
845 for (MVT VT : MVT::fp_vector_valuetypes())
846 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
848 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
849 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
850 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
852 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
853 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
854 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
856 for (auto VT : { MVT::v8i16, MVT::v16i8 }) {
857 setOperationAction(ISD::SRL, VT, Custom);
858 setOperationAction(ISD::SHL, VT, Custom);
859 setOperationAction(ISD::SRA, VT, Custom);
862 // In the customized shift lowering, the legal cases in AVX2 will be
864 for (auto VT : { MVT::v4i32, MVT::v2i64 }) {
865 setOperationAction(ISD::SRL, VT, Custom);
866 setOperationAction(ISD::SHL, VT, Custom);
867 setOperationAction(ISD::SRA, VT, Custom);
871 if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
872 setOperationAction(ISD::BITREVERSE, MVT::v16i8, Custom);
873 setOperationAction(ISD::CTLZ, MVT::v16i8, Custom);
874 setOperationAction(ISD::CTLZ, MVT::v8i16, Custom);
875 // ISD::CTLZ v4i32 - scalarization is faster.
876 // ISD::CTLZ v2i64 - scalarization is faster.
879 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
880 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
881 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
882 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
883 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
884 setOperationAction(ISD::FRINT, RoundedTy, Legal);
885 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
888 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
889 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
890 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
891 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
892 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
893 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
894 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
895 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
897 // FIXME: Do we need to handle scalar-to-vector here?
898 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
900 // We directly match byte blends in the backend as they match the VSELECT
902 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
904 // SSE41 brings specific instructions for doing vector sign extend even in
905 // cases where we don't have SRA.
906 for (MVT VT : MVT::integer_vector_valuetypes()) {
907 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
908 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
909 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
912 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
913 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
914 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
915 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
916 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
917 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
918 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
920 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
921 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
922 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
923 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
924 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
925 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
927 // i8 vectors are custom because the source register and source
928 // source memory operand types are not the same width.
929 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
932 if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
933 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
934 MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
935 setOperationAction(ISD::ROTL, VT, Custom);
937 // XOP can efficiently perform BITREVERSE with VPPERM.
938 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
939 setOperationAction(ISD::BITREVERSE, VT, Custom);
941 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
942 MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
943 setOperationAction(ISD::BITREVERSE, VT, Custom);
946 if (!Subtarget.useSoftFloat() && Subtarget.hasFp256()) {
947 bool HasInt256 = Subtarget.hasInt256();
949 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
950 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
951 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
952 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
953 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
954 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
956 for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
957 setOperationAction(ISD::FFLOOR, VT, Legal);
958 setOperationAction(ISD::FCEIL, VT, Legal);
959 setOperationAction(ISD::FTRUNC, VT, Legal);
960 setOperationAction(ISD::FRINT, VT, Legal);
961 setOperationAction(ISD::FNEARBYINT, VT, Legal);
962 setOperationAction(ISD::FNEG, VT, Custom);
963 setOperationAction(ISD::FABS, VT, Custom);
966 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
967 // even though v8i16 is a legal type.
968 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
969 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
970 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
972 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
973 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
974 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
976 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
977 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
979 for (MVT VT : MVT::fp_vector_valuetypes())
980 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
982 for (auto VT : { MVT::v32i8, MVT::v16i16 }) {
983 setOperationAction(ISD::SRL, VT, Custom);
984 setOperationAction(ISD::SHL, VT, Custom);
985 setOperationAction(ISD::SRA, VT, Custom);
988 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
989 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
990 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
991 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
993 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
994 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
995 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
997 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
998 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
999 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1000 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1001 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1002 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1003 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1004 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1005 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1006 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1007 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1008 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1009 setOperationAction(ISD::BITREVERSE, MVT::v32i8, Custom);
1011 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1012 setOperationAction(ISD::CTPOP, VT, Custom);
1013 setOperationAction(ISD::CTTZ, VT, Custom);
1016 // ISD::CTLZ v8i32/v4i64 - scalarization is faster without AVX2
1017 // as we end up splitting the 256-bit vectors.
1018 for (auto VT : { MVT::v32i8, MVT::v16i16 })
1019 setOperationAction(ISD::CTLZ, VT, Custom);
1022 for (auto VT : { MVT::v8i32, MVT::v4i64 })
1023 setOperationAction(ISD::CTLZ, VT, Custom);
1025 if (Subtarget.hasAnyFMA()) {
1026 for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1027 MVT::v2f64, MVT::v4f64 })
1028 setOperationAction(ISD::FMA, VT, Legal);
1031 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1032 setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1033 setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1036 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1037 setOperationAction(ISD::MUL, MVT::v8i32, HasInt256 ? Legal : Custom);
1038 setOperationAction(ISD::MUL, MVT::v16i16, HasInt256 ? Legal : Custom);
1039 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1041 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1042 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1044 setOperationAction(ISD::MULHU, MVT::v16i16, HasInt256 ? Legal : Custom);
1045 setOperationAction(ISD::MULHS, MVT::v16i16, HasInt256 ? Legal : Custom);
1046 setOperationAction(ISD::MULHU, MVT::v32i8, Custom);
1047 setOperationAction(ISD::MULHS, MVT::v32i8, Custom);
1049 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1050 setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1051 setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1052 setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1053 setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1057 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i64, Custom);
1058 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i32, Custom);
1059 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v16i16, Custom);
1061 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1062 // when we have a 256bit-wide blend with immediate.
1063 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1065 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1066 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1067 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1068 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1069 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1070 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1071 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1073 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1074 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1075 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1076 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1077 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1078 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1081 // In the customized shift lowering, the legal cases in AVX2 will be
1083 for (auto VT : { MVT::v8i32, MVT::v4i64 }) {
1084 setOperationAction(ISD::SRL, VT, Custom);
1085 setOperationAction(ISD::SHL, VT, Custom);
1086 setOperationAction(ISD::SRA, VT, Custom);
1089 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1090 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1091 setOperationAction(ISD::MLOAD, VT, Legal);
1092 setOperationAction(ISD::MSTORE, VT, Legal);
1095 // Extract subvector is special because the value type
1096 // (result) is 128-bit but the source is 256-bit wide.
1097 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1098 MVT::v4f32, MVT::v2f64 }) {
1099 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1102 // Custom lower several nodes for 256-bit types.
1103 for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1104 MVT::v8f32, MVT::v4f64 }) {
1105 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1106 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1107 setOperationAction(ISD::VSELECT, VT, Custom);
1108 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1109 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1110 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1111 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1112 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1116 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1118 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1119 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1120 setOperationPromotedToType(ISD::AND, VT, MVT::v4i64);
1121 setOperationPromotedToType(ISD::OR, VT, MVT::v4i64);
1122 setOperationPromotedToType(ISD::XOR, VT, MVT::v4i64);
1123 setOperationPromotedToType(ISD::LOAD, VT, MVT::v4i64);
1124 setOperationPromotedToType(ISD::SELECT, VT, MVT::v4i64);
1128 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1129 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1130 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1131 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1132 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1134 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1135 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1136 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1138 for (MVT VT : MVT::fp_vector_valuetypes())
1139 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1141 for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD, ISD::EXTLOAD}) {
1142 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i8, Legal);
1143 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i16, Legal);
1144 setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1145 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i8, Legal);
1146 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i16, Legal);
1147 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i32, Legal);
1149 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1150 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1151 setOperationAction(ISD::SETCCE, MVT::i1, Custom);
1152 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
1153 setOperationAction(ISD::XOR, MVT::i1, Legal);
1154 setOperationAction(ISD::OR, MVT::i1, Legal);
1155 setOperationAction(ISD::AND, MVT::i1, Legal);
1156 setOperationAction(ISD::SUB, MVT::i1, Custom);
1157 setOperationAction(ISD::ADD, MVT::i1, Custom);
1158 setOperationAction(ISD::MUL, MVT::i1, Custom);
1160 for (MVT VT : {MVT::v2i64, MVT::v4i32, MVT::v8i32, MVT::v4i64, MVT::v8i16,
1161 MVT::v16i8, MVT::v16i16, MVT::v32i8, MVT::v16i32,
1162 MVT::v8i64, MVT::v32i16, MVT::v64i8}) {
1163 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
1164 setLoadExtAction(ISD::SEXTLOAD, VT, MaskVT, Custom);
1165 setLoadExtAction(ISD::ZEXTLOAD, VT, MaskVT, Custom);
1166 setLoadExtAction(ISD::EXTLOAD, VT, MaskVT, Custom);
1167 setTruncStoreAction(VT, MaskVT, Custom);
1170 for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1171 setOperationAction(ISD::FNEG, VT, Custom);
1172 setOperationAction(ISD::FABS, VT, Custom);
1173 setOperationAction(ISD::FMA, VT, Legal);
1176 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1177 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1178 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1179 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1180 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1181 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1182 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1183 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1184 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1185 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1186 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1187 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1188 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1189 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1190 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1191 setOperationAction(ISD::UINT_TO_FP, MVT::v16i1, Custom);
1192 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1193 setOperationAction(ISD::UINT_TO_FP, MVT::v8i1, Custom);
1194 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1195 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1196 setOperationAction(ISD::SINT_TO_FP, MVT::v2i1, Custom);
1197 setOperationAction(ISD::UINT_TO_FP, MVT::v2i1, Custom);
1198 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1199 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1201 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1202 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1203 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1204 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1205 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1206 if (Subtarget.hasVLX()){
1207 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1208 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1209 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1210 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1211 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1213 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1214 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1215 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1216 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1217 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1219 setOperationAction(ISD::MLOAD, MVT::v8i32, Custom);
1220 setOperationAction(ISD::MLOAD, MVT::v8f32, Custom);
1221 setOperationAction(ISD::MSTORE, MVT::v8i32, Custom);
1222 setOperationAction(ISD::MSTORE, MVT::v8f32, Custom);
1224 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1225 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1226 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1227 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i1, Custom);
1228 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i1, Custom);
1229 setOperationAction(ISD::VSELECT, MVT::v8i1, Expand);
1230 setOperationAction(ISD::VSELECT, MVT::v16i1, Expand);
1231 if (Subtarget.hasDQI()) {
1232 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1233 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1234 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1235 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1236 if (Subtarget.hasVLX()) {
1237 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1238 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1239 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1240 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1241 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1242 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1243 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1244 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1247 if (Subtarget.hasVLX()) {
1248 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1249 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1250 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1251 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1252 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1253 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1254 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1255 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1256 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Custom);
1257 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i64, Custom);
1259 // FIXME. This commands are available on SSE/AVX2, add relevant patterns.
1260 setLoadExtAction(ISD::EXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1261 setLoadExtAction(ISD::EXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1262 setLoadExtAction(ISD::EXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1263 setLoadExtAction(ISD::EXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1264 setLoadExtAction(ISD::EXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1265 setLoadExtAction(ISD::EXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1266 setLoadExtAction(ISD::EXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1267 setLoadExtAction(ISD::EXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1268 setLoadExtAction(ISD::EXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1269 setLoadExtAction(ISD::EXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1272 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1273 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1274 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1275 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1276 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1277 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1278 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1279 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1280 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1281 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1282 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1283 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1284 if (Subtarget.hasDQI()) {
1285 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1286 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1288 for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1289 setOperationAction(ISD::FFLOOR, VT, Legal);
1290 setOperationAction(ISD::FCEIL, VT, Legal);
1291 setOperationAction(ISD::FTRUNC, VT, Legal);
1292 setOperationAction(ISD::FRINT, VT, Legal);
1293 setOperationAction(ISD::FNEARBYINT, VT, Legal);
1296 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1297 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1298 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1299 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1300 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Custom);
1302 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1303 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1305 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1307 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1308 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1309 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v16i1, Custom);
1310 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1311 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1312 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1313 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1314 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1315 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1316 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1317 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1318 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1320 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1321 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1322 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1323 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1324 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1325 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1326 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1327 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1329 setOperationAction(ISD::ADD, MVT::v8i1, Expand);
1330 setOperationAction(ISD::ADD, MVT::v16i1, Expand);
1331 setOperationAction(ISD::SUB, MVT::v8i1, Expand);
1332 setOperationAction(ISD::SUB, MVT::v16i1, Expand);
1333 setOperationAction(ISD::MUL, MVT::v8i1, Expand);
1334 setOperationAction(ISD::MUL, MVT::v16i1, Expand);
1336 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1338 for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1339 setOperationAction(ISD::SRL, VT, Custom);
1340 setOperationAction(ISD::SHL, VT, Custom);
1341 setOperationAction(ISD::SRA, VT, Custom);
1342 setOperationAction(ISD::AND, VT, Legal);
1343 setOperationAction(ISD::OR, VT, Legal);
1344 setOperationAction(ISD::XOR, VT, Legal);
1345 setOperationAction(ISD::CTPOP, VT, Custom);
1346 setOperationAction(ISD::CTTZ, VT, Custom);
1349 if (Subtarget.hasCDI()) {
1350 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1351 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1353 setOperationAction(ISD::CTLZ, MVT::v8i16, Custom);
1354 setOperationAction(ISD::CTLZ, MVT::v16i8, Custom);
1355 setOperationAction(ISD::CTLZ, MVT::v16i16, Custom);
1356 setOperationAction(ISD::CTLZ, MVT::v32i8, Custom);
1358 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i64, Custom);
1359 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i32, Custom);
1361 if (Subtarget.hasVLX()) {
1362 setOperationAction(ISD::CTLZ, MVT::v4i64, Legal);
1363 setOperationAction(ISD::CTLZ, MVT::v8i32, Legal);
1364 setOperationAction(ISD::CTLZ, MVT::v2i64, Legal);
1365 setOperationAction(ISD::CTLZ, MVT::v4i32, Legal);
1367 setOperationAction(ISD::CTLZ, MVT::v4i64, Custom);
1368 setOperationAction(ISD::CTLZ, MVT::v8i32, Custom);
1369 setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
1370 setOperationAction(ISD::CTLZ, MVT::v4i32, Custom);
1373 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i64, Custom);
1374 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i32, Custom);
1375 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
1376 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
1377 } // Subtarget.hasCDI()
1379 if (Subtarget.hasDQI()) {
1380 if (Subtarget.hasVLX()) {
1381 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1382 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1384 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1386 // Custom lower several nodes.
1387 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1388 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1389 setOperationAction(ISD::MGATHER, VT, Custom);
1390 setOperationAction(ISD::MSCATTER, VT, Custom);
1392 // Extract subvector is special because the value type
1393 // (result) is 256-bit but the source is 512-bit wide.
1394 // 128-bit was made Custom under AVX1.
1395 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1396 MVT::v8f32, MVT::v4f64 })
1397 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1398 for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1,
1399 MVT::v16i1, MVT::v32i1, MVT::v64i1 })
1400 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1402 for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1403 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1404 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1405 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1406 setOperationAction(ISD::VSELECT, VT, Legal);
1407 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1408 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1409 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1410 setOperationAction(ISD::MLOAD, VT, Legal);
1411 setOperationAction(ISD::MSTORE, VT, Legal);
1412 setOperationAction(ISD::MGATHER, VT, Legal);
1413 setOperationAction(ISD::MSCATTER, VT, Custom);
1415 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1416 setOperationPromotedToType(ISD::SELECT, VT, MVT::v8i64);
1420 if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1421 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1422 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1424 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1425 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1427 setOperationAction(ISD::ADD, MVT::v32i1, Expand);
1428 setOperationAction(ISD::ADD, MVT::v64i1, Expand);
1429 setOperationAction(ISD::SUB, MVT::v32i1, Expand);
1430 setOperationAction(ISD::SUB, MVT::v64i1, Expand);
1431 setOperationAction(ISD::MUL, MVT::v32i1, Expand);
1432 setOperationAction(ISD::MUL, MVT::v64i1, Expand);
1434 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1435 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1436 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1437 setOperationAction(ISD::MUL, MVT::v64i8, Custom);
1438 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1439 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1440 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1441 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1442 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i16, Custom);
1443 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i8, Custom);
1444 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1445 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1446 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i16, Custom);
1447 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i8, Custom);
1448 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1449 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1450 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i16, Custom);
1451 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v64i8, Custom);
1452 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1453 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1454 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1455 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1456 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1457 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1458 setOperationAction(ISD::ANY_EXTEND, MVT::v32i16, Custom);
1459 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i16, Custom);
1460 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i8, Custom);
1461 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1462 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1463 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1464 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1465 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i16, Custom);
1466 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i8, Custom);
1467 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1468 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1469 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1470 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1471 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1472 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i1, Custom);
1473 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i1, Custom);
1474 setOperationAction(ISD::BUILD_VECTOR, MVT::v32i1, Custom);
1475 setOperationAction(ISD::BUILD_VECTOR, MVT::v64i1, Custom);
1476 setOperationAction(ISD::VSELECT, MVT::v32i1, Expand);
1477 setOperationAction(ISD::VSELECT, MVT::v64i1, Expand);
1478 setOperationAction(ISD::BITREVERSE, MVT::v64i8, Custom);
1480 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1481 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1482 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1483 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1484 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1485 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1486 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1487 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1489 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1490 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1491 if (Subtarget.hasVLX())
1492 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1494 LegalizeAction Action = Subtarget.hasVLX() ? Legal : Custom;
1495 for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
1496 setOperationAction(ISD::MLOAD, VT, Action);
1497 setOperationAction(ISD::MSTORE, VT, Action);
1500 if (Subtarget.hasCDI()) {
1501 setOperationAction(ISD::CTLZ, MVT::v32i16, Custom);
1502 setOperationAction(ISD::CTLZ, MVT::v64i8, Custom);
1505 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1506 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1507 setOperationAction(ISD::VSELECT, VT, Legal);
1508 setOperationAction(ISD::SRL, VT, Custom);
1509 setOperationAction(ISD::SHL, VT, Custom);
1510 setOperationAction(ISD::SRA, VT, Custom);
1511 setOperationAction(ISD::MLOAD, VT, Legal);
1512 setOperationAction(ISD::MSTORE, VT, Legal);
1513 setOperationAction(ISD::CTPOP, VT, Custom);
1514 setOperationAction(ISD::CTTZ, VT, Custom);
1516 setOperationPromotedToType(ISD::AND, VT, MVT::v8i64);
1517 setOperationPromotedToType(ISD::OR, VT, MVT::v8i64);
1518 setOperationPromotedToType(ISD::XOR, VT, MVT::v8i64);
1521 for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD, ISD::EXTLOAD}) {
1522 setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1523 if (Subtarget.hasVLX()) {
1524 // FIXME. This commands are available on SSE/AVX2, add relevant patterns.
1525 setLoadExtAction(ExtType, MVT::v16i16, MVT::v16i8, Legal);
1526 setLoadExtAction(ExtType, MVT::v8i16, MVT::v8i8, Legal);
1531 if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
1532 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1533 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1535 setOperationAction(ISD::ADD, MVT::v2i1, Expand);
1536 setOperationAction(ISD::ADD, MVT::v4i1, Expand);
1537 setOperationAction(ISD::SUB, MVT::v2i1, Expand);
1538 setOperationAction(ISD::SUB, MVT::v4i1, Expand);
1539 setOperationAction(ISD::MUL, MVT::v2i1, Expand);
1540 setOperationAction(ISD::MUL, MVT::v4i1, Expand);
1542 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1543 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1544 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1545 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1546 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1547 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1548 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1549 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1550 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1551 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1552 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1553 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1554 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i1, Custom);
1555 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i1, Custom);
1556 setOperationAction(ISD::VSELECT, MVT::v2i1, Expand);
1557 setOperationAction(ISD::VSELECT, MVT::v4i1, Expand);
1559 for (auto VT : { MVT::v4i32, MVT::v8i32 }) {
1560 setOperationAction(ISD::AND, VT, Legal);
1561 setOperationAction(ISD::OR, VT, Legal);
1562 setOperationAction(ISD::XOR, VT, Legal);
1565 for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1566 setOperationAction(ISD::SMAX, VT, Legal);
1567 setOperationAction(ISD::UMAX, VT, Legal);
1568 setOperationAction(ISD::SMIN, VT, Legal);
1569 setOperationAction(ISD::UMIN, VT, Legal);
1573 // We want to custom lower some of our intrinsics.
1574 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1575 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1576 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1577 if (!Subtarget.is64Bit()) {
1578 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1579 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1582 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1583 // handle type legalization for these operations here.
1585 // FIXME: We really should do custom legalization for addition and
1586 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1587 // than generic legalization for 64-bit multiplication-with-overflow, though.
1588 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1589 if (VT == MVT::i64 && !Subtarget.is64Bit())
1591 // Add/Sub/Mul with overflow operations are custom lowered.
1592 setOperationAction(ISD::SADDO, VT, Custom);
1593 setOperationAction(ISD::UADDO, VT, Custom);
1594 setOperationAction(ISD::SSUBO, VT, Custom);
1595 setOperationAction(ISD::USUBO, VT, Custom);
1596 setOperationAction(ISD::SMULO, VT, Custom);
1597 setOperationAction(ISD::UMULO, VT, Custom);
1600 if (!Subtarget.is64Bit()) {
1601 // These libcalls are not available in 32-bit.
1602 setLibcallName(RTLIB::SHL_I128, nullptr);
1603 setLibcallName(RTLIB::SRL_I128, nullptr);
1604 setLibcallName(RTLIB::SRA_I128, nullptr);
1607 // Combine sin / cos into one node or libcall if possible.
1608 if (Subtarget.hasSinCos()) {
1609 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1610 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1611 if (Subtarget.isTargetDarwin()) {
1612 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1613 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1614 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1615 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1619 if (Subtarget.isTargetWin64()) {
1620 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1621 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1622 setOperationAction(ISD::SREM, MVT::i128, Custom);
1623 setOperationAction(ISD::UREM, MVT::i128, Custom);
1624 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1625 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1628 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
1629 // is. We should promote the value to 64-bits to solve this.
1630 // This is what the CRT headers do - `fmodf` is an inline header
1631 // function casting to f64 and calling `fmod`.
1632 if (Subtarget.is32Bit() && Subtarget.isTargetKnownWindowsMSVC())
1633 for (ISD::NodeType Op :
1634 {ISD::FCEIL, ISD::FCOS, ISD::FEXP, ISD::FFLOOR, ISD::FREM, ISD::FLOG,
1635 ISD::FLOG10, ISD::FPOW, ISD::FSIN})
1636 if (isOperationExpand(Op, MVT::f32))
1637 setOperationAction(Op, MVT::f32, Promote);
1639 // We have target-specific dag combine patterns for the following nodes:
1640 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1641 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1642 setTargetDAGCombine(ISD::BITCAST);
1643 setTargetDAGCombine(ISD::VSELECT);
1644 setTargetDAGCombine(ISD::SELECT);
1645 setTargetDAGCombine(ISD::SHL);
1646 setTargetDAGCombine(ISD::SRA);
1647 setTargetDAGCombine(ISD::SRL);
1648 setTargetDAGCombine(ISD::OR);
1649 setTargetDAGCombine(ISD::AND);
1650 setTargetDAGCombine(ISD::ADD);
1651 setTargetDAGCombine(ISD::FADD);
1652 setTargetDAGCombine(ISD::FSUB);
1653 setTargetDAGCombine(ISD::FNEG);
1654 setTargetDAGCombine(ISD::FMA);
1655 setTargetDAGCombine(ISD::FMINNUM);
1656 setTargetDAGCombine(ISD::FMAXNUM);
1657 setTargetDAGCombine(ISD::SUB);
1658 setTargetDAGCombine(ISD::LOAD);
1659 setTargetDAGCombine(ISD::MLOAD);
1660 setTargetDAGCombine(ISD::STORE);
1661 setTargetDAGCombine(ISD::MSTORE);
1662 setTargetDAGCombine(ISD::TRUNCATE);
1663 setTargetDAGCombine(ISD::ZERO_EXTEND);
1664 setTargetDAGCombine(ISD::ANY_EXTEND);
1665 setTargetDAGCombine(ISD::SIGN_EXTEND);
1666 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1667 setTargetDAGCombine(ISD::SINT_TO_FP);
1668 setTargetDAGCombine(ISD::UINT_TO_FP);
1669 setTargetDAGCombine(ISD::SETCC);
1670 setTargetDAGCombine(ISD::MUL);
1671 setTargetDAGCombine(ISD::XOR);
1672 setTargetDAGCombine(ISD::MSCATTER);
1673 setTargetDAGCombine(ISD::MGATHER);
1675 computeRegisterProperties(Subtarget.getRegisterInfo());
1677 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1678 MaxStoresPerMemsetOptSize = 8;
1679 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1680 MaxStoresPerMemcpyOptSize = 4;
1681 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1682 MaxStoresPerMemmoveOptSize = 4;
1683 setPrefLoopAlignment(4); // 2^4 bytes.
1685 // An out-of-order CPU can speculatively execute past a predictable branch,
1686 // but a conditional move could be stalled by an expensive earlier operation.
1687 PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
1688 EnableExtLdPromotion = true;
1689 setPrefFunctionAlignment(4); // 2^4 bytes.
1691 verifyIntrinsicTables();
1694 // This has so far only been implemented for 64-bit MachO.
1695 bool X86TargetLowering::useLoadStackGuardNode() const {
1696 return Subtarget.isTargetMachO() && Subtarget.is64Bit();
1699 TargetLoweringBase::LegalizeTypeAction
1700 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1701 if (ExperimentalVectorWideningLegalization &&
1702 VT.getVectorNumElements() != 1 &&
1703 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1704 return TypeWidenVector;
1706 return TargetLoweringBase::getPreferredVectorAction(VT);
1709 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL,
1710 LLVMContext& Context,
1713 return Subtarget.hasAVX512() ? MVT::i1: MVT::i8;
1715 if (VT.isSimple()) {
1716 MVT VVT = VT.getSimpleVT();
1717 const unsigned NumElts = VVT.getVectorNumElements();
1718 MVT EltVT = VVT.getVectorElementType();
1719 if (VVT.is512BitVector()) {
1720 if (Subtarget.hasAVX512())
1721 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1722 EltVT == MVT::f32 || EltVT == MVT::f64)
1724 case 8: return MVT::v8i1;
1725 case 16: return MVT::v16i1;
1727 if (Subtarget.hasBWI())
1728 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1730 case 32: return MVT::v32i1;
1731 case 64: return MVT::v64i1;
1735 if (Subtarget.hasBWI() && Subtarget.hasVLX())
1736 return MVT::getVectorVT(MVT::i1, NumElts);
1738 if (!isTypeLegal(VT) && getTypeAction(Context, VT) == TypePromoteInteger) {
1739 EVT LegalVT = getTypeToTransformTo(Context, VT);
1740 EltVT = LegalVT.getVectorElementType().getSimpleVT();
1743 if (Subtarget.hasVLX() && EltVT.getSizeInBits() >= 32)
1745 case 2: return MVT::v2i1;
1746 case 4: return MVT::v4i1;
1747 case 8: return MVT::v8i1;
1751 return VT.changeVectorElementTypeToInteger();
1754 /// Helper for getByValTypeAlignment to determine
1755 /// the desired ByVal argument alignment.
1756 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1759 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1760 if (VTy->getBitWidth() == 128)
1762 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1763 unsigned EltAlign = 0;
1764 getMaxByValAlign(ATy->getElementType(), EltAlign);
1765 if (EltAlign > MaxAlign)
1766 MaxAlign = EltAlign;
1767 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1768 for (auto *EltTy : STy->elements()) {
1769 unsigned EltAlign = 0;
1770 getMaxByValAlign(EltTy, EltAlign);
1771 if (EltAlign > MaxAlign)
1772 MaxAlign = EltAlign;
1779 /// Return the desired alignment for ByVal aggregate
1780 /// function arguments in the caller parameter area. For X86, aggregates
1781 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1782 /// are at 4-byte boundaries.
1783 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1784 const DataLayout &DL) const {
1785 if (Subtarget.is64Bit()) {
1786 // Max of 8 and alignment of type.
1787 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1794 if (Subtarget.hasSSE1())
1795 getMaxByValAlign(Ty, Align);
1799 /// Returns the target specific optimal type for load
1800 /// and store operations as a result of memset, memcpy, and memmove
1801 /// lowering. If DstAlign is zero that means it's safe to destination
1802 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1803 /// means there isn't a need to check it against alignment requirement,
1804 /// probably because the source does not need to be loaded. If 'IsMemset' is
1805 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1806 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1807 /// source is constant so it does not need to be loaded.
1808 /// It returns EVT::Other if the type should be determined using generic
1809 /// target-independent logic.
1811 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1812 unsigned DstAlign, unsigned SrcAlign,
1813 bool IsMemset, bool ZeroMemset,
1815 MachineFunction &MF) const {
1816 const Function *F = MF.getFunction();
1817 if (!F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1819 (!Subtarget.isUnalignedMem16Slow() ||
1820 ((DstAlign == 0 || DstAlign >= 16) &&
1821 (SrcAlign == 0 || SrcAlign >= 16)))) {
1822 // FIXME: Check if unaligned 32-byte accesses are slow.
1823 if (Size >= 32 && Subtarget.hasAVX()) {
1824 // Although this isn't a well-supported type for AVX1, we'll let
1825 // legalization and shuffle lowering produce the optimal codegen. If we
1826 // choose an optimal type with a vector element larger than a byte,
1827 // getMemsetStores() may create an intermediate splat (using an integer
1828 // multiply) before we splat as a vector.
1831 if (Subtarget.hasSSE2())
1833 // TODO: Can SSE1 handle a byte vector?
1834 if (Subtarget.hasSSE1())
1836 } else if ((!IsMemset || ZeroMemset) && !MemcpyStrSrc && Size >= 8 &&
1837 !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
1838 // Do not use f64 to lower memcpy if source is string constant. It's
1839 // better to use i32 to avoid the loads.
1840 // Also, do not use f64 to lower memset unless this is a memset of zeros.
1841 // The gymnastics of splatting a byte value into an XMM register and then
1842 // only using 8-byte stores (because this is a CPU with slow unaligned
1843 // 16-byte accesses) makes that a loser.
1847 // This is a compromise. If we reach here, unaligned accesses may be slow on
1848 // this target. However, creating smaller, aligned accesses could be even
1849 // slower and would certainly be a lot more code.
1850 if (Subtarget.is64Bit() && Size >= 8)
1855 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1857 return X86ScalarSSEf32;
1858 else if (VT == MVT::f64)
1859 return X86ScalarSSEf64;
1864 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1869 switch (VT.getSizeInBits()) {
1871 // 8-byte and under are always assumed to be fast.
1875 *Fast = !Subtarget.isUnalignedMem16Slow();
1878 *Fast = !Subtarget.isUnalignedMem32Slow();
1880 // TODO: What about AVX-512 (512-bit) accesses?
1883 // Misaligned accesses of any size are always allowed.
1887 /// Return the entry encoding for a jump table in the
1888 /// current function. The returned value is a member of the
1889 /// MachineJumpTableInfo::JTEntryKind enum.
1890 unsigned X86TargetLowering::getJumpTableEncoding() const {
1891 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1893 if (isPositionIndependent() && Subtarget.isPICStyleGOT())
1894 return MachineJumpTableInfo::EK_Custom32;
1896 // Otherwise, use the normal jump table encoding heuristics.
1897 return TargetLowering::getJumpTableEncoding();
1900 bool X86TargetLowering::useSoftFloat() const {
1901 return Subtarget.useSoftFloat();
1905 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1906 const MachineBasicBlock *MBB,
1907 unsigned uid,MCContext &Ctx) const{
1908 assert(isPositionIndependent() && Subtarget.isPICStyleGOT());
1909 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1911 return MCSymbolRefExpr::create(MBB->getSymbol(),
1912 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1915 /// Returns relocation base for the given PIC jumptable.
1916 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1917 SelectionDAG &DAG) const {
1918 if (!Subtarget.is64Bit())
1919 // This doesn't have SDLoc associated with it, but is not really the
1920 // same as a Register.
1921 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1922 getPointerTy(DAG.getDataLayout()));
1926 /// This returns the relocation base for the given PIC jumptable,
1927 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1928 const MCExpr *X86TargetLowering::
1929 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1930 MCContext &Ctx) const {
1931 // X86-64 uses RIP relative addressing based on the jump table label.
1932 if (Subtarget.isPICStyleRIPRel())
1933 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1935 // Otherwise, the reference is relative to the PIC base.
1936 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1939 std::pair<const TargetRegisterClass *, uint8_t>
1940 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1942 const TargetRegisterClass *RRC = nullptr;
1944 switch (VT.SimpleTy) {
1946 return TargetLowering::findRepresentativeClass(TRI, VT);
1947 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1948 RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1951 RRC = &X86::VR64RegClass;
1953 case MVT::f32: case MVT::f64:
1954 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1955 case MVT::v4f32: case MVT::v2f64:
1956 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1958 RRC = &X86::VR128RegClass;
1961 return std::make_pair(RRC, Cost);
1964 unsigned X86TargetLowering::getAddressSpace() const {
1965 if (Subtarget.is64Bit())
1966 return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
1970 Value *X86TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
1971 // glibc has a special slot for the stack guard in tcbhead_t, use it instead
1972 // of the usual global variable (see sysdeps/{i386,x86_64}/nptl/tls.h)
1973 if (!Subtarget.isTargetGlibc())
1974 return TargetLowering::getIRStackGuard(IRB);
1976 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1978 unsigned Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
1979 unsigned AddressSpace = getAddressSpace();
1980 return ConstantExpr::getIntToPtr(
1981 ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
1982 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
1985 void X86TargetLowering::insertSSPDeclarations(Module &M) const {
1986 // MSVC CRT provides functionalities for stack protection.
1987 if (Subtarget.getTargetTriple().isOSMSVCRT()) {
1988 // MSVC CRT has a global variable holding security cookie.
1989 M.getOrInsertGlobal("__security_cookie",
1990 Type::getInt8PtrTy(M.getContext()));
1992 // MSVC CRT has a function to validate security cookie.
1993 auto *SecurityCheckCookie = cast<Function>(
1994 M.getOrInsertFunction("__security_check_cookie",
1995 Type::getVoidTy(M.getContext()),
1996 Type::getInt8PtrTy(M.getContext()), nullptr));
1997 SecurityCheckCookie->setCallingConv(CallingConv::X86_FastCall);
1998 SecurityCheckCookie->addAttribute(1, Attribute::AttrKind::InReg);
2001 // glibc has a special slot for the stack guard.
2002 if (Subtarget.isTargetGlibc())
2004 TargetLowering::insertSSPDeclarations(M);
2007 Value *X86TargetLowering::getSDagStackGuard(const Module &M) const {
2008 // MSVC CRT has a global variable holding security cookie.
2009 if (Subtarget.getTargetTriple().isOSMSVCRT())
2010 return M.getGlobalVariable("__security_cookie");
2011 return TargetLowering::getSDagStackGuard(M);
2014 Value *X86TargetLowering::getSSPStackGuardCheck(const Module &M) const {
2015 // MSVC CRT has a function to validate security cookie.
2016 if (Subtarget.getTargetTriple().isOSMSVCRT())
2017 return M.getFunction("__security_check_cookie");
2018 return TargetLowering::getSSPStackGuardCheck(M);
2021 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2022 if (!Subtarget.isTargetAndroid())
2023 return TargetLowering::getSafeStackPointerLocation(IRB);
2025 // Android provides a fixed TLS slot for the SafeStack pointer. See the
2026 // definition of TLS_SLOT_SAFESTACK in
2027 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2028 unsigned AddressSpace, Offset;
2030 // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2032 Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
2033 AddressSpace = getAddressSpace();
2034 return ConstantExpr::getIntToPtr(
2035 ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2036 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2039 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2040 unsigned DestAS) const {
2041 assert(SrcAS != DestAS && "Expected different address spaces!");
2043 return SrcAS < 256 && DestAS < 256;
2046 //===----------------------------------------------------------------------===//
2047 // Return Value Calling Convention Implementation
2048 //===----------------------------------------------------------------------===//
2050 #include "X86GenCallingConv.inc"
2052 bool X86TargetLowering::CanLowerReturn(
2053 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2054 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2055 SmallVector<CCValAssign, 16> RVLocs;
2056 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2057 return CCInfo.CheckReturn(Outs, RetCC_X86);
2060 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2061 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2066 X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2068 const SmallVectorImpl<ISD::OutputArg> &Outs,
2069 const SmallVectorImpl<SDValue> &OutVals,
2070 const SDLoc &dl, SelectionDAG &DAG) const {
2071 MachineFunction &MF = DAG.getMachineFunction();
2072 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2074 if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2075 report_fatal_error("X86 interrupts may not return any value");
2077 SmallVector<CCValAssign, 16> RVLocs;
2078 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2079 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2082 SmallVector<SDValue, 6> RetOps;
2083 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2084 // Operand #1 = Bytes To Pop
2085 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2088 // Copy the result values into the output registers.
2089 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2090 CCValAssign &VA = RVLocs[i];
2091 assert(VA.isRegLoc() && "Can only return in registers!");
2092 SDValue ValToCopy = OutVals[i];
2093 EVT ValVT = ValToCopy.getValueType();
2095 // Promote values to the appropriate types.
2096 if (VA.getLocInfo() == CCValAssign::SExt)
2097 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2098 else if (VA.getLocInfo() == CCValAssign::ZExt)
2099 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2100 else if (VA.getLocInfo() == CCValAssign::AExt) {
2101 if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2102 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2104 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2106 else if (VA.getLocInfo() == CCValAssign::BCvt)
2107 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2109 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2110 "Unexpected FP-extend for return value.");
2112 // If this is x86-64, and we disabled SSE, we can't return FP values,
2113 // or SSE or MMX vectors.
2114 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2115 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2116 (Subtarget.is64Bit() && !Subtarget.hasSSE1())) {
2117 report_fatal_error("SSE register return with SSE disabled");
2119 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2120 // llvm-gcc has never done it right and no one has noticed, so this
2121 // should be OK for now.
2122 if (ValVT == MVT::f64 &&
2123 (Subtarget.is64Bit() && !Subtarget.hasSSE2()))
2124 report_fatal_error("SSE2 register return with SSE2 disabled");
2126 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2127 // the RET instruction and handled by the FP Stackifier.
2128 if (VA.getLocReg() == X86::FP0 ||
2129 VA.getLocReg() == X86::FP1) {
2130 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2131 // change the value to the FP stack register class.
2132 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2133 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2134 RetOps.push_back(ValToCopy);
2135 // Don't emit a copytoreg.
2139 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2140 // which is returned in RAX / RDX.
2141 if (Subtarget.is64Bit()) {
2142 if (ValVT == MVT::x86mmx) {
2143 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2144 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2145 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2147 // If we don't have SSE2 available, convert to v4f32 so the generated
2148 // register is legal.
2149 if (!Subtarget.hasSSE2())
2150 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2155 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2156 Flag = Chain.getValue(1);
2157 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2160 // Swift calling convention does not require we copy the sret argument
2161 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
2163 // All x86 ABIs require that for returning structs by value we copy
2164 // the sret argument into %rax/%eax (depending on ABI) for the return.
2165 // We saved the argument into a virtual register in the entry block,
2166 // so now we copy the value out and into %rax/%eax.
2168 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2169 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2170 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2171 // either case FuncInfo->setSRetReturnReg() will have been called.
2172 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2173 // When we have both sret and another return value, we should use the
2174 // original Chain stored in RetOps[0], instead of the current Chain updated
2175 // in the above loop. If we only have sret, RetOps[0] equals to Chain.
2177 // For the case of sret and another return value, we have
2178 // Chain_0 at the function entry
2179 // Chain_1 = getCopyToReg(Chain_0) in the above loop
2180 // If we use Chain_1 in getCopyFromReg, we will have
2181 // Val = getCopyFromReg(Chain_1)
2182 // Chain_2 = getCopyToReg(Chain_1, Val) from below
2184 // getCopyToReg(Chain_0) will be glued together with
2185 // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
2186 // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
2187 // Data dependency from Unit B to Unit A due to usage of Val in
2188 // getCopyToReg(Chain_1, Val)
2189 // Chain dependency from Unit A to Unit B
2191 // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
2192 SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
2193 getPointerTy(MF.getDataLayout()));
2196 = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
2197 X86::RAX : X86::EAX;
2198 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2199 Flag = Chain.getValue(1);
2201 // RAX/EAX now acts like a return value.
2203 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2206 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
2207 const MCPhysReg *I =
2208 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2211 if (X86::GR64RegClass.contains(*I))
2212 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2214 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2218 RetOps[0] = Chain; // Update chain.
2220 // Add the flag if we have it.
2222 RetOps.push_back(Flag);
2224 X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2225 if (CallConv == CallingConv::X86_INTR)
2226 opcode = X86ISD::IRET;
2227 return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2230 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2231 if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
2234 SDValue TCChain = Chain;
2235 SDNode *Copy = *N->use_begin();
2236 if (Copy->getOpcode() == ISD::CopyToReg) {
2237 // If the copy has a glue operand, we conservatively assume it isn't safe to
2238 // perform a tail call.
2239 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2241 TCChain = Copy->getOperand(0);
2242 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2245 bool HasRet = false;
2246 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2248 if (UI->getOpcode() != X86ISD::RET_FLAG)
2250 // If we are returning more than one value, we can definitely
2251 // not make a tail call see PR19530
2252 if (UI->getNumOperands() > 4)
2254 if (UI->getNumOperands() == 4 &&
2255 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2267 EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
2268 ISD::NodeType ExtendKind) const {
2269 MVT ReturnMVT = MVT::i32;
2271 bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
2272 if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
2273 // The ABI does not require i1, i8 or i16 to be extended.
2275 // On Darwin, there is code in the wild relying on Clang's old behaviour of
2276 // always extending i8/i16 return values, so keep doing that for now.
2278 ReturnMVT = MVT::i8;
2281 EVT MinVT = getRegisterType(Context, ReturnMVT);
2282 return VT.bitsLT(MinVT) ? MinVT : VT;
2285 /// Lower the result values of a call into the
2286 /// appropriate copies out of appropriate physical registers.
2288 SDValue X86TargetLowering::LowerCallResult(
2289 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2290 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2291 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2293 // Assign locations to each value returned by this call.
2294 SmallVector<CCValAssign, 16> RVLocs;
2295 bool Is64Bit = Subtarget.is64Bit();
2296 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2298 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2300 // Copy all of the result registers out of their specified physreg.
2301 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2302 CCValAssign &VA = RVLocs[i];
2303 EVT CopyVT = VA.getLocVT();
2305 // If this is x86-64, and we disabled SSE, we can't return FP values
2306 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2307 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget.hasSSE1())) {
2308 report_fatal_error("SSE register return with SSE disabled");
2311 // If we prefer to use the value in xmm registers, copy it out as f80 and
2312 // use a truncate to move it from fp stack reg to xmm reg.
2313 bool RoundAfterCopy = false;
2314 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2315 isScalarFPTypeInSSEReg(VA.getValVT())) {
2316 if (!Subtarget.hasX87())
2317 report_fatal_error("X87 register return with X87 disabled");
2319 RoundAfterCopy = (CopyVT != VA.getLocVT());
2322 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2323 CopyVT, InFlag).getValue(1);
2324 SDValue Val = Chain.getValue(0);
2327 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2328 // This truncation won't change the value.
2329 DAG.getIntPtrConstant(1, dl));
2331 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2332 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2334 InFlag = Chain.getValue(2);
2335 InVals.push_back(Val);
2341 //===----------------------------------------------------------------------===//
2342 // C & StdCall & Fast Calling Convention implementation
2343 //===----------------------------------------------------------------------===//
2344 // StdCall calling convention seems to be standard for many Windows' API
2345 // routines and around. It differs from C calling convention just a little:
2346 // callee should clean up the stack, not caller. Symbols should be also
2347 // decorated in some fancy way :) It doesn't support any vector arguments.
2348 // For info on fast calling convention see Fast Calling Convention (tail call)
2349 // implementation LowerX86_32FastCCCallTo.
2351 /// CallIsStructReturn - Determines whether a call uses struct return
2353 enum StructReturnType {
2358 static StructReturnType
2359 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsMCU) {
2361 return NotStructReturn;
2363 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2364 if (!Flags.isSRet())
2365 return NotStructReturn;
2366 if (Flags.isInReg() || IsMCU)
2367 return RegStructReturn;
2368 return StackStructReturn;
2371 /// Determines whether a function uses struct return semantics.
2372 static StructReturnType
2373 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsMCU) {
2375 return NotStructReturn;
2377 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2378 if (!Flags.isSRet())
2379 return NotStructReturn;
2380 if (Flags.isInReg() || IsMCU)
2381 return RegStructReturn;
2382 return StackStructReturn;
2385 /// Make a copy of an aggregate at address specified by "Src" to address
2386 /// "Dst" with size and alignment information specified by the specific
2387 /// parameter attribute. The copy will be passed as a byval function parameter.
2388 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
2389 SDValue Chain, ISD::ArgFlagsTy Flags,
2390 SelectionDAG &DAG, const SDLoc &dl) {
2391 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2393 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2394 /*isVolatile*/false, /*AlwaysInline=*/true,
2395 /*isTailCall*/false,
2396 MachinePointerInfo(), MachinePointerInfo());
2399 /// Return true if the calling convention is one that we can guarantee TCO for.
2400 static bool canGuaranteeTCO(CallingConv::ID CC) {
2401 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2402 CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2405 /// Return true if we might ever do TCO for calls with this calling convention.
2406 static bool mayTailCallThisCC(CallingConv::ID CC) {
2408 // C calling conventions:
2409 case CallingConv::C:
2410 case CallingConv::X86_64_Win64:
2411 case CallingConv::X86_64_SysV:
2412 // Callee pop conventions:
2413 case CallingConv::X86_ThisCall:
2414 case CallingConv::X86_StdCall:
2415 case CallingConv::X86_VectorCall:
2416 case CallingConv::X86_FastCall:
2419 return canGuaranteeTCO(CC);
2423 /// Return true if the function is being made into a tailcall target by
2424 /// changing its ABI.
2425 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2426 return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2429 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2431 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2432 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2436 CallingConv::ID CalleeCC = CS.getCallingConv();
2437 if (!mayTailCallThisCC(CalleeCC))
2444 X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
2445 const SmallVectorImpl<ISD::InputArg> &Ins,
2446 const SDLoc &dl, SelectionDAG &DAG,
2447 const CCValAssign &VA,
2448 MachineFrameInfo *MFI, unsigned i) const {
2449 // Create the nodes corresponding to a load from this parameter slot.
2450 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2451 bool AlwaysUseMutable = shouldGuaranteeTCO(
2452 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2453 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2456 // If value is passed by pointer we have address passed instead of the value
2458 bool ExtendedInMem = VA.isExtInLoc() &&
2459 VA.getValVT().getScalarType() == MVT::i1;
2461 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2462 ValVT = VA.getLocVT();
2464 ValVT = VA.getValVT();
2466 // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2467 // taken by a return address.
2469 if (CallConv == CallingConv::X86_INTR) {
2470 const X86Subtarget& Subtarget =
2471 static_cast<const X86Subtarget&>(DAG.getSubtarget());
2472 // X86 interrupts may take one or two arguments.
2473 // On the stack there will be no return address as in regular call.
2474 // Offset of last argument need to be set to -4/-8 bytes.
2475 // Where offset of the first argument out of two, should be set to 0 bytes.
2476 Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2479 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2480 // changed with more analysis.
2481 // In case of tail call optimization mark all arguments mutable. Since they
2482 // could be overwritten by lowering of arguments in case of a tail call.
2483 if (Flags.isByVal()) {
2484 unsigned Bytes = Flags.getByValSize();
2485 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2486 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2487 // Adjust SP offset of interrupt parameter.
2488 if (CallConv == CallingConv::X86_INTR) {
2489 MFI->setObjectOffset(FI, Offset);
2491 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2493 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2494 VA.getLocMemOffset(), isImmutable);
2496 // Set SExt or ZExt flag.
2497 if (VA.getLocInfo() == CCValAssign::ZExt) {
2498 MFI->setObjectZExt(FI, true);
2499 } else if (VA.getLocInfo() == CCValAssign::SExt) {
2500 MFI->setObjectSExt(FI, true);
2503 // Adjust SP offset of interrupt parameter.
2504 if (CallConv == CallingConv::X86_INTR) {
2505 MFI->setObjectOffset(FI, Offset);
2508 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2509 SDValue Val = DAG.getLoad(
2510 ValVT, dl, Chain, FIN,
2511 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
2512 return ExtendedInMem ?
2513 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2517 // FIXME: Get this from tablegen.
2518 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2519 const X86Subtarget &Subtarget) {
2520 assert(Subtarget.is64Bit());
2522 if (Subtarget.isCallingConvWin64(CallConv)) {
2523 static const MCPhysReg GPR64ArgRegsWin64[] = {
2524 X86::RCX, X86::RDX, X86::R8, X86::R9
2526 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2529 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2530 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2532 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2535 // FIXME: Get this from tablegen.
2536 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2537 CallingConv::ID CallConv,
2538 const X86Subtarget &Subtarget) {
2539 assert(Subtarget.is64Bit());
2540 if (Subtarget.isCallingConvWin64(CallConv)) {
2541 // The XMM registers which might contain var arg parameters are shadowed
2542 // in their paired GPR. So we only need to save the GPR to their home
2544 // TODO: __vectorcall will change this.
2548 const Function *Fn = MF.getFunction();
2549 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2550 bool isSoftFloat = Subtarget.useSoftFloat();
2551 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2552 "SSE register cannot be used when SSE is disabled!");
2553 if (isSoftFloat || NoImplicitFloatOps || !Subtarget.hasSSE1())
2554 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2558 static const MCPhysReg XMMArgRegs64Bit[] = {
2559 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2560 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2562 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2565 SDValue X86TargetLowering::LowerFormalArguments(
2566 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2567 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2568 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2569 MachineFunction &MF = DAG.getMachineFunction();
2570 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2571 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
2573 const Function *Fn = MF.getFunction();
2574 if (Fn->hasExternalLinkage() &&
2575 Subtarget.isTargetCygMing() &&
2576 Fn->getName() == "main")
2577 FuncInfo->setForceFramePointer(true);
2579 MachineFrameInfo *MFI = MF.getFrameInfo();
2580 bool Is64Bit = Subtarget.is64Bit();
2581 bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
2583 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2584 "Var args not supported with calling convention fastcc, ghc or hipe");
2586 if (CallConv == CallingConv::X86_INTR) {
2587 bool isLegal = Ins.size() == 1 ||
2588 (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
2589 (!Is64Bit && Ins[1].VT == MVT::i32)));
2591 report_fatal_error("X86 interrupts may take one or two arguments");
2594 // Assign locations to all of the incoming arguments.
2595 SmallVector<CCValAssign, 16> ArgLocs;
2596 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2598 // Allocate shadow area for Win64
2600 CCInfo.AllocateStack(32, 8);
2602 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2604 unsigned LastVal = ~0U;
2606 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2607 CCValAssign &VA = ArgLocs[i];
2608 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2610 assert(VA.getValNo() != LastVal &&
2611 "Don't support value assigned to multiple locs yet");
2613 LastVal = VA.getValNo();
2615 if (VA.isRegLoc()) {
2616 EVT RegVT = VA.getLocVT();
2617 const TargetRegisterClass *RC;
2618 if (RegVT == MVT::i32)
2619 RC = &X86::GR32RegClass;
2620 else if (Is64Bit && RegVT == MVT::i64)
2621 RC = &X86::GR64RegClass;
2622 else if (RegVT == MVT::f32)
2623 RC = &X86::FR32RegClass;
2624 else if (RegVT == MVT::f64)
2625 RC = &X86::FR64RegClass;
2626 else if (RegVT == MVT::f128)
2627 RC = &X86::FR128RegClass;
2628 else if (RegVT.is512BitVector())
2629 RC = &X86::VR512RegClass;
2630 else if (RegVT.is256BitVector())
2631 RC = &X86::VR256RegClass;
2632 else if (RegVT.is128BitVector())
2633 RC = &X86::VR128RegClass;
2634 else if (RegVT == MVT::x86mmx)
2635 RC = &X86::VR64RegClass;
2636 else if (RegVT == MVT::i1)
2637 RC = &X86::VK1RegClass;
2638 else if (RegVT == MVT::v8i1)
2639 RC = &X86::VK8RegClass;
2640 else if (RegVT == MVT::v16i1)
2641 RC = &X86::VK16RegClass;
2642 else if (RegVT == MVT::v32i1)
2643 RC = &X86::VK32RegClass;
2644 else if (RegVT == MVT::v64i1)
2645 RC = &X86::VK64RegClass;
2647 llvm_unreachable("Unknown argument type!");
2649 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2650 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2652 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2653 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2655 if (VA.getLocInfo() == CCValAssign::SExt)
2656 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2657 DAG.getValueType(VA.getValVT()));
2658 else if (VA.getLocInfo() == CCValAssign::ZExt)
2659 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2660 DAG.getValueType(VA.getValVT()));
2661 else if (VA.getLocInfo() == CCValAssign::BCvt)
2662 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2664 if (VA.isExtInLoc()) {
2665 // Handle MMX values passed in XMM regs.
2666 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2667 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2669 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2672 assert(VA.isMemLoc());
2673 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2676 // If value is passed via pointer - do a load.
2677 if (VA.getLocInfo() == CCValAssign::Indirect)
2679 DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
2681 InVals.push_back(ArgValue);
2684 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2685 // Swift calling convention does not require we copy the sret argument
2686 // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
2687 if (CallConv == CallingConv::Swift)
2690 // All x86 ABIs require that for returning structs by value we copy the
2691 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2692 // the argument into a virtual register so that we can access it from the
2694 if (Ins[i].Flags.isSRet()) {
2695 unsigned Reg = FuncInfo->getSRetReturnReg();
2697 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2698 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2699 FuncInfo->setSRetReturnReg(Reg);
2701 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2702 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2707 unsigned StackSize = CCInfo.getNextStackOffset();
2708 // Align stack specially for tail calls.
2709 if (shouldGuaranteeTCO(CallConv,
2710 MF.getTarget().Options.GuaranteedTailCallOpt))
2711 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2713 // If the function takes variable number of arguments, make a frame index for
2714 // the start of the first vararg value... for expansion of llvm.va_start. We
2715 // can skip this if there are no va_start calls.
2716 if (MFI->hasVAStart() &&
2717 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2718 CallConv != CallingConv::X86_ThisCall))) {
2719 FuncInfo->setVarArgsFrameIndex(
2720 MFI->CreateFixedObject(1, StackSize, true));
2723 // Figure out if XMM registers are in use.
2724 assert(!(Subtarget.useSoftFloat() &&
2725 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2726 "SSE register cannot be used when SSE is disabled!");
2728 // 64-bit calling conventions support varargs and register parameters, so we
2729 // have to do extra work to spill them in the prologue.
2730 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2731 // Find the first unallocated argument registers.
2732 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2733 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2734 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2735 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2736 assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&
2737 "SSE register cannot be used when SSE is disabled!");
2739 // Gather all the live in physical registers.
2740 SmallVector<SDValue, 6> LiveGPRs;
2741 SmallVector<SDValue, 8> LiveXMMRegs;
2743 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2744 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2746 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2748 if (!ArgXMMs.empty()) {
2749 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2750 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2751 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2752 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2753 LiveXMMRegs.push_back(
2754 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2759 // Get to the caller-allocated home save location. Add 8 to account
2760 // for the return address.
2761 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2762 FuncInfo->setRegSaveFrameIndex(
2763 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2764 // Fixup to set vararg frame on shadow area (4 x i64).
2766 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2768 // For X86-64, if there are vararg parameters that are passed via
2769 // registers, then we must store them to their spots on the stack so
2770 // they may be loaded by dereferencing the result of va_next.
2771 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2772 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2773 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2774 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2777 // Store the integer parameter registers.
2778 SmallVector<SDValue, 8> MemOps;
2779 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2780 getPointerTy(DAG.getDataLayout()));
2781 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2782 for (SDValue Val : LiveGPRs) {
2783 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2784 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2786 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2787 MachinePointerInfo::getFixedStack(
2788 DAG.getMachineFunction(),
2789 FuncInfo->getRegSaveFrameIndex(), Offset));
2790 MemOps.push_back(Store);
2794 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2795 // Now store the XMM (fp + vector) parameter registers.
2796 SmallVector<SDValue, 12> SaveXMMOps;
2797 SaveXMMOps.push_back(Chain);
2798 SaveXMMOps.push_back(ALVal);
2799 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2800 FuncInfo->getRegSaveFrameIndex(), dl));
2801 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2802 FuncInfo->getVarArgsFPOffset(), dl));
2803 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2805 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2806 MVT::Other, SaveXMMOps));
2809 if (!MemOps.empty())
2810 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2813 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2814 // Find the largest legal vector type.
2815 MVT VecVT = MVT::Other;
2816 // FIXME: Only some x86_32 calling conventions support AVX512.
2817 if (Subtarget.hasAVX512() &&
2818 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2819 CallConv == CallingConv::Intel_OCL_BI)))
2820 VecVT = MVT::v16f32;
2821 else if (Subtarget.hasAVX())
2823 else if (Subtarget.hasSSE2())
2826 // We forward some GPRs and some vector types.
2827 SmallVector<MVT, 2> RegParmTypes;
2828 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2829 RegParmTypes.push_back(IntVT);
2830 if (VecVT != MVT::Other)
2831 RegParmTypes.push_back(VecVT);
2833 // Compute the set of forwarded registers. The rest are scratch.
2834 SmallVectorImpl<ForwardedRegister> &Forwards =
2835 FuncInfo->getForwardedMustTailRegParms();
2836 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2838 // Conservatively forward AL on x86_64, since it might be used for varargs.
2839 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2840 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2841 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2844 // Copy all forwards from physical to virtual registers.
2845 for (ForwardedRegister &F : Forwards) {
2846 // FIXME: Can we use a less constrained schedule?
2847 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2848 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2849 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2853 // Some CCs need callee pop.
2854 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2855 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2856 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2857 } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
2858 // X86 interrupts must pop the error code if present
2859 FuncInfo->setBytesToPopOnReturn(Is64Bit ? 8 : 4);
2861 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2862 // If this is an sret function, the return should pop the hidden pointer.
2863 if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2864 !Subtarget.getTargetTriple().isOSMSVCRT() &&
2865 argsAreStructReturn(Ins, Subtarget.isTargetMCU()) == StackStructReturn)
2866 FuncInfo->setBytesToPopOnReturn(4);
2870 // RegSaveFrameIndex is X86-64 only.
2871 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2872 if (CallConv == CallingConv::X86_FastCall ||
2873 CallConv == CallingConv::X86_ThisCall)
2874 // fastcc functions can't have varargs.
2875 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2878 FuncInfo->setArgumentStackSize(StackSize);
2880 if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
2881 EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
2882 if (Personality == EHPersonality::CoreCLR) {
2884 // TODO: Add a mechanism to frame lowering that will allow us to indicate
2885 // that we'd prefer this slot be allocated towards the bottom of the frame
2886 // (i.e. near the stack pointer after allocating the frame). Every
2887 // funclet needs a copy of this slot in its (mostly empty) frame, and the
2888 // offset from the bottom of this and each funclet's frame must be the
2889 // same, so the size of funclets' (mostly empty) frames is dictated by
2890 // how far this slot is from the bottom (since they allocate just enough
2891 // space to accommodate holding this slot at the correct offset).
2892 int PSPSymFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2893 EHInfo->PSPSymFrameIdx = PSPSymFI;
2900 SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
2901 SDValue Arg, const SDLoc &dl,
2903 const CCValAssign &VA,
2904 ISD::ArgFlagsTy Flags) const {
2905 unsigned LocMemOffset = VA.getLocMemOffset();
2906 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2907 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2909 if (Flags.isByVal())
2910 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2912 return DAG.getStore(
2913 Chain, dl, Arg, PtrOff,
2914 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
2917 /// Emit a load of return address if tail call
2918 /// optimization is performed and it is required.
2919 SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
2920 SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
2921 bool Is64Bit, int FPDiff, const SDLoc &dl) const {
2922 // Adjust the Return address stack slot.
2923 EVT VT = getPointerTy(DAG.getDataLayout());
2924 OutRetAddr = getReturnAddressFrameIndex(DAG);
2926 // Load the "old" Return address.
2927 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
2928 return SDValue(OutRetAddr.getNode(), 1);
2931 /// Emit a store of the return address if tail call
2932 /// optimization is performed and it is required (FPDiff!=0).
2933 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2934 SDValue Chain, SDValue RetAddrFrIdx,
2935 EVT PtrVT, unsigned SlotSize,
2936 int FPDiff, const SDLoc &dl) {
2937 // Store the return address to the appropriate stack slot.
2938 if (!FPDiff) return Chain;
2939 // Calculate the new stack slot for the return address.
2940 int NewReturnAddrFI =
2941 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2943 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2944 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2945 MachinePointerInfo::getFixedStack(
2946 DAG.getMachineFunction(), NewReturnAddrFI));
2950 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2951 /// operation of specified width.
2952 static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
2954 unsigned NumElems = VT.getVectorNumElements();
2955 SmallVector<int, 8> Mask;
2956 Mask.push_back(NumElems);
2957 for (unsigned i = 1; i != NumElems; ++i)
2959 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
2963 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2964 SmallVectorImpl<SDValue> &InVals) const {
2965 SelectionDAG &DAG = CLI.DAG;
2967 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2968 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2969 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2970 SDValue Chain = CLI.Chain;
2971 SDValue Callee = CLI.Callee;
2972 CallingConv::ID CallConv = CLI.CallConv;
2973 bool &isTailCall = CLI.IsTailCall;
2974 bool isVarArg = CLI.IsVarArg;
2976 MachineFunction &MF = DAG.getMachineFunction();
2977 bool Is64Bit = Subtarget.is64Bit();
2978 bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
2979 StructReturnType SR = callIsStructReturn(Outs, Subtarget.isTargetMCU());
2980 bool IsSibcall = false;
2981 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2982 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2984 if (CallConv == CallingConv::X86_INTR)
2985 report_fatal_error("X86 interrupts may not be called directly");
2987 if (Attr.getValueAsString() == "true")
2990 if (Subtarget.isPICStyleGOT() &&
2991 !MF.getTarget().Options.GuaranteedTailCallOpt) {
2992 // If we are using a GOT, disable tail calls to external symbols with
2993 // default visibility. Tail calling such a symbol requires using a GOT
2994 // relocation, which forces early binding of the symbol. This breaks code
2995 // that require lazy function symbol resolution. Using musttail or
2996 // GuaranteedTailCallOpt will override this.
2997 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2998 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2999 G->getGlobal()->hasDefaultVisibility()))
3003 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3005 // Force this to be a tail call. The verifier rules are enough to ensure
3006 // that we can lower this successfully without moving the return address
3009 } else if (isTailCall) {
3010 // Check if it's really possible to do a tail call.
3011 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3012 isVarArg, SR != NotStructReturn,
3013 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3014 Outs, OutVals, Ins, DAG);
3016 // Sibcalls are automatically detected tailcalls which do not require
3018 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3025 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3026 "Var args not supported with calling convention fastcc, ghc or hipe");
3028 // Analyze operands of the call, assigning locations to each operand.
3029 SmallVector<CCValAssign, 16> ArgLocs;
3030 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3032 // Allocate shadow area for Win64
3034 CCInfo.AllocateStack(32, 8);
3036 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3038 // Get a count of how many bytes are to be pushed on the stack.
3039 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3041 // This is a sibcall. The memory operands are available in caller's
3042 // own caller's stack.
3044 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3045 canGuaranteeTCO(CallConv))
3046 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3049 if (isTailCall && !IsSibcall && !IsMustTail) {
3050 // Lower arguments at fp - stackoffset + fpdiff.
3051 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3053 FPDiff = NumBytesCallerPushed - NumBytes;
3055 // Set the delta of movement of the returnaddr stackslot.
3056 // But only set if delta is greater than previous delta.
3057 if (FPDiff < X86Info->getTCReturnAddrDelta())
3058 X86Info->setTCReturnAddrDelta(FPDiff);
3061 unsigned NumBytesToPush = NumBytes;
3062 unsigned NumBytesToPop = NumBytes;
3064 // If we have an inalloca argument, all stack space has already been allocated
3065 // for us and be right at the top of the stack. We don't support multiple
3066 // arguments passed in memory when using inalloca.
3067 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3069 if (!ArgLocs.back().isMemLoc())
3070 report_fatal_error("cannot use inalloca attribute on a register "
3072 if (ArgLocs.back().getLocMemOffset() != 0)
3073 report_fatal_error("any parameter with the inalloca attribute must be "
3074 "the only memory argument");
3078 Chain = DAG.getCALLSEQ_START(
3079 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3081 SDValue RetAddrFrIdx;
3082 // Load return address for tail calls.
3083 if (isTailCall && FPDiff)
3084 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3085 Is64Bit, FPDiff, dl);
3087 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3088 SmallVector<SDValue, 8> MemOpChains;
3091 // Walk the register/memloc assignments, inserting copies/loads. In the case
3092 // of tail call optimization arguments are handle later.
3093 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3094 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3095 // Skip inalloca arguments, they have already been written.
3096 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3097 if (Flags.isInAlloca())
3100 CCValAssign &VA = ArgLocs[i];
3101 EVT RegVT = VA.getLocVT();
3102 SDValue Arg = OutVals[i];
3103 bool isByVal = Flags.isByVal();
3105 // Promote the value if needed.
3106 switch (VA.getLocInfo()) {
3107 default: llvm_unreachable("Unknown loc info!");
3108 case CCValAssign::Full: break;
3109 case CCValAssign::SExt:
3110 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3112 case CCValAssign::ZExt:
3113 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3115 case CCValAssign::AExt:
3116 if (Arg.getValueType().isVector() &&
3117 Arg.getValueType().getVectorElementType() == MVT::i1)
3118 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3119 else if (RegVT.is128BitVector()) {
3120 // Special case: passing MMX values in XMM registers.
3121 Arg = DAG.getBitcast(MVT::i64, Arg);
3122 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3123 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3125 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3127 case CCValAssign::BCvt:
3128 Arg = DAG.getBitcast(RegVT, Arg);
3130 case CCValAssign::Indirect: {
3131 // Store the argument.
3132 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3133 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3134 Chain = DAG.getStore(
3135 Chain, dl, Arg, SpillSlot,
3136 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3142 if (VA.isRegLoc()) {
3143 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3144 if (isVarArg && IsWin64) {
3145 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3146 // shadow reg if callee is a varargs function.
3147 unsigned ShadowReg = 0;
3148 switch (VA.getLocReg()) {
3149 case X86::XMM0: ShadowReg = X86::RCX; break;
3150 case X86::XMM1: ShadowReg = X86::RDX; break;
3151 case X86::XMM2: ShadowReg = X86::R8; break;
3152 case X86::XMM3: ShadowReg = X86::R9; break;
3155 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3157 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3158 assert(VA.isMemLoc());
3159 if (!StackPtr.getNode())
3160 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3161 getPointerTy(DAG.getDataLayout()));
3162 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3163 dl, DAG, VA, Flags));
3167 if (!MemOpChains.empty())
3168 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3170 if (Subtarget.isPICStyleGOT()) {
3171 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3174 RegsToPass.push_back(std::make_pair(
3175 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3176 getPointerTy(DAG.getDataLayout()))));
3178 // If we are tail calling and generating PIC/GOT style code load the
3179 // address of the callee into ECX. The value in ecx is used as target of
3180 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3181 // for tail calls on PIC/GOT architectures. Normally we would just put the
3182 // address of GOT into ebx and then call target@PLT. But for tail calls
3183 // ebx would be restored (since ebx is callee saved) before jumping to the
3186 // Note: The actual moving to ECX is done further down.
3187 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3188 if (G && !G->getGlobal()->hasLocalLinkage() &&
3189 G->getGlobal()->hasDefaultVisibility())
3190 Callee = LowerGlobalAddress(Callee, DAG);
3191 else if (isa<ExternalSymbolSDNode>(Callee))
3192 Callee = LowerExternalSymbol(Callee, DAG);
3196 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3197 // From AMD64 ABI document:
3198 // For calls that may call functions that use varargs or stdargs
3199 // (prototype-less calls or calls to functions containing ellipsis (...) in
3200 // the declaration) %al is used as hidden argument to specify the number
3201 // of SSE registers used. The contents of %al do not need to match exactly
3202 // the number of registers, but must be an ubound on the number of SSE
3203 // registers used and is in the range 0 - 8 inclusive.
3205 // Count the number of XMM registers allocated.
3206 static const MCPhysReg XMMArgRegs[] = {
3207 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3208 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3210 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3211 assert((Subtarget.hasSSE1() || !NumXMMRegs)
3212 && "SSE registers cannot be used when SSE is disabled");
3214 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3215 DAG.getConstant(NumXMMRegs, dl,
3219 if (isVarArg && IsMustTail) {
3220 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3221 for (const auto &F : Forwards) {
3222 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3223 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3227 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3228 // don't need this because the eligibility check rejects calls that require
3229 // shuffling arguments passed in memory.
3230 if (!IsSibcall && isTailCall) {
3231 // Force all the incoming stack arguments to be loaded from the stack
3232 // before any new outgoing arguments are stored to the stack, because the
3233 // outgoing stack slots may alias the incoming argument stack slots, and
3234 // the alias isn't otherwise explicit. This is slightly more conservative
3235 // than necessary, because it means that each store effectively depends
3236 // on every argument instead of just those arguments it would clobber.
3237 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3239 SmallVector<SDValue, 8> MemOpChains2;
3242 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3243 CCValAssign &VA = ArgLocs[i];
3246 assert(VA.isMemLoc());
3247 SDValue Arg = OutVals[i];
3248 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3249 // Skip inalloca arguments. They don't require any work.
3250 if (Flags.isInAlloca())
3252 // Create frame index.
3253 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3254 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3255 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3256 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3258 if (Flags.isByVal()) {
3259 // Copy relative to framepointer.
3260 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3261 if (!StackPtr.getNode())
3262 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3263 getPointerTy(DAG.getDataLayout()));
3264 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3267 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3271 // Store relative to framepointer.
3272 MemOpChains2.push_back(DAG.getStore(
3273 ArgChain, dl, Arg, FIN,
3274 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
3278 if (!MemOpChains2.empty())
3279 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3281 // Store the return address to the appropriate stack slot.
3282 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3283 getPointerTy(DAG.getDataLayout()),
3284 RegInfo->getSlotSize(), FPDiff, dl);
3287 // Build a sequence of copy-to-reg nodes chained together with token chain
3288 // and flag operands which copy the outgoing args into registers.
3290 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3291 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3292 RegsToPass[i].second, InFlag);
3293 InFlag = Chain.getValue(1);
3296 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3297 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3298 // In the 64-bit large code model, we have to make all calls
3299 // through a register, since the call instruction's 32-bit
3300 // pc-relative offset may not be large enough to hold the whole
3302 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3303 // If the callee is a GlobalAddress node (quite common, every direct call
3304 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3306 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3308 // We should use extra load for direct calls to dllimported functions in
3310 const GlobalValue *GV = G->getGlobal();
3311 if (!GV->hasDLLImportStorageClass()) {
3312 unsigned char OpFlags = Subtarget.classifyGlobalFunctionReference(GV);
3314 Callee = DAG.getTargetGlobalAddress(
3315 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3317 if (OpFlags == X86II::MO_GOTPCREL) {
3319 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3320 getPointerTy(DAG.getDataLayout()), Callee);
3321 // Add extra indirection
3322 Callee = DAG.getLoad(
3323 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3324 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3327 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3328 const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
3329 unsigned char OpFlags =
3330 Subtarget.classifyGlobalFunctionReference(nullptr, *Mod);
3332 Callee = DAG.getTargetExternalSymbol(
3333 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3334 } else if (Subtarget.isTarget64BitILP32() &&
3335 Callee->getValueType(0) == MVT::i32) {
3336 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3337 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3340 // Returns a chain & a flag for retval copy to use.
3341 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3342 SmallVector<SDValue, 8> Ops;
3344 if (!IsSibcall && isTailCall) {
3345 Chain = DAG.getCALLSEQ_END(Chain,
3346 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3347 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3348 InFlag = Chain.getValue(1);
3351 Ops.push_back(Chain);
3352 Ops.push_back(Callee);
3355 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3357 // Add argument registers to the end of the list so that they are known live
3359 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3360 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3361 RegsToPass[i].second.getValueType()));
3363 // Add a register mask operand representing the call-preserved registers.
3364 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3365 assert(Mask && "Missing call preserved mask for calling convention");
3367 // If this is an invoke in a 32-bit function using a funclet-based
3368 // personality, assume the function clobbers all registers. If an exception
3369 // is thrown, the runtime will not restore CSRs.
3370 // FIXME: Model this more precisely so that we can register allocate across
3371 // the normal edge and spill and fill across the exceptional edge.
3372 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3373 const Function *CallerFn = MF.getFunction();
3374 EHPersonality Pers =
3375 CallerFn->hasPersonalityFn()
3376 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3377 : EHPersonality::Unknown;
3378 if (isFuncletEHPersonality(Pers))
3379 Mask = RegInfo->getNoPreservedMask();
3382 Ops.push_back(DAG.getRegisterMask(Mask));
3384 if (InFlag.getNode())
3385 Ops.push_back(InFlag);
3389 //// If this is the first return lowered for this function, add the regs
3390 //// to the liveout set for the function.
3391 // This isn't right, although it's probably harmless on x86; liveouts
3392 // should be computed from returns not tail calls. Consider a void
3393 // function making a tail call to a function returning int.
3394 MF.getFrameInfo()->setHasTailCall();
3395 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3398 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3399 InFlag = Chain.getValue(1);
3401 // Create the CALLSEQ_END node.
3402 unsigned NumBytesForCalleeToPop;
3403 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3404 DAG.getTarget().Options.GuaranteedTailCallOpt))
3405 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3406 else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3407 !Subtarget.getTargetTriple().isOSMSVCRT() &&
3408 SR == StackStructReturn)
3409 // If this is a call to a struct-return function, the callee
3410 // pops the hidden struct pointer, so we have to push it back.
3411 // This is common for Darwin/X86, Linux & Mingw32 targets.
3412 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3413 NumBytesForCalleeToPop = 4;
3415 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3417 if (CLI.DoesNotReturn && !getTargetMachine().Options.TrapUnreachable) {
3418 // No need to reset the stack after the call if the call doesn't return. To
3419 // make the MI verify, we'll pretend the callee does it for us.
3420 NumBytesForCalleeToPop = NumBytes;
3423 // Returns a flag for retval copy to use.
3425 Chain = DAG.getCALLSEQ_END(Chain,
3426 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3427 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3430 InFlag = Chain.getValue(1);
3433 // Handle result values, copying them out of physregs into vregs that we
3435 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3436 Ins, dl, DAG, InVals);
3439 //===----------------------------------------------------------------------===//
3440 // Fast Calling Convention (tail call) implementation
3441 //===----------------------------------------------------------------------===//
3443 // Like std call, callee cleans arguments, convention except that ECX is
3444 // reserved for storing the tail called function address. Only 2 registers are
3445 // free for argument passing (inreg). Tail call optimization is performed
3447 // * tailcallopt is enabled
3448 // * caller/callee are fastcc
3449 // On X86_64 architecture with GOT-style position independent code only local
3450 // (within module) calls are supported at the moment.
3451 // To keep the stack aligned according to platform abi the function
3452 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3453 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3454 // If a tail called function callee has more arguments than the caller the
3455 // caller needs to make sure that there is room to move the RETADDR to. This is
3456 // achieved by reserving an area the size of the argument delta right after the
3457 // original RETADDR, but before the saved framepointer or the spilled registers
3458 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3470 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3473 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3474 SelectionDAG& DAG) const {
3475 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3476 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
3477 unsigned StackAlignment = TFI.getStackAlignment();
3478 uint64_t AlignMask = StackAlignment - 1;
3479 int64_t Offset = StackSize;
3480 unsigned SlotSize = RegInfo->getSlotSize();
3481 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3482 // Number smaller than 12 so just add the difference.
3483 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3485 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3486 Offset = ((~AlignMask) & Offset) + StackAlignment +
3487 (StackAlignment-SlotSize);
3492 /// Return true if the given stack call argument is already available in the
3493 /// same position (relatively) of the caller's incoming argument stack.
3495 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3496 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3497 const X86InstrInfo *TII, const CCValAssign &VA) {
3498 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3501 // Look through nodes that don't alter the bits of the incoming value.
3502 unsigned Op = Arg.getOpcode();
3503 if (Op == ISD::ZERO_EXTEND || Op == ISD::ANY_EXTEND || Op == ISD::BITCAST) {
3504 Arg = Arg.getOperand(0);
3507 if (Op == ISD::TRUNCATE) {
3508 const SDValue &TruncInput = Arg.getOperand(0);
3509 if (TruncInput.getOpcode() == ISD::AssertZext &&
3510 cast<VTSDNode>(TruncInput.getOperand(1))->getVT() ==
3511 Arg.getValueType()) {
3512 Arg = TruncInput.getOperand(0);
3520 if (Arg.getOpcode() == ISD::CopyFromReg) {
3521 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3522 if (!TargetRegisterInfo::isVirtualRegister(VR))
3524 MachineInstr *Def = MRI->getVRegDef(VR);
3527 if (!Flags.isByVal()) {
3528 if (!TII->isLoadFromStackSlot(*Def, FI))
3531 unsigned Opcode = Def->getOpcode();
3532 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3533 Opcode == X86::LEA64_32r) &&
3534 Def->getOperand(1).isFI()) {
3535 FI = Def->getOperand(1).getIndex();
3536 Bytes = Flags.getByValSize();
3540 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3541 if (Flags.isByVal())
3542 // ByVal argument is passed in as a pointer but it's now being
3543 // dereferenced. e.g.
3544 // define @foo(%struct.X* %A) {
3545 // tail call @bar(%struct.X* byval %A)
3548 SDValue Ptr = Ld->getBasePtr();
3549 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3552 FI = FINode->getIndex();
3553 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3554 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3555 FI = FINode->getIndex();
3556 Bytes = Flags.getByValSize();
3560 assert(FI != INT_MAX);
3561 if (!MFI->isFixedObjectIndex(FI))
3564 if (Offset != MFI->getObjectOffset(FI))
3567 if (VA.getLocVT().getSizeInBits() > Arg.getValueType().getSizeInBits()) {
3568 // If the argument location is wider than the argument type, check that any
3569 // extension flags match.
3570 if (Flags.isZExt() != MFI->isObjectZExt(FI) ||
3571 Flags.isSExt() != MFI->isObjectSExt(FI)) {
3576 return Bytes == MFI->getObjectSize(FI);
3579 /// Check whether the call is eligible for tail call optimization. Targets
3580 /// that want to do tail call optimization should implement this function.
3581 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3582 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3583 bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3584 const SmallVectorImpl<ISD::OutputArg> &Outs,
3585 const SmallVectorImpl<SDValue> &OutVals,
3586 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3587 if (!mayTailCallThisCC(CalleeCC))
3590 // If -tailcallopt is specified, make fastcc functions tail-callable.
3591 MachineFunction &MF = DAG.getMachineFunction();
3592 const Function *CallerF = MF.getFunction();
3594 // If the function return type is x86_fp80 and the callee return type is not,
3595 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3596 // perform a tailcall optimization here.
3597 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3600 CallingConv::ID CallerCC = CallerF->getCallingConv();
3601 bool CCMatch = CallerCC == CalleeCC;
3602 bool IsCalleeWin64 = Subtarget.isCallingConvWin64(CalleeCC);
3603 bool IsCallerWin64 = Subtarget.isCallingConvWin64(CallerCC);
3605 // Win64 functions have extra shadow space for argument homing. Don't do the
3606 // sibcall if the caller and callee have mismatched expectations for this
3608 if (IsCalleeWin64 != IsCallerWin64)
3611 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3612 if (canGuaranteeTCO(CalleeCC) && CCMatch)
3617 // Look for obvious safe cases to perform tail call optimization that do not
3618 // require ABI changes. This is what gcc calls sibcall.
3620 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3621 // emit a special epilogue.
3622 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3623 if (RegInfo->needsStackRealignment(MF))
3626 // Also avoid sibcall optimization if either caller or callee uses struct
3627 // return semantics.
3628 if (isCalleeStructRet || isCallerStructRet)
3631 // Do not sibcall optimize vararg calls unless all arguments are passed via
3633 LLVMContext &C = *DAG.getContext();
3634 if (isVarArg && !Outs.empty()) {
3635 // Optimizing for varargs on Win64 is unlikely to be safe without
3636 // additional testing.
3637 if (IsCalleeWin64 || IsCallerWin64)
3640 SmallVector<CCValAssign, 16> ArgLocs;
3641 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3643 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3644 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3645 if (!ArgLocs[i].isRegLoc())
3649 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3650 // stack. Therefore, if it's not used by the call it is not safe to optimize
3651 // this into a sibcall.
3652 bool Unused = false;
3653 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3660 SmallVector<CCValAssign, 16> RVLocs;
3661 CCState CCInfo(CalleeCC, false, MF, RVLocs, C);
3662 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3663 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3664 CCValAssign &VA = RVLocs[i];
3665 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3670 // Check that the call results are passed in the same way.
3671 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3672 RetCC_X86, RetCC_X86))
3674 // The callee has to preserve all registers the caller needs to preserve.
3675 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
3676 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3678 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3679 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3683 unsigned StackArgsSize = 0;
3685 // If the callee takes no arguments then go on to check the results of the
3687 if (!Outs.empty()) {
3688 // Check if stack adjustment is needed. For now, do not do this if any
3689 // argument is passed on the stack.
3690 SmallVector<CCValAssign, 16> ArgLocs;
3691 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3693 // Allocate shadow area for Win64
3695 CCInfo.AllocateStack(32, 8);
3697 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3698 StackArgsSize = CCInfo.getNextStackOffset();
3700 if (CCInfo.getNextStackOffset()) {
3701 // Check if the arguments are already laid out in the right way as
3702 // the caller's fixed stack objects.
3703 MachineFrameInfo *MFI = MF.getFrameInfo();
3704 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3705 const X86InstrInfo *TII = Subtarget.getInstrInfo();
3706 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3707 CCValAssign &VA = ArgLocs[i];
3708 SDValue Arg = OutVals[i];
3709 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3710 if (VA.getLocInfo() == CCValAssign::Indirect)
3712 if (!VA.isRegLoc()) {
3713 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3720 bool PositionIndependent = isPositionIndependent();
3721 // If the tailcall address may be in a register, then make sure it's
3722 // possible to register allocate for it. In 32-bit, the call address can
3723 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3724 // callee-saved registers are restored. These happen to be the same
3725 // registers used to pass 'inreg' arguments so watch out for those.
3726 if (!Subtarget.is64Bit() && ((!isa<GlobalAddressSDNode>(Callee) &&
3727 !isa<ExternalSymbolSDNode>(Callee)) ||
3728 PositionIndependent)) {
3729 unsigned NumInRegs = 0;
3730 // In PIC we need an extra register to formulate the address computation
3732 unsigned MaxInRegs = PositionIndependent ? 2 : 3;
3734 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3735 CCValAssign &VA = ArgLocs[i];
3738 unsigned Reg = VA.getLocReg();
3741 case X86::EAX: case X86::EDX: case X86::ECX:
3742 if (++NumInRegs == MaxInRegs)
3749 const MachineRegisterInfo &MRI = MF.getRegInfo();
3750 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3754 bool CalleeWillPop =
3755 X86::isCalleePop(CalleeCC, Subtarget.is64Bit(), isVarArg,
3756 MF.getTarget().Options.GuaranteedTailCallOpt);
3758 if (unsigned BytesToPop =
3759 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3760 // If we have bytes to pop, the callee must pop them.
3761 bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3762 if (!CalleePopMatches)
3764 } else if (CalleeWillPop && StackArgsSize > 0) {
3765 // If we don't have bytes to pop, make sure the callee doesn't pop any.
3773 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3774 const TargetLibraryInfo *libInfo) const {
3775 return X86::createFastISel(funcInfo, libInfo);
3778 //===----------------------------------------------------------------------===//
3779 // Other Lowering Hooks
3780 //===----------------------------------------------------------------------===//
3782 static bool MayFoldLoad(SDValue Op) {
3783 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3786 static bool MayFoldIntoStore(SDValue Op) {
3787 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3790 static bool isTargetShuffle(unsigned Opcode) {
3792 default: return false;
3793 case X86ISD::BLENDI:
3794 case X86ISD::PSHUFB:
3795 case X86ISD::PSHUFD:
3796 case X86ISD::PSHUFHW:
3797 case X86ISD::PSHUFLW:
3799 case X86ISD::INSERTPS:
3800 case X86ISD::PALIGNR:
3801 case X86ISD::VSHLDQ:
3802 case X86ISD::VSRLDQ:
3803 case X86ISD::MOVLHPS:
3804 case X86ISD::MOVLHPD:
3805 case X86ISD::MOVHLPS:
3806 case X86ISD::MOVLPS:
3807 case X86ISD::MOVLPD:
3808 case X86ISD::MOVSHDUP:
3809 case X86ISD::MOVSLDUP:
3810 case X86ISD::MOVDDUP:
3813 case X86ISD::UNPCKL:
3814 case X86ISD::UNPCKH:
3815 case X86ISD::VBROADCAST:
3816 case X86ISD::VPERMILPI:
3817 case X86ISD::VPERMILPV:
3818 case X86ISD::VPERM2X128:
3819 case X86ISD::VPERMIL2:
3820 case X86ISD::VPERMI:
3821 case X86ISD::VPPERM:
3822 case X86ISD::VPERMV:
3823 case X86ISD::VPERMV3:
3824 case X86ISD::VZEXT_MOVL:
3829 static bool isTargetShuffleVariableMask(unsigned Opcode) {
3831 default: return false;
3832 case X86ISD::PSHUFB:
3833 case X86ISD::VPERMILPV:
3838 static SDValue getTargetShuffleNode(unsigned Opc, const SDLoc &dl, MVT VT,
3839 SDValue V1, unsigned TargetMask,
3840 SelectionDAG &DAG) {
3842 default: llvm_unreachable("Unknown x86 shuffle node");
3843 case X86ISD::PSHUFD:
3844 case X86ISD::PSHUFHW:
3845 case X86ISD::PSHUFLW:
3846 case X86ISD::VPERMILPI:
3847 case X86ISD::VPERMI:
3848 return DAG.getNode(Opc, dl, VT, V1,
3849 DAG.getConstant(TargetMask, dl, MVT::i8));
3853 static SDValue getTargetShuffleNode(unsigned Opc, const SDLoc &dl, MVT VT,
3854 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3856 default: llvm_unreachable("Unknown x86 shuffle node");
3857 case X86ISD::MOVLHPS:
3858 case X86ISD::MOVLHPD:
3859 case X86ISD::MOVHLPS:
3860 case X86ISD::MOVLPS:
3861 case X86ISD::MOVLPD:
3864 case X86ISD::UNPCKL:
3865 case X86ISD::UNPCKH:
3866 return DAG.getNode(Opc, dl, VT, V1, V2);
3870 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3871 MachineFunction &MF = DAG.getMachineFunction();
3872 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3873 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3874 int ReturnAddrIndex = FuncInfo->getRAIndex();
3876 if (ReturnAddrIndex == 0) {
3877 // Set up a frame object for the return address.
3878 unsigned SlotSize = RegInfo->getSlotSize();
3879 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3882 FuncInfo->setRAIndex(ReturnAddrIndex);
3885 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3888 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3889 bool hasSymbolicDisplacement) {
3890 // Offset should fit into 32 bit immediate field.
3891 if (!isInt<32>(Offset))
3894 // If we don't have a symbolic displacement - we don't have any extra
3896 if (!hasSymbolicDisplacement)
3899 // FIXME: Some tweaks might be needed for medium code model.
3900 if (M != CodeModel::Small && M != CodeModel::Kernel)
3903 // For small code model we assume that latest object is 16MB before end of 31
3904 // bits boundary. We may also accept pretty large negative constants knowing
3905 // that all objects are in the positive half of address space.
3906 if (M == CodeModel::Small && Offset < 16*1024*1024)
3909 // For kernel code model we know that all object resist in the negative half
3910 // of 32bits address space. We may not accept negative offsets, since they may
3911 // be just off and we may accept pretty large positive ones.
3912 if (M == CodeModel::Kernel && Offset >= 0)
3918 /// Determines whether the callee is required to pop its own arguments.
3919 /// Callee pop is necessary to support tail calls.
3920 bool X86::isCalleePop(CallingConv::ID CallingConv,
3921 bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
3922 // If GuaranteeTCO is true, we force some calls to be callee pop so that we
3923 // can guarantee TCO.
3924 if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
3927 switch (CallingConv) {
3930 case CallingConv::X86_StdCall:
3931 case CallingConv::X86_FastCall:
3932 case CallingConv::X86_ThisCall:
3933 case CallingConv::X86_VectorCall:
3938 /// \brief Return true if the condition is an unsigned comparison operation.
3939 static bool isX86CCUnsigned(unsigned X86CC) {
3942 llvm_unreachable("Invalid integer condition!");
3958 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
3959 switch (SetCCOpcode) {
3960 default: llvm_unreachable("Invalid integer condition!");
3961 case ISD::SETEQ: return X86::COND_E;
3962 case ISD::SETGT: return X86::COND_G;
3963 case ISD::SETGE: return X86::COND_GE;
3964 case ISD::SETLT: return X86::COND_L;
3965 case ISD::SETLE: return X86::COND_LE;
3966 case ISD::SETNE: return X86::COND_NE;
3967 case ISD::SETULT: return X86::COND_B;
3968 case ISD::SETUGT: return X86::COND_A;
3969 case ISD::SETULE: return X86::COND_BE;
3970 case ISD::SETUGE: return X86::COND_AE;
3974 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3975 /// condition code, returning the condition code and the LHS/RHS of the
3976 /// comparison to make.
3977 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, const SDLoc &DL,
3978 bool isFP, SDValue &LHS, SDValue &RHS,
3979 SelectionDAG &DAG) {
3981 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3982 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3983 // X > -1 -> X == 0, jump !sign.
3984 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3985 return X86::COND_NS;
3987 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3988 // X < 0 -> X == 0, jump on sign.
3991 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3993 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3994 return X86::COND_LE;
3998 return TranslateIntegerX86CC(SetCCOpcode);
4001 // First determine if it is required or is profitable to flip the operands.
4003 // If LHS is a foldable load, but RHS is not, flip the condition.
4004 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4005 !ISD::isNON_EXTLoad(RHS.getNode())) {
4006 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4007 std::swap(LHS, RHS);
4010 switch (SetCCOpcode) {
4016 std::swap(LHS, RHS);
4020 // On a floating point condition, the flags are set as follows:
4022 // 0 | 0 | 0 | X > Y
4023 // 0 | 0 | 1 | X < Y
4024 // 1 | 0 | 0 | X == Y
4025 // 1 | 1 | 1 | unordered
4026 switch (SetCCOpcode) {
4027 default: llvm_unreachable("Condcode should be pre-legalized away");
4029 case ISD::SETEQ: return X86::COND_E;
4030 case ISD::SETOLT: // flipped
4032 case ISD::SETGT: return X86::COND_A;
4033 case ISD::SETOLE: // flipped
4035 case ISD::SETGE: return X86::COND_AE;
4036 case ISD::SETUGT: // flipped
4038 case ISD::SETLT: return X86::COND_B;
4039 case ISD::SETUGE: // flipped
4041 case ISD::SETLE: return X86::COND_BE;
4043 case ISD::SETNE: return X86::COND_NE;
4044 case ISD::SETUO: return X86::COND_P;
4045 case ISD::SETO: return X86::COND_NP;
4047 case ISD::SETUNE: return X86::COND_INVALID;
4051 /// Is there a floating point cmov for the specific X86 condition code?
4052 /// Current x86 isa includes the following FP cmov instructions:
4053 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4054 static bool hasFPCMov(unsigned X86CC) {
4071 bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
4073 unsigned Intrinsic) const {
4075 const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
4079 Info.opc = ISD::INTRINSIC_W_CHAIN;
4080 Info.readMem = false;
4081 Info.writeMem = false;
4085 switch (IntrData->Type) {
4086 case EXPAND_FROM_MEM: {
4087 Info.ptrVal = I.getArgOperand(0);
4088 Info.memVT = MVT::getVT(I.getType());
4090 Info.readMem = true;
4093 case COMPRESS_TO_MEM: {
4094 Info.ptrVal = I.getArgOperand(0);
4095 Info.memVT = MVT::getVT(I.getArgOperand(1)->getType());
4097 Info.writeMem = true;
4100 case TRUNCATE_TO_MEM_VI8:
4101 case TRUNCATE_TO_MEM_VI16:
4102 case TRUNCATE_TO_MEM_VI32: {
4103 Info.ptrVal = I.getArgOperand(0);
4104 MVT VT = MVT::getVT(I.getArgOperand(1)->getType());
4105 MVT ScalarVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
4106 if (IntrData->Type == TRUNCATE_TO_MEM_VI8)
4108 else if (IntrData->Type == TRUNCATE_TO_MEM_VI16)
4109 ScalarVT = MVT::i16;
4110 else if (IntrData->Type == TRUNCATE_TO_MEM_VI32)
4111 ScalarVT = MVT::i32;
4113 Info.memVT = MVT::getVectorVT(ScalarVT, VT.getVectorNumElements());
4115 Info.writeMem = true;
4125 /// Returns true if the target can instruction select the
4126 /// specified FP immediate natively. If false, the legalizer will
4127 /// materialize the FP immediate as a load from a constant pool.
4128 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4129 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4130 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4136 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4137 ISD::LoadExtType ExtTy,
4139 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4140 // relocation target a movq or addq instruction: don't let the load shrink.
4141 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4142 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4143 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4144 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4148 /// \brief Returns true if it is beneficial to convert a load of a constant
4149 /// to just the constant itself.
4150 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4152 assert(Ty->isIntegerTy());
4154 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4155 if (BitSize == 0 || BitSize > 64)
4160 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4161 unsigned Index) const {
4162 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4165 return (Index == 0 || Index == ResVT.getVectorNumElements());
4168 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4169 // Speculate cttz only if we can directly use TZCNT.
4170 return Subtarget.hasBMI();
4173 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4174 // Speculate ctlz only if we can directly use LZCNT.
4175 return Subtarget.hasLZCNT();
4178 bool X86TargetLowering::hasAndNotCompare(SDValue Y) const {
4179 if (!Subtarget.hasBMI())
4182 // There are only 32-bit and 64-bit forms for 'andn'.
4183 EVT VT = Y.getValueType();
4184 if (VT != MVT::i32 && VT != MVT::i64)
4190 /// Return true if every element in Mask, beginning
4191 /// from position Pos and ending in Pos+Size is undef.
4192 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4193 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4199 /// Return true if Val is undef or if its value falls within the
4200 /// specified range (L, H].
4201 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4202 return (Val < 0) || (Val >= Low && Val < Hi);
4205 /// Return true if every element in Mask is undef or if its value
4206 /// falls within the specified range (L, H].
4207 static bool isUndefOrInRange(ArrayRef<int> Mask,
4210 if (!isUndefOrInRange(M, Low, Hi))
4215 /// Val is either less than zero (undef) or equal to the specified value.
4216 static bool isUndefOrEqual(int Val, int CmpVal) {
4217 return (Val < 0 || Val == CmpVal);
4220 /// Val is either the undef or zero sentinel value.
4221 static bool isUndefOrZero(int Val) {
4222 return (Val == SM_SentinelUndef || Val == SM_SentinelZero);
4225 /// Return true if every element in Mask, beginning
4226 /// from position Pos and ending in Pos+Size, falls within the specified
4227 /// sequential range (Low, Low+Size]. or is undef.
4228 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4229 unsigned Pos, unsigned Size, int Low) {
4230 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4231 if (!isUndefOrEqual(Mask[i], Low))
4236 /// Return true if every element in Mask, beginning
4237 /// from position Pos and ending in Pos+Size, falls within the specified
4238 /// sequential range (Low, Low+Size], or is undef or is zero.
4239 static bool isSequentialOrUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
4240 unsigned Size, int Low) {
4241 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, ++Low)
4242 if (!isUndefOrZero(Mask[i]) && Mask[i] != Low)
4247 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4248 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4249 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4250 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4251 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4254 // The index should be aligned on a vecWidth-bit boundary.
4256 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4258 MVT VT = N->getSimpleValueType(0);
4259 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4260 bool Result = (Index * ElSize) % vecWidth == 0;
4265 /// Return true if the specified INSERT_SUBVECTOR
4266 /// operand specifies a subvector insert that is suitable for input to
4267 /// insertion of 128 or 256-bit subvectors
4268 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4269 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4270 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4272 // The index should be aligned on a vecWidth-bit boundary.
4274 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4276 MVT VT = N->getSimpleValueType(0);
4277 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4278 bool Result = (Index * ElSize) % vecWidth == 0;
4283 bool X86::isVINSERT128Index(SDNode *N) {
4284 return isVINSERTIndex(N, 128);
4287 bool X86::isVINSERT256Index(SDNode *N) {
4288 return isVINSERTIndex(N, 256);
4291 bool X86::isVEXTRACT128Index(SDNode *N) {
4292 return isVEXTRACTIndex(N, 128);
4295 bool X86::isVEXTRACT256Index(SDNode *N) {
4296 return isVEXTRACTIndex(N, 256);
4299 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4300 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4301 assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4302 "Illegal extract subvector for VEXTRACT");
4305 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4307 MVT VecVT = N->getOperand(0).getSimpleValueType();
4308 MVT ElVT = VecVT.getVectorElementType();
4310 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4311 return Index / NumElemsPerChunk;
4314 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4315 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4316 assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4317 "Illegal insert subvector for VINSERT");
4320 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4322 MVT VecVT = N->getSimpleValueType(0);
4323 MVT ElVT = VecVT.getVectorElementType();
4325 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4326 return Index / NumElemsPerChunk;
4329 /// Return the appropriate immediate to extract the specified
4330 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4331 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4332 return getExtractVEXTRACTImmediate(N, 128);
4335 /// Return the appropriate immediate to extract the specified
4336 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4337 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4338 return getExtractVEXTRACTImmediate(N, 256);
4341 /// Return the appropriate immediate to insert at the specified
4342 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4343 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4344 return getInsertVINSERTImmediate(N, 128);
4347 /// Return the appropriate immediate to insert at the specified
4348 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4349 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4350 return getInsertVINSERTImmediate(N, 256);
4353 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4354 bool X86::isZeroNode(SDValue Elt) {
4355 return isNullConstant(Elt) || isNullFPConstant(Elt);
4358 // Build a vector of constants
4359 // Use an UNDEF node if MaskElt == -1.
4360 // Spilt 64-bit constants in the 32-bit mode.
4361 static SDValue getConstVector(ArrayRef<int> Values, MVT VT, SelectionDAG &DAG,
4362 const SDLoc &dl, bool IsMask = false) {
4364 SmallVector<SDValue, 32> Ops;
4367 MVT ConstVecVT = VT;
4368 unsigned NumElts = VT.getVectorNumElements();
4369 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4370 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4371 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4375 MVT EltVT = ConstVecVT.getVectorElementType();
4376 for (unsigned i = 0; i < NumElts; ++i) {
4377 bool IsUndef = Values[i] < 0 && IsMask;
4378 SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4379 DAG.getConstant(Values[i], dl, EltVT);
4380 Ops.push_back(OpNode);
4382 Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4383 DAG.getConstant(0, dl, EltVT));
4385 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
4387 ConstsNode = DAG.getBitcast(VT, ConstsNode);
4391 /// Returns a vector of specified type with all zero elements.
4392 static SDValue getZeroVector(MVT VT, const X86Subtarget &Subtarget,
4393 SelectionDAG &DAG, const SDLoc &dl) {
4394 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() ||
4395 VT.getVectorElementType() == MVT::i1) &&
4396 "Unexpected vector type");
4398 // Try to build SSE/AVX zero vectors as <N x i32> bitcasted to their dest
4399 // type. This ensures they get CSE'd. But if the integer type is not
4400 // available, use a floating-point +0.0 instead.
4402 if (!Subtarget.hasSSE2() && VT.is128BitVector()) {
4403 Vec = DAG.getConstantFP(+0.0, dl, MVT::v4f32);
4404 } else if (VT.getVectorElementType() == MVT::i1) {
4405 assert((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&
4406 "Unexpected vector type");
4407 assert((Subtarget.hasVLX() || VT.getVectorNumElements() >= 8) &&
4408 "Unexpected vector type");
4409 Vec = DAG.getConstant(0, dl, VT);
4411 unsigned Num32BitElts = VT.getSizeInBits() / 32;
4412 Vec = DAG.getConstant(0, dl, MVT::getVectorVT(MVT::i32, Num32BitElts));
4414 return DAG.getBitcast(VT, Vec);
4417 static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
4418 const SDLoc &dl, unsigned vectorWidth) {
4419 assert((vectorWidth == 128 || vectorWidth == 256) &&
4420 "Unsupported vector width");
4421 EVT VT = Vec.getValueType();
4422 EVT ElVT = VT.getVectorElementType();
4423 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4424 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4425 VT.getVectorNumElements()/Factor);
4427 // Extract from UNDEF is UNDEF.
4429 return DAG.getUNDEF(ResultVT);
4431 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4432 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4433 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4435 // This is the index of the first element of the vectorWidth-bit chunk
4436 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4437 IdxVal &= ~(ElemsPerChunk - 1);
4439 // If the input is a buildvector just emit a smaller one.
4440 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4441 return DAG.getNode(ISD::BUILD_VECTOR,
4442 dl, ResultVT, makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4444 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4445 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4448 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4449 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4450 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4451 /// instructions or a simple subregister reference. Idx is an index in the
4452 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4453 /// lowering EXTRACT_VECTOR_ELT operations easier.
4454 static SDValue extract128BitVector(SDValue Vec, unsigned IdxVal,
4455 SelectionDAG &DAG, const SDLoc &dl) {
4456 assert((Vec.getValueType().is256BitVector() ||
4457 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4458 return extractSubVector(Vec, IdxVal, DAG, dl, 128);
4461 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4462 static SDValue extract256BitVector(SDValue Vec, unsigned IdxVal,
4463 SelectionDAG &DAG, const SDLoc &dl) {
4464 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4465 return extractSubVector(Vec, IdxVal, DAG, dl, 256);
4468 static SDValue insertSubVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4469 SelectionDAG &DAG, const SDLoc &dl,
4470 unsigned vectorWidth) {
4471 assert((vectorWidth == 128 || vectorWidth == 256) &&
4472 "Unsupported vector width");
4473 // Inserting UNDEF is Result
4476 EVT VT = Vec.getValueType();
4477 EVT ElVT = VT.getVectorElementType();
4478 EVT ResultVT = Result.getValueType();
4480 // Insert the relevant vectorWidth bits.
4481 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4482 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4484 // This is the index of the first element of the vectorWidth-bit chunk
4485 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4486 IdxVal &= ~(ElemsPerChunk - 1);
4488 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4489 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4492 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4493 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4494 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4495 /// simple superregister reference. Idx is an index in the 128 bits
4496 /// we want. It need not be aligned to a 128-bit boundary. That makes
4497 /// lowering INSERT_VECTOR_ELT operations easier.
4498 static SDValue insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4499 SelectionDAG &DAG, const SDLoc &dl) {
4500 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4502 // For insertion into the zero index (low half) of a 256-bit vector, it is
4503 // more efficient to generate a blend with immediate instead of an insert*128.
4504 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4505 // extend the subvector to the size of the result vector. Make sure that
4506 // we are not recursing on that node by checking for undef here.
4507 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4508 !Result.isUndef()) {
4509 EVT ResultVT = Result.getValueType();
4510 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4511 SDValue Undef = DAG.getUNDEF(ResultVT);
4512 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4515 // The blend instruction, and therefore its mask, depend on the data type.
4516 MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4517 if (ScalarType.isFloatingPoint()) {
4518 // Choose either vblendps (float) or vblendpd (double).
4519 unsigned ScalarSize = ScalarType.getSizeInBits();
4520 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4521 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4522 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4523 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4526 const X86Subtarget &Subtarget =
4527 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4529 // AVX2 is needed for 256-bit integer blend support.
4530 // Integers must be cast to 32-bit because there is only vpblendd;
4531 // vpblendw can't be used for this because it has a handicapped mask.
4533 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4534 // is still more efficient than using the wrong domain vinsertf128 that
4535 // will be created by InsertSubVector().
4536 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4538 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4539 Result = DAG.getBitcast(CastVT, Result);
4540 Vec256 = DAG.getBitcast(CastVT, Vec256);
4541 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4542 return DAG.getBitcast(ResultVT, Vec256);
4545 return insertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4548 static SDValue insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4549 SelectionDAG &DAG, const SDLoc &dl) {
4550 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4551 return insertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4554 /// Insert i1-subvector to i1-vector.
4555 static SDValue insert1BitVector(SDValue Op, SelectionDAG &DAG,
4556 const X86Subtarget &Subtarget) {
4559 SDValue Vec = Op.getOperand(0);
4560 SDValue SubVec = Op.getOperand(1);
4561 SDValue Idx = Op.getOperand(2);
4563 if (!isa<ConstantSDNode>(Idx))
4566 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4567 if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
4570 MVT OpVT = Op.getSimpleValueType();
4571 MVT SubVecVT = SubVec.getSimpleValueType();
4572 unsigned NumElems = OpVT.getVectorNumElements();
4573 unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4575 assert(IdxVal + SubVecNumElems <= NumElems &&
4576 IdxVal % SubVecVT.getSizeInBits() == 0 &&
4577 "Unexpected index value in INSERT_SUBVECTOR");
4579 // There are 3 possible cases:
4580 // 1. Subvector should be inserted in the lower part (IdxVal == 0)
4581 // 2. Subvector should be inserted in the upper part
4582 // (IdxVal + SubVecNumElems == NumElems)
4583 // 3. Subvector should be inserted in the middle (for example v2i1
4584 // to v16i1, index 2)
4586 // extend to natively supported kshift
4587 MVT MinVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
4588 MVT WideOpVT = OpVT;
4589 if (OpVT.getSizeInBits() < MinVT.getStoreSizeInBits())
4592 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
4593 SDValue Undef = DAG.getUNDEF(WideOpVT);
4594 SDValue WideSubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4595 Undef, SubVec, ZeroIdx);
4597 // Extract sub-vector if require.
4598 auto ExtractSubVec = [&](SDValue V) {
4599 return (WideOpVT == OpVT) ? V : DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
4603 if (Vec.isUndef()) {
4605 SDValue ShiftBits = DAG.getConstant(IdxVal, dl, MVT::i8);
4606 WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, WideOpVT, WideSubVec, ShiftBits);
4608 return ExtractSubVec(WideSubVec);
4611 if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
4612 NumElems = WideOpVT.getVectorNumElements();
4613 unsigned ShiftLeft = NumElems - SubVecNumElems;
4614 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4615 Vec = DAG.getNode(X86ISD::VSHLI, dl, WideOpVT, WideSubVec,
4616 DAG.getConstant(ShiftLeft, dl, MVT::i8));
4617 Vec = ShiftRight ? DAG.getNode(X86ISD::VSRLI, dl, WideOpVT, Vec,
4618 DAG.getConstant(ShiftRight, dl, MVT::i8)) : Vec;
4619 return ExtractSubVec(Vec);
4623 // Zero lower bits of the Vec
4624 SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4625 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
4626 Vec = DAG.getNode(X86ISD::VSRLI, dl, WideOpVT, Vec, ShiftBits);
4627 Vec = DAG.getNode(X86ISD::VSHLI, dl, WideOpVT, Vec, ShiftBits);
4628 // Merge them together, SubVec should be zero extended.
4629 WideSubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4630 getZeroVector(WideOpVT, Subtarget, DAG, dl),
4632 Vec = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, WideSubVec);
4633 return ExtractSubVec(Vec);
4636 // Simple case when we put subvector in the upper part
4637 if (IdxVal + SubVecNumElems == NumElems) {
4638 // Zero upper bits of the Vec
4639 WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, WideOpVT, WideSubVec,
4640 DAG.getConstant(IdxVal, dl, MVT::i8));
4641 SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4642 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
4643 Vec = DAG.getNode(X86ISD::VSHLI, dl, WideOpVT, Vec, ShiftBits);
4644 Vec = DAG.getNode(X86ISD::VSRLI, dl, WideOpVT, Vec, ShiftBits);
4645 Vec = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, WideSubVec);
4646 return ExtractSubVec(Vec);
4648 // Subvector should be inserted in the middle - use shuffle
4649 WideSubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
4651 SmallVector<int, 64> Mask;
4652 for (unsigned i = 0; i < NumElems; ++i)
4653 Mask.push_back(i >= IdxVal && i < IdxVal + SubVecNumElems ?
4655 return DAG.getVectorShuffle(OpVT, dl, WideSubVec, Vec, Mask);
4658 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4659 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4660 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4661 /// large BUILD_VECTORS.
4662 static SDValue concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4663 unsigned NumElems, SelectionDAG &DAG,
4665 SDValue V = insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4666 return insert128BitVector(V, V2, NumElems / 2, DAG, dl);
4669 static SDValue concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4670 unsigned NumElems, SelectionDAG &DAG,
4672 SDValue V = insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4673 return insert256BitVector(V, V2, NumElems / 2, DAG, dl);
4676 /// Returns a vector of specified type with all bits set.
4677 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4678 /// no AVX2 support, use two <4 x i32> inserted in a <8 x i32> appropriately.
4679 /// Then bitcast to their original type, ensuring they get CSE'd.
4680 static SDValue getOnesVector(EVT VT, const X86Subtarget &Subtarget,
4681 SelectionDAG &DAG, const SDLoc &dl) {
4682 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4683 "Expected a 128/256/512-bit vector type");
4685 APInt Ones = APInt::getAllOnesValue(32);
4686 unsigned NumElts = VT.getSizeInBits() / 32;
4688 if (!Subtarget.hasInt256() && NumElts == 8) {
4689 Vec = DAG.getConstant(Ones, dl, MVT::v4i32);
4690 Vec = concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4692 Vec = DAG.getConstant(Ones, dl, MVT::getVectorVT(MVT::i32, NumElts));
4694 return DAG.getBitcast(VT, Vec);
4697 /// Returns a vector_shuffle node for an unpackl operation.
4698 static SDValue getUnpackl(SelectionDAG &DAG, const SDLoc &dl, MVT VT,
4699 SDValue V1, SDValue V2) {
4700 assert(VT.is128BitVector() && "Expected a 128-bit vector type");
4701 unsigned NumElems = VT.getVectorNumElements();
4702 SmallVector<int, 8> Mask(NumElems);
4703 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4705 Mask[i * 2 + 1] = i + NumElems;
4707 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
4710 /// Returns a vector_shuffle node for an unpackh operation.
4711 static SDValue getUnpackh(SelectionDAG &DAG, const SDLoc &dl, MVT VT,
4712 SDValue V1, SDValue V2) {
4713 assert(VT.is128BitVector() && "Expected a 128-bit vector type");
4714 unsigned NumElems = VT.getVectorNumElements();
4715 SmallVector<int, 8> Mask(NumElems);
4716 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4717 Mask[i * 2] = i + Half;
4718 Mask[i * 2 + 1] = i + NumElems + Half;
4720 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
4723 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4724 /// This produces a shuffle where the low element of V2 is swizzled into the
4725 /// zero/undef vector, landing at element Idx.
4726 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4727 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, int Idx,
4729 const X86Subtarget &Subtarget,
4730 SelectionDAG &DAG) {
4731 MVT VT = V2.getSimpleValueType();
4733 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4734 int NumElems = VT.getVectorNumElements();
4735 SmallVector<int, 16> MaskVec(NumElems);
4736 for (int i = 0; i != NumElems; ++i)
4737 // If this is the insertion idx, put the low elt of V2 here.
4738 MaskVec[i] = (i == Idx) ? NumElems : i;
4739 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, MaskVec);
4742 static SDValue peekThroughBitcasts(SDValue V) {
4743 while (V.getNode() && V.getOpcode() == ISD::BITCAST)
4744 V = V.getOperand(0);
4748 static bool getTargetShuffleMaskIndices(SDValue MaskNode,
4749 unsigned MaskEltSizeInBits,
4750 SmallVectorImpl<uint64_t> &RawMask) {
4751 MaskNode = peekThroughBitcasts(MaskNode);
4753 MVT VT = MaskNode.getSimpleValueType();
4754 assert(VT.isVector() && "Can't produce a non-vector with a build_vector!");
4756 // Split an APInt element into MaskEltSizeInBits sized pieces and
4757 // insert into the shuffle mask.
4758 auto SplitElementToMask = [&](APInt Element) {
4759 // Note that this is x86 and so always little endian: the low byte is
4760 // the first byte of the mask.
4761 int Split = VT.getScalarSizeInBits() / MaskEltSizeInBits;
4762 for (int i = 0; i < Split; ++i) {
4763 APInt RawElt = Element.getLoBits(MaskEltSizeInBits);
4764 Element = Element.lshr(MaskEltSizeInBits);
4765 RawMask.push_back(RawElt.getZExtValue());
4769 if (MaskNode.getOpcode() == X86ISD::VBROADCAST) {
4770 // TODO: Handle (MaskEltSizeInBits % VT.getScalarSizeInBits()) == 0
4771 // TODO: Handle (VT.getScalarSizeInBits() % MaskEltSizeInBits) == 0
4772 if (VT.getScalarSizeInBits() != MaskEltSizeInBits)
4774 if (auto *CN = dyn_cast<ConstantSDNode>(MaskNode.getOperand(0))) {
4775 const APInt &MaskElement = CN->getAPIntValue();
4776 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4777 APInt RawElt = MaskElement.getLoBits(MaskEltSizeInBits);
4778 RawMask.push_back(RawElt.getZExtValue());
4784 if (MaskNode.getOpcode() == X86ISD::VZEXT_MOVL &&
4785 MaskNode.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR) {
4787 // TODO: Handle (MaskEltSizeInBits % VT.getScalarSizeInBits()) == 0
4788 if ((VT.getScalarSizeInBits() % MaskEltSizeInBits) != 0)
4790 unsigned ElementSplit = VT.getScalarSizeInBits() / MaskEltSizeInBits;
4792 SDValue MaskOp = MaskNode.getOperand(0).getOperand(0);
4793 if (auto *CN = dyn_cast<ConstantSDNode>(MaskOp)) {
4794 SplitElementToMask(CN->getAPIntValue());
4795 RawMask.append((VT.getVectorNumElements() - 1) * ElementSplit, 0);
4801 if (MaskNode.getOpcode() != ISD::BUILD_VECTOR)
4804 // We can always decode if the buildvector is all zero constants,
4805 // but can't use isBuildVectorAllZeros as it might contain UNDEFs.
4806 if (llvm::all_of(MaskNode->ops(), X86::isZeroNode)) {
4807 RawMask.append(VT.getSizeInBits() / MaskEltSizeInBits, 0);
4811 // TODO: Handle (MaskEltSizeInBits % VT.getScalarSizeInBits()) == 0
4812 if ((VT.getScalarSizeInBits() % MaskEltSizeInBits) != 0)
4815 for (SDValue Op : MaskNode->ops()) {
4816 if (auto *CN = dyn_cast<ConstantSDNode>(Op.getNode()))
4817 SplitElementToMask(CN->getAPIntValue());
4818 else if (auto *CFN = dyn_cast<ConstantFPSDNode>(Op.getNode()))
4819 SplitElementToMask(CFN->getValueAPF().bitcastToAPInt());
4827 static const Constant *getTargetShuffleMaskConstant(SDValue MaskNode) {
4828 MaskNode = peekThroughBitcasts(MaskNode);
4830 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4834 SDValue Ptr = MaskLoad->getBasePtr();
4835 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4836 Ptr->getOpcode() == X86ISD::WrapperRIP)
4837 Ptr = Ptr->getOperand(0);
4839 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4840 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4843 return dyn_cast<Constant>(MaskCP->getConstVal());
4846 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4847 /// If the mask could be calculated, returns it in \p Mask, returns the shuffle
4848 /// operands in \p Ops, and returns true.
4849 /// Sets \p IsUnary to true if only one source is used. Note that this will set
4850 /// IsUnary for shuffles which use a single input multiple times, and in those
4851 /// cases it will adjust the mask to only have indices within that single input.
4852 /// It is an error to call this with non-empty Mask/Ops vectors.
4853 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
4854 SmallVectorImpl<SDValue> &Ops,
4855 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4856 unsigned NumElems = VT.getVectorNumElements();
4859 assert(Mask.empty() && "getTargetShuffleMask expects an empty Mask vector");
4860 assert(Ops.empty() && "getTargetShuffleMask expects an empty Ops vector");
4863 bool IsFakeUnary = false;
4864 switch(N->getOpcode()) {
4865 case X86ISD::BLENDI:
4866 ImmN = N->getOperand(N->getNumOperands()-1);
4867 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4870 ImmN = N->getOperand(N->getNumOperands()-1);
4871 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4872 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4874 case X86ISD::INSERTPS:
4875 ImmN = N->getOperand(N->getNumOperands()-1);
4876 DecodeINSERTPSMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4877 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4879 case X86ISD::UNPCKH:
4880 DecodeUNPCKHMask(VT, Mask);
4881 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4883 case X86ISD::UNPCKL:
4884 DecodeUNPCKLMask(VT, Mask);
4885 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4887 case X86ISD::MOVHLPS:
4888 DecodeMOVHLPSMask(NumElems, Mask);
4889 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4891 case X86ISD::MOVLHPS:
4892 DecodeMOVLHPSMask(NumElems, Mask);
4893 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4895 case X86ISD::PALIGNR:
4896 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
4897 ImmN = N->getOperand(N->getNumOperands()-1);
4898 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4900 case X86ISD::VSHLDQ:
4901 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
4902 ImmN = N->getOperand(N->getNumOperands() - 1);
4903 DecodePSLLDQMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4906 case X86ISD::VSRLDQ:
4907 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
4908 ImmN = N->getOperand(N->getNumOperands() - 1);
4909 DecodePSRLDQMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4912 case X86ISD::PSHUFD:
4913 case X86ISD::VPERMILPI:
4914 ImmN = N->getOperand(N->getNumOperands()-1);
4915 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4918 case X86ISD::PSHUFHW:
4919 ImmN = N->getOperand(N->getNumOperands()-1);
4920 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4923 case X86ISD::PSHUFLW:
4924 ImmN = N->getOperand(N->getNumOperands()-1);
4925 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4928 case X86ISD::VZEXT_MOVL:
4929 DecodeZeroMoveLowMask(VT, Mask);
4932 case X86ISD::VBROADCAST: {
4933 // We only decode broadcasts of same-sized vectors at the moment.
4934 if (N->getOperand(0).getValueType() == VT) {
4935 DecodeVectorBroadcast(VT, Mask);
4941 case X86ISD::VPERMILPV: {
4943 SDValue MaskNode = N->getOperand(1);
4944 unsigned MaskEltSize = VT.getScalarSizeInBits();
4945 SmallVector<uint64_t, 32> RawMask;
4946 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask)) {
4947 DecodeVPERMILPMask(VT, RawMask, Mask);
4950 if (auto *C = getTargetShuffleMaskConstant(MaskNode)) {
4951 DecodeVPERMILPMask(C, MaskEltSize, Mask);
4956 case X86ISD::PSHUFB: {
4958 SDValue MaskNode = N->getOperand(1);
4959 SmallVector<uint64_t, 32> RawMask;
4960 if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask)) {
4961 DecodePSHUFBMask(RawMask, Mask);
4964 if (auto *C = getTargetShuffleMaskConstant(MaskNode)) {
4965 DecodePSHUFBMask(C, Mask);
4970 case X86ISD::VPERMI:
4971 ImmN = N->getOperand(N->getNumOperands()-1);
4972 DecodeVPERMMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4977 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4979 case X86ISD::VPERM2X128:
4980 ImmN = N->getOperand(N->getNumOperands()-1);
4981 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4982 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4984 case X86ISD::MOVSLDUP:
4985 DecodeMOVSLDUPMask(VT, Mask);
4988 case X86ISD::MOVSHDUP:
4989 DecodeMOVSHDUPMask(VT, Mask);
4992 case X86ISD::MOVDDUP:
4993 DecodeMOVDDUPMask(VT, Mask);
4996 case X86ISD::MOVLHPD:
4997 case X86ISD::MOVLPD:
4998 case X86ISD::MOVLPS:
4999 // Not yet implemented
5001 case X86ISD::VPERMIL2: {
5002 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5003 unsigned MaskEltSize = VT.getScalarSizeInBits();
5004 SDValue MaskNode = N->getOperand(2);
5005 SDValue CtrlNode = N->getOperand(3);
5006 if (ConstantSDNode *CtrlOp = dyn_cast<ConstantSDNode>(CtrlNode)) {
5007 unsigned CtrlImm = CtrlOp->getZExtValue();
5008 SmallVector<uint64_t, 32> RawMask;
5009 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask)) {
5010 DecodeVPERMIL2PMask(VT, CtrlImm, RawMask, Mask);
5013 if (auto *C = getTargetShuffleMaskConstant(MaskNode)) {
5014 DecodeVPERMIL2PMask(C, CtrlImm, MaskEltSize, Mask);
5020 case X86ISD::VPPERM: {
5021 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5022 SDValue MaskNode = N->getOperand(2);
5023 SmallVector<uint64_t, 32> RawMask;
5024 if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask)) {
5025 DecodeVPPERMMask(RawMask, Mask);
5028 if (auto *C = getTargetShuffleMaskConstant(MaskNode)) {
5029 DecodeVPPERMMask(C, Mask);
5034 case X86ISD::VPERMV: {
5036 // Unlike most shuffle nodes, VPERMV's mask operand is operand 0.
5037 Ops.push_back(N->getOperand(1));
5038 SDValue MaskNode = N->getOperand(0);
5039 SmallVector<uint64_t, 32> RawMask;
5040 unsigned MaskEltSize = VT.getScalarSizeInBits();
5041 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask)) {
5042 DecodeVPERMVMask(RawMask, Mask);
5045 if (auto *C = getTargetShuffleMaskConstant(MaskNode)) {
5046 DecodeVPERMVMask(C, VT, Mask);
5051 case X86ISD::VPERMV3: {
5052 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(2);
5053 // Unlike most shuffle nodes, VPERMV3's mask operand is the middle one.
5054 Ops.push_back(N->getOperand(0));
5055 Ops.push_back(N->getOperand(2));
5056 SDValue MaskNode = N->getOperand(1);
5057 if (auto *C = getTargetShuffleMaskConstant(MaskNode)) {
5058 DecodeVPERMV3Mask(C, VT, Mask);
5063 default: llvm_unreachable("unknown target shuffle node");
5066 // Empty mask indicates the decode failed.
5070 // Check if we're getting a shuffle mask with zero'd elements.
5071 if (!AllowSentinelZero)
5072 if (llvm::any_of(Mask, [](int M) { return M == SM_SentinelZero; }))
5075 // If we have a fake unary shuffle, the shuffle mask is spread across two
5076 // inputs that are actually the same node. Re-map the mask to always point
5077 // into the first input.
5080 if (M >= (int)Mask.size())
5083 // If we didn't already add operands in the opcode-specific code, default to
5084 // adding 1 or 2 operands starting at 0.
5086 Ops.push_back(N->getOperand(0));
5087 if (!IsUnary || IsFakeUnary)
5088 Ops.push_back(N->getOperand(1));
5094 /// Check a target shuffle mask's inputs to see if we can set any values to
5095 /// SM_SentinelZero - this is for elements that are known to be zero
5096 /// (not just zeroable) from their inputs.
5097 /// Returns true if the target shuffle mask was decoded.
5098 static bool setTargetShuffleZeroElements(SDValue N,
5099 SmallVectorImpl<int> &Mask,
5100 SmallVectorImpl<SDValue> &Ops) {
5102 if (!isTargetShuffle(N.getOpcode()))
5104 if (!getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), true, Ops,
5108 SDValue V1 = Ops[0];
5109 SDValue V2 = IsUnary ? V1 : Ops[1];
5111 V1 = peekThroughBitcasts(V1);
5112 V2 = peekThroughBitcasts(V2);
5114 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
5117 // Already decoded as SM_SentinelZero / SM_SentinelUndef.
5121 // Determine shuffle input and normalize the mask.
5122 SDValue V = M < Size ? V1 : V2;
5125 // We are referencing an UNDEF input.
5127 Mask[i] = SM_SentinelUndef;
5131 // Currently we can only search BUILD_VECTOR for UNDEF/ZERO elements.
5132 if (V.getOpcode() != ISD::BUILD_VECTOR)
5135 // If the BUILD_VECTOR has fewer elements then the (larger) source
5136 // element must be UNDEF/ZERO.
5137 // TODO: Is it worth testing the individual bits of a constant?
5138 if ((Size % V.getNumOperands()) == 0) {
5139 int Scale = Size / V->getNumOperands();
5140 SDValue Op = V.getOperand(M / Scale);
5142 Mask[i] = SM_SentinelUndef;
5143 else if (X86::isZeroNode(Op))
5144 Mask[i] = SM_SentinelZero;
5148 // If the BUILD_VECTOR has more elements then all the (smaller) source
5149 // elements must be all UNDEF or all ZERO.
5150 if ((V.getNumOperands() % Size) == 0) {
5151 int Scale = V->getNumOperands() / Size;
5152 bool AllUndef = true;
5153 bool AllZero = true;
5154 for (int j = 0; j < Scale; ++j) {
5155 SDValue Op = V.getOperand((M * Scale) + j);
5156 AllUndef &= Op.isUndef();
5157 AllZero &= X86::isZeroNode(Op);
5160 Mask[i] = SM_SentinelUndef;
5162 Mask[i] = SM_SentinelZero;
5170 /// Calls setTargetShuffleZeroElements to resolve a target shuffle mask's inputs
5171 /// and set the SM_SentinelUndef and SM_SentinelZero values. Then check the
5172 /// remaining input indices in case we now have a unary shuffle and adjust the
5173 /// Op0/Op1 inputs accordingly.
5174 /// Returns true if the target shuffle mask was decoded.
5175 static bool resolveTargetShuffleInputs(SDValue Op, SDValue &Op0, SDValue &Op1,
5176 SmallVectorImpl<int> &Mask) {
5177 SmallVector<SDValue, 2> Ops;
5178 if (!setTargetShuffleZeroElements(Op, Mask, Ops))
5181 int NumElts = Mask.size();
5182 bool Op0InUse = std::any_of(Mask.begin(), Mask.end(), [NumElts](int Idx) {
5183 return 0 <= Idx && Idx < NumElts;
5185 bool Op1InUse = std::any_of(Mask.begin(), Mask.end(),
5186 [NumElts](int Idx) { return NumElts <= Idx; });
5188 Op0 = Op0InUse ? Ops[0] : SDValue();
5189 Op1 = Op1InUse ? Ops[1] : SDValue();
5191 // We're only using Op1 - commute the mask and inputs.
5192 if (!Op0InUse && Op1InUse) {
5203 /// Returns the scalar element that will make up the ith
5204 /// element of the result of the vector shuffle.
5205 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5208 return SDValue(); // Limit search depth.
5210 SDValue V = SDValue(N, 0);
5211 EVT VT = V.getValueType();
5212 unsigned Opcode = V.getOpcode();
5214 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5215 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5216 int Elt = SV->getMaskElt(Index);
5219 return DAG.getUNDEF(VT.getVectorElementType());
5221 unsigned NumElems = VT.getVectorNumElements();
5222 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5223 : SV->getOperand(1);
5224 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5227 // Recurse into target specific vector shuffles to find scalars.
5228 if (isTargetShuffle(Opcode)) {
5229 MVT ShufVT = V.getSimpleValueType();
5230 MVT ShufSVT = ShufVT.getVectorElementType();
5231 int NumElems = (int)ShufVT.getVectorNumElements();
5232 SmallVector<int, 16> ShuffleMask;
5233 SmallVector<SDValue, 16> ShuffleOps;
5236 if (!getTargetShuffleMask(N, ShufVT, true, ShuffleOps, ShuffleMask, IsUnary))
5239 int Elt = ShuffleMask[Index];
5240 if (Elt == SM_SentinelZero)
5241 return ShufSVT.isInteger() ? DAG.getConstant(0, SDLoc(N), ShufSVT)
5242 : DAG.getConstantFP(+0.0, SDLoc(N), ShufSVT);
5243 if (Elt == SM_SentinelUndef)
5244 return DAG.getUNDEF(ShufSVT);
5246 assert(0 <= Elt && Elt < (2*NumElems) && "Shuffle index out of range");
5247 SDValue NewV = (Elt < NumElems) ? ShuffleOps[0] : ShuffleOps[1];
5248 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5252 // Actual nodes that may contain scalar elements
5253 if (Opcode == ISD::BITCAST) {
5254 V = V.getOperand(0);
5255 EVT SrcVT = V.getValueType();
5256 unsigned NumElems = VT.getVectorNumElements();
5258 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5262 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5263 return (Index == 0) ? V.getOperand(0)
5264 : DAG.getUNDEF(VT.getVectorElementType());
5266 if (V.getOpcode() == ISD::BUILD_VECTOR)
5267 return V.getOperand(Index);
5272 /// Custom lower build_vector of v16i8.
5273 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5274 unsigned NumNonZero, unsigned NumZero,
5276 const X86Subtarget &Subtarget,
5277 const TargetLowering &TLI) {
5285 // SSE4.1 - use PINSRB to insert each byte directly.
5286 if (Subtarget.hasSSE41()) {
5287 for (unsigned i = 0; i < 16; ++i) {
5288 bool isNonZero = (NonZeros & (1 << i)) != 0;
5292 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
5294 V = DAG.getUNDEF(MVT::v16i8);
5297 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5298 MVT::v16i8, V, Op.getOperand(i),
5299 DAG.getIntPtrConstant(i, dl));
5306 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5307 for (unsigned i = 0; i < 16; ++i) {
5308 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5309 if (ThisIsNonZero && First) {
5311 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5313 V = DAG.getUNDEF(MVT::v8i16);
5318 SDValue ThisElt, LastElt;
5319 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5320 if (LastIsNonZero) {
5321 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5322 MVT::i16, Op.getOperand(i-1));
5324 if (ThisIsNonZero) {
5325 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5326 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5327 ThisElt, DAG.getConstant(8, dl, MVT::i8));
5329 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5333 if (ThisElt.getNode())
5334 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5335 DAG.getIntPtrConstant(i/2, dl));
5339 return DAG.getBitcast(MVT::v16i8, V);
5342 /// Custom lower build_vector of v8i16.
5343 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5344 unsigned NumNonZero, unsigned NumZero,
5346 const X86Subtarget &Subtarget,
5347 const TargetLowering &TLI) {
5354 for (unsigned i = 0; i < 8; ++i) {
5355 bool isNonZero = (NonZeros & (1 << i)) != 0;
5359 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5361 V = DAG.getUNDEF(MVT::v8i16);
5364 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5365 MVT::v8i16, V, Op.getOperand(i),
5366 DAG.getIntPtrConstant(i, dl));
5373 /// Custom lower build_vector of v4i32 or v4f32.
5374 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5375 const X86Subtarget &Subtarget,
5376 const TargetLowering &TLI) {
5377 // Find all zeroable elements.
5378 std::bitset<4> Zeroable;
5379 for (int i=0; i < 4; ++i) {
5380 SDValue Elt = Op->getOperand(i);
5381 Zeroable[i] = (Elt.isUndef() || X86::isZeroNode(Elt));
5383 assert(Zeroable.size() - Zeroable.count() > 1 &&
5384 "We expect at least two non-zero elements!");
5386 // We only know how to deal with build_vector nodes where elements are either
5387 // zeroable or extract_vector_elt with constant index.
5388 SDValue FirstNonZero;
5389 unsigned FirstNonZeroIdx;
5390 for (unsigned i=0; i < 4; ++i) {
5393 SDValue Elt = Op->getOperand(i);
5394 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5395 !isa<ConstantSDNode>(Elt.getOperand(1)))
5397 // Make sure that this node is extracting from a 128-bit vector.
5398 MVT VT = Elt.getOperand(0).getSimpleValueType();
5399 if (!VT.is128BitVector())
5401 if (!FirstNonZero.getNode()) {
5403 FirstNonZeroIdx = i;
5407 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5408 SDValue V1 = FirstNonZero.getOperand(0);
5409 MVT VT = V1.getSimpleValueType();
5411 // See if this build_vector can be lowered as a blend with zero.
5413 unsigned EltMaskIdx, EltIdx;
5415 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5416 if (Zeroable[EltIdx]) {
5417 // The zero vector will be on the right hand side.
5418 Mask[EltIdx] = EltIdx+4;
5422 Elt = Op->getOperand(EltIdx);
5423 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5424 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5425 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5427 Mask[EltIdx] = EltIdx;
5431 // Let the shuffle legalizer deal with blend operations.
5432 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5433 if (V1.getSimpleValueType() != VT)
5434 V1 = DAG.getBitcast(VT, V1);
5435 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, Mask);
5438 // See if we can lower this build_vector to a INSERTPS.
5439 if (!Subtarget.hasSSE41())
5442 SDValue V2 = Elt.getOperand(0);
5443 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5446 bool CanFold = true;
5447 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5451 SDValue Current = Op->getOperand(i);
5452 SDValue SrcVector = Current->getOperand(0);
5455 CanFold = SrcVector == V1 &&
5456 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5462 assert(V1.getNode() && "Expected at least two non-zero elements!");
5463 if (V1.getSimpleValueType() != MVT::v4f32)
5464 V1 = DAG.getBitcast(MVT::v4f32, V1);
5465 if (V2.getSimpleValueType() != MVT::v4f32)
5466 V2 = DAG.getBitcast(MVT::v4f32, V2);
5468 // Ok, we can emit an INSERTPS instruction.
5469 unsigned ZMask = Zeroable.to_ulong();
5471 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5472 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5474 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5475 DAG.getIntPtrConstant(InsertPSMask, DL));
5476 return DAG.getBitcast(VT, Result);
5479 /// Return a vector logical shift node.
5480 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, unsigned NumBits,
5481 SelectionDAG &DAG, const TargetLowering &TLI,
5483 assert(VT.is128BitVector() && "Unknown type for VShift");
5484 MVT ShVT = MVT::v16i8;
5485 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5486 SrcOp = DAG.getBitcast(ShVT, SrcOp);
5487 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5488 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5489 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5490 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5493 static SDValue LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, const SDLoc &dl,
5494 SelectionDAG &DAG) {
5496 // Check if the scalar load can be widened into a vector load. And if
5497 // the address is "base + cst" see if the cst can be "absorbed" into
5498 // the shuffle mask.
5499 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5500 SDValue Ptr = LD->getBasePtr();
5501 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5503 EVT PVT = LD->getValueType(0);
5504 if (PVT != MVT::i32 && PVT != MVT::f32)
5509 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5510 FI = FINode->getIndex();
5512 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5513 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5514 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5515 Offset = Ptr.getConstantOperandVal(1);
5516 Ptr = Ptr.getOperand(0);
5521 // FIXME: 256-bit vector instructions don't require a strict alignment,
5522 // improve this code to support it better.
5523 unsigned RequiredAlign = VT.getSizeInBits()/8;
5524 SDValue Chain = LD->getChain();
5525 // Make sure the stack object alignment is at least 16 or 32.
5526 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5527 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5528 if (MFI->isFixedObjectIndex(FI)) {
5529 // Can't change the alignment. FIXME: It's possible to compute
5530 // the exact stack offset and reference FI + adjust offset instead.
5531 // If someone *really* cares about this. That's the way to implement it.
5534 MFI->setObjectAlignment(FI, RequiredAlign);
5538 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5539 // Ptr + (Offset & ~15).
5542 if ((Offset % RequiredAlign) & 3)
5544 int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5547 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5548 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5551 int EltNo = (Offset - StartOffset) >> 2;
5552 unsigned NumElems = VT.getVectorNumElements();
5554 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5555 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5556 LD->getPointerInfo().getWithOffset(StartOffset));
5558 SmallVector<int, 8> Mask(NumElems, EltNo);
5560 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), Mask);
5566 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5567 /// elements can be replaced by a single large load which has the same value as
5568 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5570 /// Example: <load i32 *a, load i32 *a+4, zero, undef> -> zextload a
5571 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5572 SDLoc &DL, SelectionDAG &DAG,
5573 bool isAfterLegalize) {
5574 unsigned NumElems = Elts.size();
5576 int LastLoadedElt = -1;
5577 SmallBitVector LoadMask(NumElems, false);
5578 SmallBitVector ZeroMask(NumElems, false);
5579 SmallBitVector UndefMask(NumElems, false);
5581 // For each element in the initializer, see if we've found a load, zero or an
5583 for (unsigned i = 0; i < NumElems; ++i) {
5584 SDValue Elt = peekThroughBitcasts(Elts[i]);
5589 UndefMask[i] = true;
5590 else if (X86::isZeroNode(Elt) || ISD::isBuildVectorAllZeros(Elt.getNode()))
5592 else if (ISD::isNON_EXTLoad(Elt.getNode())) {
5595 // Each loaded element must be the correct fractional portion of the
5596 // requested vector load.
5597 if ((NumElems * Elt.getValueSizeInBits()) != VT.getSizeInBits())
5602 assert((ZeroMask | UndefMask | LoadMask).count() == NumElems &&
5603 "Incomplete element masks");
5605 // Handle Special Cases - all undef or undef/zero.
5606 if (UndefMask.count() == NumElems)
5607 return DAG.getUNDEF(VT);
5609 // FIXME: Should we return this as a BUILD_VECTOR instead?
5610 if ((ZeroMask | UndefMask).count() == NumElems)
5611 return VT.isInteger() ? DAG.getConstant(0, DL, VT)
5612 : DAG.getConstantFP(0.0, DL, VT);
5614 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5615 int FirstLoadedElt = LoadMask.find_first();
5616 SDValue EltBase = peekThroughBitcasts(Elts[FirstLoadedElt]);
5617 LoadSDNode *LDBase = cast<LoadSDNode>(EltBase);
5618 EVT LDBaseVT = EltBase.getValueType();
5620 // Consecutive loads can contain UNDEFS but not ZERO elements.
5621 // Consecutive loads with UNDEFs and ZEROs elements require a
5622 // an additional shuffle stage to clear the ZERO elements.
5623 bool IsConsecutiveLoad = true;
5624 bool IsConsecutiveLoadWithZeros = true;
5625 for (int i = FirstLoadedElt + 1; i <= LastLoadedElt; ++i) {
5627 SDValue Elt = peekThroughBitcasts(Elts[i]);
5628 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5629 if (!DAG.areNonVolatileConsecutiveLoads(
5630 LD, LDBase, Elt.getValueType().getStoreSizeInBits() / 8,
5631 i - FirstLoadedElt)) {
5632 IsConsecutiveLoad = false;
5633 IsConsecutiveLoadWithZeros = false;
5636 } else if (ZeroMask[i]) {
5637 IsConsecutiveLoad = false;
5641 auto CreateLoad = [&DAG, &DL](EVT VT, LoadSDNode *LDBase) {
5642 auto MMOFlags = LDBase->getMemOperand()->getFlags();
5643 assert(!(MMOFlags & MachineMemOperand::MOVolatile) &&
5644 "Cannot merge volatile loads.");
5646 DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5647 LDBase->getPointerInfo(), LDBase->getAlignment(), MMOFlags);
5649 if (LDBase->hasAnyUseOfValue(1)) {
5651 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, SDValue(LDBase, 1),
5652 SDValue(NewLd.getNode(), 1));
5653 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5654 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5655 SDValue(NewLd.getNode(), 1));
5661 // LOAD - all consecutive load/undefs (must start/end with a load).
5662 // If we have found an entire vector of loads and undefs, then return a large
5663 // load of the entire vector width starting at the base pointer.
5664 // If the vector contains zeros, then attempt to shuffle those elements.
5665 if (FirstLoadedElt == 0 && LastLoadedElt == (int)(NumElems - 1) &&
5666 (IsConsecutiveLoad || IsConsecutiveLoadWithZeros)) {
5667 assert(LDBase && "Did not find base load for merging consecutive loads");
5668 EVT EltVT = LDBase->getValueType(0);
5669 // Ensure that the input vector size for the merged loads matches the
5670 // cumulative size of the input elements.
5671 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5674 if (isAfterLegalize && !TLI.isOperationLegal(ISD::LOAD, VT))
5677 if (IsConsecutiveLoad)
5678 return CreateLoad(VT, LDBase);
5680 // IsConsecutiveLoadWithZeros - we need to create a shuffle of the loaded
5681 // vector and a zero vector to clear out the zero elements.
5682 if (!isAfterLegalize && NumElems == VT.getVectorNumElements()) {
5683 SmallVector<int, 4> ClearMask(NumElems, -1);
5684 for (unsigned i = 0; i < NumElems; ++i) {
5686 ClearMask[i] = i + NumElems;
5687 else if (LoadMask[i])
5690 SDValue V = CreateLoad(VT, LDBase);
5691 SDValue Z = VT.isInteger() ? DAG.getConstant(0, DL, VT)
5692 : DAG.getConstantFP(0.0, DL, VT);
5693 return DAG.getVectorShuffle(VT, DL, V, Z, ClearMask);
5698 (1 + LastLoadedElt - FirstLoadedElt) * LDBaseVT.getStoreSizeInBits();
5700 // VZEXT_LOAD - consecutive load/undefs followed by zeros/undefs.
5701 if (IsConsecutiveLoad && FirstLoadedElt == 0 && LoadSize == 64 &&
5702 ((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))) {
5703 MVT VecSVT = VT.isFloatingPoint() ? MVT::f64 : MVT::i64;
5704 MVT VecVT = MVT::getVectorVT(VecSVT, VT.getSizeInBits() / 64);
5705 if (TLI.isTypeLegal(VecVT)) {
5706 SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
5707 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5709 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, VecSVT,
5710 LDBase->getPointerInfo(),
5711 LDBase->getAlignment(),
5712 false/*isVolatile*/, true/*ReadMem*/,
5715 // Make sure the newly-created LOAD is in the same position as LDBase in
5716 // terms of dependency. We create a TokenFactor for LDBase and ResNode,
5717 // and update uses of LDBase's output chain to use the TokenFactor.
5718 if (LDBase->hasAnyUseOfValue(1)) {
5720 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, SDValue(LDBase, 1),
5721 SDValue(ResNode.getNode(), 1));
5722 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5723 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5724 SDValue(ResNode.getNode(), 1));
5727 return DAG.getBitcast(VT, ResNode);
5731 // VZEXT_MOVL - consecutive 32-bit load/undefs followed by zeros/undefs.
5732 if (IsConsecutiveLoad && FirstLoadedElt == 0 && LoadSize == 32 &&
5733 ((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))) {
5734 MVT VecSVT = VT.isFloatingPoint() ? MVT::f32 : MVT::i32;
5735 MVT VecVT = MVT::getVectorVT(VecSVT, VT.getSizeInBits() / 32);
5736 if (TLI.isTypeLegal(VecVT)) {
5737 SDValue V = LastLoadedElt != 0 ? CreateLoad(VecSVT, LDBase)
5738 : DAG.getBitcast(VecSVT, EltBase);
5739 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, V);
5740 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, VecVT, V);
5741 return DAG.getBitcast(VT, V);
5748 /// Attempt to use the vbroadcast instruction to generate a splat value for the
5749 /// following cases:
5750 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5751 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5752 /// a scalar load, or a constant.
5753 /// The VBROADCAST node is returned when a pattern is found,
5754 /// or SDValue() otherwise.
5755 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget &Subtarget,
5756 SelectionDAG &DAG) {
5757 // VBROADCAST requires AVX.
5758 // TODO: Splats could be generated for non-AVX CPUs using SSE
5759 // instructions, but there's less potential gain for only 128-bit vectors.
5760 if (!Subtarget.hasAVX())
5763 MVT VT = Op.getSimpleValueType();
5766 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5767 "Unsupported vector type for broadcast.");
5772 switch (Op.getOpcode()) {
5774 // Unknown pattern found.
5777 case ISD::BUILD_VECTOR: {
5778 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5779 BitVector UndefElements;
5780 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5782 // We need a splat of a single value to use broadcast, and it doesn't
5783 // make any sense if the value is only in one element of the vector.
5784 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5788 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5789 Ld.getOpcode() == ISD::ConstantFP);
5791 // Make sure that all of the users of a non-constant load are from the
5792 // BUILD_VECTOR node.
5793 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5798 case ISD::VECTOR_SHUFFLE: {
5799 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5801 // Shuffles must have a splat mask where the first element is
5803 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5806 SDValue Sc = Op.getOperand(0);
5807 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5808 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5810 if (!Subtarget.hasInt256())
5813 // Use the register form of the broadcast instruction available on AVX2.
5814 if (VT.getSizeInBits() >= 256)
5815 Sc = extract128BitVector(Sc, 0, DAG, dl);
5816 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5819 Ld = Sc.getOperand(0);
5820 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5821 Ld.getOpcode() == ISD::ConstantFP);
5823 // The scalar_to_vector node and the suspected
5824 // load node must have exactly one user.
5825 // Constants may have multiple users.
5827 // AVX-512 has register version of the broadcast
5828 bool hasRegVer = Subtarget.hasAVX512() && VT.is512BitVector() &&
5829 Ld.getValueType().getSizeInBits() >= 32;
5830 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5837 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5838 bool IsGE256 = (VT.getSizeInBits() >= 256);
5840 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5841 // instruction to save 8 or more bytes of constant pool data.
5842 // TODO: If multiple splats are generated to load the same constant,
5843 // it may be detrimental to overall size. There needs to be a way to detect
5844 // that condition to know if this is truly a size win.
5845 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5847 // Handle broadcasting a single constant scalar from the constant pool
5849 // On Sandybridge (no AVX2), it is still better to load a constant vector
5850 // from the constant pool and not to broadcast it from a scalar.
5851 // But override that restriction when optimizing for size.
5852 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5853 if (ConstSplatVal && (Subtarget.hasAVX2() || OptForSize)) {
5854 EVT CVT = Ld.getValueType();
5855 assert(!CVT.isVector() && "Must not broadcast a vector type");
5857 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5858 // For size optimization, also splat v2f64 and v2i64, and for size opt
5859 // with AVX2, also splat i8 and i16.
5860 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5861 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5862 (OptForSize && (ScalarSize == 64 || Subtarget.hasAVX2()))) {
5863 const Constant *C = nullptr;
5864 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5865 C = CI->getConstantIntValue();
5866 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5867 C = CF->getConstantFPValue();
5869 assert(C && "Invalid constant type");
5871 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5873 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5874 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5876 CVT, dl, DAG.getEntryNode(), CP,
5877 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
5880 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5884 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5886 // Handle AVX2 in-register broadcasts.
5887 if (!IsLoad && Subtarget.hasInt256() &&
5888 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5889 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5891 // The scalar source must be a normal load.
5895 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5896 (Subtarget.hasVLX() && ScalarSize == 64))
5897 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5899 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5900 // double since there is no vbroadcastsd xmm
5901 if (Subtarget.hasInt256() && Ld.getValueType().isInteger()) {
5902 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5903 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5906 // Unsupported broadcast.
5910 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5911 /// underlying vector and index.
5913 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5915 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5917 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5918 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5921 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5923 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5925 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5926 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5929 // In this case the vector is the extract_subvector expression and the index
5930 // is 2, as specified by the shuffle.
5931 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5932 SDValue ShuffleVec = SVOp->getOperand(0);
5933 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5934 assert(ShuffleVecVT.getVectorElementType() ==
5935 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5937 int ShuffleIdx = SVOp->getMaskElt(Idx);
5938 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5939 ExtractedFromVec = ShuffleVec;
5945 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5946 MVT VT = Op.getSimpleValueType();
5948 // Skip if insert_vec_elt is not supported.
5949 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5950 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5954 unsigned NumElems = Op.getNumOperands();
5958 SmallVector<unsigned, 4> InsertIndices;
5959 SmallVector<int, 8> Mask(NumElems, -1);
5961 for (unsigned i = 0; i != NumElems; ++i) {
5962 unsigned Opc = Op.getOperand(i).getOpcode();
5964 if (Opc == ISD::UNDEF)
5967 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5968 // Quit if more than 1 elements need inserting.
5969 if (InsertIndices.size() > 1)
5972 InsertIndices.push_back(i);
5976 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5977 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5978 // Quit if non-constant index.
5979 if (!isa<ConstantSDNode>(ExtIdx))
5981 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5983 // Quit if extracted from vector of different type.
5984 if (ExtractedFromVec.getValueType() != VT)
5987 if (!VecIn1.getNode())
5988 VecIn1 = ExtractedFromVec;
5989 else if (VecIn1 != ExtractedFromVec) {
5990 if (!VecIn2.getNode())
5991 VecIn2 = ExtractedFromVec;
5992 else if (VecIn2 != ExtractedFromVec)
5993 // Quit if more than 2 vectors to shuffle
5997 if (ExtractedFromVec == VecIn1)
5999 else if (ExtractedFromVec == VecIn2)
6000 Mask[i] = Idx + NumElems;
6003 if (!VecIn1.getNode())
6006 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6007 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, Mask);
6008 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6009 unsigned Idx = InsertIndices[i];
6010 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6011 DAG.getIntPtrConstant(Idx, DL));
6017 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
6018 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
6019 Op.getScalarValueSizeInBits() == 1 &&
6020 "Can not convert non-constant vector");
6021 uint64_t Immediate = 0;
6022 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6023 SDValue In = Op.getOperand(idx);
6025 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
6029 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
6030 return DAG.getConstant(Immediate, dl, VT);
6032 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6034 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6036 MVT VT = Op.getSimpleValueType();
6037 assert((VT.getVectorElementType() == MVT::i1) &&
6038 "Unexpected type in LowerBUILD_VECTORvXi1!");
6041 if (ISD::isBuildVectorAllZeros(Op.getNode()))
6042 return DAG.getTargetConstant(0, dl, VT);
6044 if (ISD::isBuildVectorAllOnes(Op.getNode()))
6045 return DAG.getTargetConstant(1, dl, VT);
6047 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
6048 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
6049 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
6050 return DAG.getBitcast(VT, Imm);
6051 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
6052 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
6053 DAG.getIntPtrConstant(0, dl));
6056 // Vector has one or more non-const elements
6057 uint64_t Immediate = 0;
6058 SmallVector<unsigned, 16> NonConstIdx;
6059 bool IsSplat = true;
6060 bool HasConstElts = false;
6062 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6063 SDValue In = Op.getOperand(idx);
6066 if (!isa<ConstantSDNode>(In))
6067 NonConstIdx.push_back(idx);
6069 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
6070 HasConstElts = true;
6074 else if (In != Op.getOperand(SplatIdx))
6078 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
6080 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
6081 DAG.getConstant(1, dl, VT),
6082 DAG.getConstant(0, dl, VT));
6084 // insert elements one by one
6088 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
6089 Imm = DAG.getConstant(Immediate, dl, ImmVT);
6091 else if (HasConstElts)
6092 Imm = DAG.getConstant(0, dl, VT);
6094 Imm = DAG.getUNDEF(VT);
6095 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
6096 DstVec = DAG.getBitcast(VT, Imm);
6098 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
6099 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
6100 DAG.getIntPtrConstant(0, dl));
6103 for (unsigned i = 0, e = NonConstIdx.size(); i != e; ++i) {
6104 unsigned InsertIdx = NonConstIdx[i];
6105 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6106 Op.getOperand(InsertIdx),
6107 DAG.getIntPtrConstant(InsertIdx, dl));
6112 /// \brief Return true if \p N implements a horizontal binop and return the
6113 /// operands for the horizontal binop into V0 and V1.
6115 /// This is a helper function of LowerToHorizontalOp().
6116 /// This function checks that the build_vector \p N in input implements a
6117 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6118 /// operation to match.
6119 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6120 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6121 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6124 /// This function only analyzes elements of \p N whose indices are
6125 /// in range [BaseIdx, LastIdx).
6126 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6128 unsigned BaseIdx, unsigned LastIdx,
6129 SDValue &V0, SDValue &V1) {
6130 EVT VT = N->getValueType(0);
6132 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6133 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6134 "Invalid Vector in input!");
6136 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6137 bool CanFold = true;
6138 unsigned ExpectedVExtractIdx = BaseIdx;
6139 unsigned NumElts = LastIdx - BaseIdx;
6140 V0 = DAG.getUNDEF(VT);
6141 V1 = DAG.getUNDEF(VT);
6143 // Check if N implements a horizontal binop.
6144 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6145 SDValue Op = N->getOperand(i + BaseIdx);
6148 if (Op->isUndef()) {
6149 // Update the expected vector extract index.
6150 if (i * 2 == NumElts)
6151 ExpectedVExtractIdx = BaseIdx;
6152 ExpectedVExtractIdx += 2;
6156 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6161 SDValue Op0 = Op.getOperand(0);
6162 SDValue Op1 = Op.getOperand(1);
6164 // Try to match the following pattern:
6165 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6166 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6167 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6168 Op0.getOperand(0) == Op1.getOperand(0) &&
6169 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6170 isa<ConstantSDNode>(Op1.getOperand(1)));
6174 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6175 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6177 if (i * 2 < NumElts) {
6179 V0 = Op0.getOperand(0);
6180 if (V0.getValueType() != VT)
6185 V1 = Op0.getOperand(0);
6186 if (V1.getValueType() != VT)
6189 if (i * 2 == NumElts)
6190 ExpectedVExtractIdx = BaseIdx;
6193 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6194 if (I0 == ExpectedVExtractIdx)
6195 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6196 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6197 // Try to match the following dag sequence:
6198 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6199 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6203 ExpectedVExtractIdx += 2;
6209 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6210 /// a concat_vector.
6212 /// This is a helper function of LowerToHorizontalOp().
6213 /// This function expects two 256-bit vectors called V0 and V1.
6214 /// At first, each vector is split into two separate 128-bit vectors.
6215 /// Then, the resulting 128-bit vectors are used to implement two
6216 /// horizontal binary operations.
6218 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6220 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6221 /// the two new horizontal binop.
6222 /// When Mode is set, the first horizontal binop dag node would take as input
6223 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6224 /// horizontal binop dag node would take as input the lower 128-bit of V1
6225 /// and the upper 128-bit of V1.
6227 /// HADD V0_LO, V0_HI
6228 /// HADD V1_LO, V1_HI
6230 /// Otherwise, the first horizontal binop dag node takes as input the lower
6231 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6232 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
6234 /// HADD V0_LO, V1_LO
6235 /// HADD V0_HI, V1_HI
6237 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6238 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6239 /// the upper 128-bits of the result.
6240 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6241 const SDLoc &DL, SelectionDAG &DAG,
6242 unsigned X86Opcode, bool Mode,
6243 bool isUndefLO, bool isUndefHI) {
6244 MVT VT = V0.getSimpleValueType();
6245 assert(VT.is256BitVector() && VT == V1.getSimpleValueType() &&
6246 "Invalid nodes in input!");
6248 unsigned NumElts = VT.getVectorNumElements();
6249 SDValue V0_LO = extract128BitVector(V0, 0, DAG, DL);
6250 SDValue V0_HI = extract128BitVector(V0, NumElts/2, DAG, DL);
6251 SDValue V1_LO = extract128BitVector(V1, 0, DAG, DL);
6252 SDValue V1_HI = extract128BitVector(V1, NumElts/2, DAG, DL);
6253 MVT NewVT = V0_LO.getSimpleValueType();
6255 SDValue LO = DAG.getUNDEF(NewVT);
6256 SDValue HI = DAG.getUNDEF(NewVT);
6259 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6260 if (!isUndefLO && !V0->isUndef())
6261 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6262 if (!isUndefHI && !V1->isUndef())
6263 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6265 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6266 if (!isUndefLO && (!V0_LO->isUndef() || !V1_LO->isUndef()))
6267 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6269 if (!isUndefHI && (!V0_HI->isUndef() || !V1_HI->isUndef()))
6270 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6273 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6276 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
6278 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
6279 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
6280 MVT VT = BV->getSimpleValueType(0);
6281 if ((!Subtarget.hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
6282 (!Subtarget.hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
6286 unsigned NumElts = VT.getVectorNumElements();
6287 SDValue InVec0 = DAG.getUNDEF(VT);
6288 SDValue InVec1 = DAG.getUNDEF(VT);
6290 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6291 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6293 // Odd-numbered elements in the input build vector are obtained from
6294 // adding two integer/float elements.
6295 // Even-numbered elements in the input build vector are obtained from
6296 // subtracting two integer/float elements.
6297 unsigned ExpectedOpcode = ISD::FSUB;
6298 unsigned NextExpectedOpcode = ISD::FADD;
6299 bool AddFound = false;
6300 bool SubFound = false;
6302 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6303 SDValue Op = BV->getOperand(i);
6305 // Skip 'undef' values.
6306 unsigned Opcode = Op.getOpcode();
6307 if (Opcode == ISD::UNDEF) {
6308 std::swap(ExpectedOpcode, NextExpectedOpcode);
6312 // Early exit if we found an unexpected opcode.
6313 if (Opcode != ExpectedOpcode)
6316 SDValue Op0 = Op.getOperand(0);
6317 SDValue Op1 = Op.getOperand(1);
6319 // Try to match the following pattern:
6320 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6321 // Early exit if we cannot match that sequence.
6322 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6323 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6324 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6325 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6326 Op0.getOperand(1) != Op1.getOperand(1))
6329 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6333 // We found a valid add/sub node. Update the information accordingly.
6339 // Update InVec0 and InVec1.
6340 if (InVec0.isUndef()) {
6341 InVec0 = Op0.getOperand(0);
6342 if (InVec0.getSimpleValueType() != VT)
6345 if (InVec1.isUndef()) {
6346 InVec1 = Op1.getOperand(0);
6347 if (InVec1.getSimpleValueType() != VT)
6351 // Make sure that operands in input to each add/sub node always
6352 // come from a same pair of vectors.
6353 if (InVec0 != Op0.getOperand(0)) {
6354 if (ExpectedOpcode == ISD::FSUB)
6357 // FADD is commutable. Try to commute the operands
6358 // and then test again.
6359 std::swap(Op0, Op1);
6360 if (InVec0 != Op0.getOperand(0))
6364 if (InVec1 != Op1.getOperand(0))
6367 // Update the pair of expected opcodes.
6368 std::swap(ExpectedOpcode, NextExpectedOpcode);
6371 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6372 if (AddFound && SubFound && !InVec0.isUndef() && !InVec1.isUndef())
6373 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6378 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6379 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6380 const X86Subtarget &Subtarget,
6381 SelectionDAG &DAG) {
6382 MVT VT = BV->getSimpleValueType(0);
6383 unsigned NumElts = VT.getVectorNumElements();
6384 unsigned NumUndefsLO = 0;
6385 unsigned NumUndefsHI = 0;
6386 unsigned Half = NumElts/2;
6388 // Count the number of UNDEF operands in the build_vector in input.
6389 for (unsigned i = 0, e = Half; i != e; ++i)
6390 if (BV->getOperand(i)->isUndef())
6393 for (unsigned i = Half, e = NumElts; i != e; ++i)
6394 if (BV->getOperand(i)->isUndef())
6397 // Early exit if this is either a build_vector of all UNDEFs or all the
6398 // operands but one are UNDEF.
6399 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6403 SDValue InVec0, InVec1;
6404 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget.hasSSE3()) {
6405 // Try to match an SSE3 float HADD/HSUB.
6406 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6407 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6409 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6410 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6411 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget.hasSSSE3()) {
6412 // Try to match an SSSE3 integer HADD/HSUB.
6413 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6414 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6416 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6417 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6420 if (!Subtarget.hasAVX())
6423 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6424 // Try to match an AVX horizontal add/sub of packed single/double
6425 // precision floating point values from 256-bit vectors.
6426 SDValue InVec2, InVec3;
6427 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6428 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6429 ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
6430 ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
6431 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6433 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6434 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6435 ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
6436 ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
6437 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6438 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6439 // Try to match an AVX2 horizontal add/sub of signed integers.
6440 SDValue InVec2, InVec3;
6442 bool CanFold = true;
6444 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6445 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6446 ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
6447 ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
6448 X86Opcode = X86ISD::HADD;
6449 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6450 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6451 ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
6452 ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
6453 X86Opcode = X86ISD::HSUB;
6458 // Fold this build_vector into a single horizontal add/sub.
6459 // Do this only if the target has AVX2.
6460 if (Subtarget.hasAVX2())
6461 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6463 // Do not try to expand this build_vector into a pair of horizontal
6464 // add/sub if we can emit a pair of scalar add/sub.
6465 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6468 // Convert this build_vector into a pair of horizontal binop followed by
6470 bool isUndefLO = NumUndefsLO == Half;
6471 bool isUndefHI = NumUndefsHI == Half;
6472 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6473 isUndefLO, isUndefHI);
6477 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6478 VT == MVT::v16i16) && Subtarget.hasAVX()) {
6480 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6481 X86Opcode = X86ISD::HADD;
6482 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6483 X86Opcode = X86ISD::HSUB;
6484 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6485 X86Opcode = X86ISD::FHADD;
6486 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6487 X86Opcode = X86ISD::FHSUB;
6491 // Don't try to expand this build_vector into a pair of horizontal add/sub
6492 // if we can simply emit a pair of scalar add/sub.
6493 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6496 // Convert this build_vector into two horizontal add/sub followed by
6498 bool isUndefLO = NumUndefsLO == Half;
6499 bool isUndefHI = NumUndefsHI == Half;
6500 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6501 isUndefLO, isUndefHI);
6507 /// If a BUILD_VECTOR's source elements all apply the same bit operation and
6508 /// one of their operands is constant, lower to a pair of BUILD_VECTOR and
6509 /// just apply the bit to the vectors.
6510 /// NOTE: Its not in our interest to start make a general purpose vectorizer
6511 /// from this, but enough scalar bit operations are created from the later
6512 /// legalization + scalarization stages to need basic support.
6513 static SDValue lowerBuildVectorToBitOp(SDValue Op, SelectionDAG &DAG) {
6515 MVT VT = Op.getSimpleValueType();
6516 unsigned NumElems = VT.getVectorNumElements();
6517 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6519 // Check that all elements have the same opcode.
6520 // TODO: Should we allow UNDEFS and if so how many?
6521 unsigned Opcode = Op.getOperand(0).getOpcode();
6522 for (unsigned i = 1; i < NumElems; ++i)
6523 if (Opcode != Op.getOperand(i).getOpcode())
6526 // TODO: We may be able to add support for other Ops (ADD/SUB + shifts).
6533 if (!TLI.isOperationLegalOrPromote(Opcode, VT))
6538 SmallVector<SDValue, 4> LHSElts, RHSElts;
6539 for (SDValue Elt : Op->ops()) {
6540 SDValue LHS = Elt.getOperand(0);
6541 SDValue RHS = Elt.getOperand(1);
6543 // We expect the canonicalized RHS operand to be the constant.
6544 if (!isa<ConstantSDNode>(RHS))
6546 LHSElts.push_back(LHS);
6547 RHSElts.push_back(RHS);
6550 SDValue LHS = DAG.getBuildVector(VT, DL, LHSElts);
6551 SDValue RHS = DAG.getBuildVector(VT, DL, RHSElts);
6552 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
6555 /// Create a vector constant without a load. SSE/AVX provide the bare minimum
6556 /// functionality to do this, so it's all zeros, all ones, or some derivation
6557 /// that is cheap to calculate.
6558 static SDValue materializeVectorConstant(SDValue Op, SelectionDAG &DAG,
6559 const X86Subtarget &Subtarget) {
6561 MVT VT = Op.getSimpleValueType();
6563 // Vectors containing all zeros can be matched by pxor and xorps.
6564 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6565 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6566 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6567 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6570 return getZeroVector(VT, Subtarget, DAG, DL);
6573 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6574 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6575 // vpcmpeqd on 256-bit vectors.
6576 if (Subtarget.hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6577 if (VT == MVT::v4i32 || VT == MVT::v16i32 ||
6578 (VT == MVT::v8i32 && Subtarget.hasInt256()))
6581 return getOnesVector(VT, Subtarget, DAG, DL);
6588 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6591 MVT VT = Op.getSimpleValueType();
6592 MVT ExtVT = VT.getVectorElementType();
6593 unsigned NumElems = Op.getNumOperands();
6595 // Generate vectors for predicate vectors.
6596 if (VT.getVectorElementType() == MVT::i1 && Subtarget.hasAVX512())
6597 return LowerBUILD_VECTORvXi1(Op, DAG);
6599 if (SDValue VectorConstant = materializeVectorConstant(Op, DAG, Subtarget))
6600 return VectorConstant;
6602 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6603 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6605 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6606 return HorizontalOp;
6607 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6609 if (SDValue BitOp = lowerBuildVectorToBitOp(Op, DAG))
6612 unsigned EVTBits = ExtVT.getSizeInBits();
6614 unsigned NumZero = 0;
6615 unsigned NumNonZero = 0;
6616 uint64_t NonZeros = 0;
6617 bool IsAllConstants = true;
6618 SmallSet<SDValue, 8> Values;
6619 for (unsigned i = 0; i < NumElems; ++i) {
6620 SDValue Elt = Op.getOperand(i);
6624 if (Elt.getOpcode() != ISD::Constant &&
6625 Elt.getOpcode() != ISD::ConstantFP)
6626 IsAllConstants = false;
6627 if (X86::isZeroNode(Elt))
6630 assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
6631 NonZeros |= ((uint64_t)1 << i);
6636 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6637 if (NumNonZero == 0)
6638 return DAG.getUNDEF(VT);
6640 // Special case for single non-zero, non-undef, element.
6641 if (NumNonZero == 1) {
6642 unsigned Idx = countTrailingZeros(NonZeros);
6643 SDValue Item = Op.getOperand(Idx);
6645 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6646 // the value are obviously zero, truncate the value to i32 and do the
6647 // insertion that way. Only do this if the value is non-constant or if the
6648 // value is a constant being inserted into element 0. It is cheaper to do
6649 // a constant pool load than it is to do a movd + shuffle.
6650 if (ExtVT == MVT::i64 && !Subtarget.is64Bit() &&
6651 (!IsAllConstants || Idx == 0)) {
6652 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6654 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6655 MVT VecVT = MVT::v4i32;
6657 // Truncate the value (which may itself be a constant) to i32, and
6658 // convert it to a vector with movd (S2V+shuffle to zero extend).
6659 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6660 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6661 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6662 Item, Idx * 2, true, Subtarget, DAG));
6666 // If we have a constant or non-constant insertion into the low element of
6667 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6668 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6669 // depending on what the source datatype is.
6672 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6674 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6675 (ExtVT == MVT::i64 && Subtarget.is64Bit())) {
6676 if (VT.is512BitVector()) {
6677 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6678 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6679 Item, DAG.getIntPtrConstant(0, dl));
6681 assert((VT.is128BitVector() || VT.is256BitVector()) &&
6682 "Expected an SSE value type!");
6683 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6684 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6685 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6688 // We can't directly insert an i8 or i16 into a vector, so zero extend
6690 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6691 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6692 if (VT.getSizeInBits() >= 256) {
6693 MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits()/32);
6694 if (Subtarget.hasAVX()) {
6695 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, Item);
6696 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6698 // Without AVX, we need to extend to a 128-bit vector and then
6699 // insert into the 256-bit vector.
6700 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6701 SDValue ZeroVec = getZeroVector(ShufVT, Subtarget, DAG, dl);
6702 Item = insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6705 assert(VT.is128BitVector() && "Expected an SSE value type!");
6706 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6707 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6709 return DAG.getBitcast(VT, Item);
6713 // Is it a vector logical left shift?
6714 if (NumElems == 2 && Idx == 1 &&
6715 X86::isZeroNode(Op.getOperand(0)) &&
6716 !X86::isZeroNode(Op.getOperand(1))) {
6717 unsigned NumBits = VT.getSizeInBits();
6718 return getVShift(true, VT,
6719 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6720 VT, Op.getOperand(1)),
6721 NumBits/2, DAG, *this, dl);
6724 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6727 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6728 // is a non-constant being inserted into an element other than the low one,
6729 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6730 // movd/movss) to move this into the low element, then shuffle it into
6732 if (EVTBits == 32) {
6733 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6734 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6738 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6739 if (Values.size() == 1) {
6740 if (EVTBits == 32) {
6741 // Instead of a shuffle like this:
6742 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6743 // Check if it's possible to issue this instead.
6744 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6745 unsigned Idx = countTrailingZeros(NonZeros);
6746 SDValue Item = Op.getOperand(Idx);
6747 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6748 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6753 // A vector full of immediates; various special cases are already
6754 // handled, so this is best done with a single constant-pool load.
6758 // See if we can use a vector load to get all of the elements.
6759 if (VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) {
6760 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElems);
6761 if (SDValue LD = EltsFromConsecutiveLoads(VT, Ops, dl, DAG, false))
6765 // For AVX-length vectors, build the individual 128-bit pieces and use
6766 // shuffles to put them in place.
6767 if (VT.is256BitVector() || VT.is512BitVector()) {
6768 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElems);
6770 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6772 // Build both the lower and upper subvector.
6774 DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElems / 2));
6775 SDValue Upper = DAG.getBuildVector(
6776 HVT, dl, makeArrayRef(&Ops[NumElems / 2], NumElems / 2));
6778 // Recreate the wider vector with the lower and upper part.
6779 if (VT.is256BitVector())
6780 return concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6781 return concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6784 // Let legalizer expand 2-wide build_vectors.
6785 if (EVTBits == 64) {
6786 if (NumNonZero == 1) {
6787 // One half is zero or undef.
6788 unsigned Idx = countTrailingZeros(NonZeros);
6789 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6790 Op.getOperand(Idx));
6791 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6796 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6797 if (EVTBits == 8 && NumElems == 16)
6798 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
6799 DAG, Subtarget, *this))
6802 if (EVTBits == 16 && NumElems == 8)
6803 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
6804 DAG, Subtarget, *this))
6807 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6808 if (EVTBits == 32 && NumElems == 4)
6809 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6812 // If element VT is == 32 bits, turn it into a number of shuffles.
6813 if (NumElems == 4 && NumZero > 0) {
6814 SmallVector<SDValue, 8> Ops(NumElems);
6815 for (unsigned i = 0; i < 4; ++i) {
6816 bool isZero = !(NonZeros & (1ULL << i));
6818 Ops[i] = getZeroVector(VT, Subtarget, DAG, dl);
6820 Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6823 for (unsigned i = 0; i < 2; ++i) {
6824 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6827 Ops[i] = Ops[i*2]; // Must be a zero vector.
6830 Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2+1], Ops[i*2]);
6833 Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
6836 Ops[i] = getUnpackl(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
6841 bool Reverse1 = (NonZeros & 0x3) == 2;
6842 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6846 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6847 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6849 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], MaskVec);
6852 if (Values.size() > 1 && VT.is128BitVector()) {
6853 // Check for a build vector from mostly shuffle plus few inserting.
6854 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6857 // For SSE 4.1, use insertps to put the high elements into the low element.
6858 if (Subtarget.hasSSE41()) {
6860 if (!Op.getOperand(0).isUndef())
6861 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6863 Result = DAG.getUNDEF(VT);
6865 for (unsigned i = 1; i < NumElems; ++i) {
6866 if (Op.getOperand(i).isUndef()) continue;
6867 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6868 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6873 // Otherwise, expand into a number of unpckl*, start by extending each of
6874 // our (non-undef) elements to the full vector width with the element in the
6875 // bottom slot of the vector (which generates no code for SSE).
6876 SmallVector<SDValue, 8> Ops(NumElems);
6877 for (unsigned i = 0; i < NumElems; ++i) {
6878 if (!Op.getOperand(i).isUndef())
6879 Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6881 Ops[i] = DAG.getUNDEF(VT);
6884 // Next, we iteratively mix elements, e.g. for v4f32:
6885 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6886 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6887 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6888 unsigned EltStride = NumElems >> 1;
6889 while (EltStride != 0) {
6890 for (unsigned i = 0; i < EltStride; ++i) {
6891 // If Ops[i+EltStride] is undef and this is the first round of mixing,
6892 // then it is safe to just drop this shuffle: V[i] is already in the
6893 // right place, the one element (since it's the first round) being
6894 // inserted as undef can be dropped. This isn't safe for successive
6895 // rounds because they will permute elements within both vectors.
6896 if (Ops[i+EltStride].isUndef() &&
6897 EltStride == NumElems/2)
6900 Ops[i] = getUnpackl(DAG, dl, VT, Ops[i], Ops[i + EltStride]);
6909 // 256-bit AVX can use the vinsertf128 instruction
6910 // to create 256-bit vectors from two other 128-bit ones.
6911 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6913 MVT ResVT = Op.getSimpleValueType();
6915 assert((ResVT.is256BitVector() ||
6916 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6918 SDValue V1 = Op.getOperand(0);
6919 SDValue V2 = Op.getOperand(1);
6920 unsigned NumElems = ResVT.getVectorNumElements();
6921 if (ResVT.is256BitVector())
6922 return concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6924 if (Op.getNumOperands() == 4) {
6925 MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6926 ResVT.getVectorNumElements()/2);
6927 SDValue V3 = Op.getOperand(2);
6928 SDValue V4 = Op.getOperand(3);
6929 return concat256BitVectors(
6930 concat128BitVectors(V1, V2, HalfVT, NumElems / 2, DAG, dl),
6931 concat128BitVectors(V3, V4, HalfVT, NumElems / 2, DAG, dl), ResVT,
6934 return concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6937 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6938 const X86Subtarget &Subtarget,
6939 SelectionDAG & DAG) {
6941 MVT ResVT = Op.getSimpleValueType();
6942 unsigned NumOfOperands = Op.getNumOperands();
6944 assert(isPowerOf2_32(NumOfOperands) &&
6945 "Unexpected number of operands in CONCAT_VECTORS");
6947 SDValue Undef = DAG.getUNDEF(ResVT);
6948 if (NumOfOperands > 2) {
6949 // Specialize the cases when all, or all but one, of the operands are undef.
6950 unsigned NumOfDefinedOps = 0;
6952 for (unsigned i = 0; i < NumOfOperands; i++)
6953 if (!Op.getOperand(i).isUndef()) {
6957 if (NumOfDefinedOps == 0)
6959 if (NumOfDefinedOps == 1) {
6960 unsigned SubVecNumElts =
6961 Op.getOperand(OpIdx).getValueType().getVectorNumElements();
6962 SDValue IdxVal = DAG.getIntPtrConstant(SubVecNumElts * OpIdx, dl);
6963 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef,
6964 Op.getOperand(OpIdx), IdxVal);
6967 MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6968 ResVT.getVectorNumElements()/2);
6969 SmallVector<SDValue, 2> Ops;
6970 for (unsigned i = 0; i < NumOfOperands/2; i++)
6971 Ops.push_back(Op.getOperand(i));
6972 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6974 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6975 Ops.push_back(Op.getOperand(i));
6976 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6977 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6981 SDValue V1 = Op.getOperand(0);
6982 SDValue V2 = Op.getOperand(1);
6983 unsigned NumElems = ResVT.getVectorNumElements();
6984 assert(V1.getValueType() == V2.getValueType() &&
6985 V1.getValueType().getVectorNumElements() == NumElems/2 &&
6986 "Unexpected operands in CONCAT_VECTORS");
6988 if (ResVT.getSizeInBits() >= 16)
6989 return Op; // The operation is legal with KUNPCK
6991 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6992 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6993 SDValue ZeroVec = getZeroVector(ResVT, Subtarget, DAG, dl);
6994 if (IsZeroV1 && IsZeroV2)
6997 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6999 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
7001 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V1, ZeroIdx);
7003 SDValue IdxVal = DAG.getIntPtrConstant(NumElems/2, dl);
7005 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, IdxVal);
7008 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V2, IdxVal);
7010 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
7011 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, V1, V2, IdxVal);
7014 static SDValue LowerCONCAT_VECTORS(SDValue Op,
7015 const X86Subtarget &Subtarget,
7016 SelectionDAG &DAG) {
7017 MVT VT = Op.getSimpleValueType();
7018 if (VT.getVectorElementType() == MVT::i1)
7019 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
7021 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7022 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7023 Op.getNumOperands() == 4)));
7025 // AVX can use the vinsertf128 instruction to create 256-bit vectors
7026 // from two other 128-bit ones.
7028 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7029 return LowerAVXCONCAT_VECTORS(Op, DAG);
7032 //===----------------------------------------------------------------------===//
7033 // Vector shuffle lowering
7035 // This is an experimental code path for lowering vector shuffles on x86. It is
7036 // designed to handle arbitrary vector shuffles and blends, gracefully
7037 // degrading performance as necessary. It works hard to recognize idiomatic
7038 // shuffles and lower them to optimal instruction patterns without leaving
7039 // a framework that allows reasonably efficient handling of all vector shuffle
7041 //===----------------------------------------------------------------------===//
7043 /// \brief Tiny helper function to identify a no-op mask.
7045 /// This is a somewhat boring predicate function. It checks whether the mask
7046 /// array input, which is assumed to be a single-input shuffle mask of the kind
7047 /// used by the X86 shuffle instructions (not a fully general
7048 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7049 /// in-place shuffle are 'no-op's.
7050 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7051 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7052 assert(Mask[i] >= -1 && "Out of bound mask element!");
7053 if (Mask[i] >= 0 && Mask[i] != i)
7059 /// \brief Test whether there are elements crossing 128-bit lanes in this
7062 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
7063 /// and we routinely test for these.
7064 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
7065 int LaneSize = 128 / VT.getScalarSizeInBits();
7066 int Size = Mask.size();
7067 for (int i = 0; i < Size; ++i)
7068 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
7073 /// \brief Test whether a shuffle mask is equivalent within each sub-lane.
7075 /// This checks a shuffle mask to see if it is performing the same
7076 /// lane-relative shuffle in each sub-lane. This trivially implies
7077 /// that it is also not lane-crossing. It may however involve a blend from the
7078 /// same lane of a second vector.
7080 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
7081 /// non-trivial to compute in the face of undef lanes. The representation is
7082 /// suitable for use with existing 128-bit shuffles as entries from the second
7083 /// vector have been remapped to [LaneSize, 2*LaneSize).
7084 static bool isRepeatedShuffleMask(unsigned LaneSizeInBits, MVT VT,
7086 SmallVectorImpl<int> &RepeatedMask) {
7087 int LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
7088 RepeatedMask.assign(LaneSize, -1);
7089 int Size = Mask.size();
7090 for (int i = 0; i < Size; ++i) {
7093 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
7094 // This entry crosses lanes, so there is no way to model this shuffle.
7097 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
7098 // Adjust second vector indices to start at LaneSize instead of Size.
7099 int LocalM = Mask[i] < Size ? Mask[i] % LaneSize
7100 : Mask[i] % LaneSize + LaneSize;
7101 if (RepeatedMask[i % LaneSize] < 0)
7102 // This is the first non-undef entry in this slot of a 128-bit lane.
7103 RepeatedMask[i % LaneSize] = LocalM;
7104 else if (RepeatedMask[i % LaneSize] != LocalM)
7105 // Found a mismatch with the repeated mask.
7111 /// Test whether a shuffle mask is equivalent within each 128-bit lane.
7113 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
7114 SmallVectorImpl<int> &RepeatedMask) {
7115 return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
7118 /// Test whether a shuffle mask is equivalent within each 256-bit lane.
7120 is256BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
7121 SmallVectorImpl<int> &RepeatedMask) {
7122 return isRepeatedShuffleMask(256, VT, Mask, RepeatedMask);
7125 static void scaleShuffleMask(int Scale, ArrayRef<int> Mask,
7126 SmallVectorImpl<int> &ScaledMask) {
7127 assert(0 < Scale && "Unexpected scaling factor");
7128 int NumElts = Mask.size();
7129 ScaledMask.assign(NumElts * Scale, -1);
7131 for (int i = 0; i != NumElts; ++i) {
7134 // Repeat sentinel values in every mask element.
7136 for (int s = 0; s != Scale; ++s)
7137 ScaledMask[(Scale * i) + s] = M;
7141 // Scale mask element and increment across each mask element.
7142 for (int s = 0; s != Scale; ++s)
7143 ScaledMask[(Scale * i) + s] = (Scale * M) + s;
7147 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7150 /// This is a fast way to test a shuffle mask against a fixed pattern:
7152 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
7154 /// It returns true if the mask is exactly as wide as the argument list, and
7155 /// each element of the mask is either -1 (signifying undef) or the value given
7156 /// in the argument.
7157 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
7158 ArrayRef<int> ExpectedMask) {
7159 if (Mask.size() != ExpectedMask.size())
7162 int Size = Mask.size();
7164 // If the values are build vectors, we can look through them to find
7165 // equivalent inputs that make the shuffles equivalent.
7166 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
7167 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
7169 for (int i = 0; i < Size; ++i) {
7170 assert(Mask[i] >= -1 && "Out of bound mask element!");
7171 if (Mask[i] >= 0 && Mask[i] != ExpectedMask[i]) {
7172 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
7173 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
7174 if (!MaskBV || !ExpectedBV ||
7175 MaskBV->getOperand(Mask[i] % Size) !=
7176 ExpectedBV->getOperand(ExpectedMask[i] % Size))
7184 /// Checks whether a target shuffle mask is equivalent to an explicit pattern.
7186 /// The masks must be exactly the same width.
7188 /// If an element in Mask matches SM_SentinelUndef (-1) then the corresponding
7189 /// value in ExpectedMask is always accepted. Otherwise the indices must match.
7191 /// SM_SentinelZero is accepted as a valid negative index but must match in both.
7192 static bool isTargetShuffleEquivalent(ArrayRef<int> Mask,
7193 ArrayRef<int> ExpectedMask) {
7194 int Size = Mask.size();
7195 if (Size != (int)ExpectedMask.size())
7198 for (int i = 0; i < Size; ++i)
7199 if (Mask[i] == SM_SentinelUndef)
7201 else if (Mask[i] < 0 && Mask[i] != SM_SentinelZero)
7203 else if (Mask[i] != ExpectedMask[i])
7209 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7211 /// This helper function produces an 8-bit shuffle immediate corresponding to
7212 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7213 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7216 /// NB: We rely heavily on "undef" masks preserving the input lane.
7217 static unsigned getV4X86ShuffleImm(ArrayRef<int> Mask) {
7218 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7219 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7220 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7221 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7222 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7225 Imm |= (Mask[0] < 0 ? 0 : Mask[0]) << 0;
7226 Imm |= (Mask[1] < 0 ? 1 : Mask[1]) << 2;
7227 Imm |= (Mask[2] < 0 ? 2 : Mask[2]) << 4;
7228 Imm |= (Mask[3] < 0 ? 3 : Mask[3]) << 6;
7232 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
7233 SelectionDAG &DAG) {
7234 return DAG.getConstant(getV4X86ShuffleImm(Mask), DL, MVT::i8);
7237 /// \brief Compute whether each element of a shuffle is zeroable.
7239 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
7240 /// Either it is an undef element in the shuffle mask, the element of the input
7241 /// referenced is undef, or the element of the input referenced is known to be
7242 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
7243 /// as many lanes with this technique as possible to simplify the remaining
7245 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
7246 SDValue V1, SDValue V2) {
7247 SmallBitVector Zeroable(Mask.size(), false);
7248 V1 = peekThroughBitcasts(V1);
7249 V2 = peekThroughBitcasts(V2);
7251 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7252 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7254 int VectorSizeInBits = V1.getValueType().getSizeInBits();
7255 int ScalarSizeInBits = VectorSizeInBits / Mask.size();
7256 assert(!(VectorSizeInBits % ScalarSizeInBits) && "Illegal shuffle mask size");
7258 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7260 // Handle the easy cases.
7261 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
7266 // Determine shuffle input and normalize the mask.
7267 SDValue V = M < Size ? V1 : V2;
7270 // Currently we can only search BUILD_VECTOR for UNDEF/ZERO elements.
7271 if (V.getOpcode() != ISD::BUILD_VECTOR)
7274 // If the BUILD_VECTOR has fewer elements then the bitcasted portion of
7275 // the (larger) source element must be UNDEF/ZERO.
7276 if ((Size % V.getNumOperands()) == 0) {
7277 int Scale = Size / V->getNumOperands();
7278 SDValue Op = V.getOperand(M / Scale);
7279 if (Op.isUndef() || X86::isZeroNode(Op))
7281 else if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
7282 APInt Val = Cst->getAPIntValue();
7283 Val = Val.lshr((M % Scale) * ScalarSizeInBits);
7284 Val = Val.getLoBits(ScalarSizeInBits);
7285 Zeroable[i] = (Val == 0);
7286 } else if (ConstantFPSDNode *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
7287 APInt Val = Cst->getValueAPF().bitcastToAPInt();
7288 Val = Val.lshr((M % Scale) * ScalarSizeInBits);
7289 Val = Val.getLoBits(ScalarSizeInBits);
7290 Zeroable[i] = (Val == 0);
7295 // If the BUILD_VECTOR has more elements then all the (smaller) source
7296 // elements must be UNDEF or ZERO.
7297 if ((V.getNumOperands() % Size) == 0) {
7298 int Scale = V->getNumOperands() / Size;
7299 bool AllZeroable = true;
7300 for (int j = 0; j < Scale; ++j) {
7301 SDValue Op = V.getOperand((M * Scale) + j);
7302 AllZeroable &= (Op.isUndef() || X86::isZeroNode(Op));
7304 Zeroable[i] = AllZeroable;
7312 /// Try to lower a shuffle with a single PSHUFB of V1.
7313 /// This is only possible if V2 is unused (at all, or only for zero elements).
7314 static SDValue lowerVectorShuffleWithPSHUFB(const SDLoc &DL, MVT VT,
7315 ArrayRef<int> Mask, SDValue V1,
7317 const X86Subtarget &Subtarget,
7318 SelectionDAG &DAG) {
7319 int Size = Mask.size();
7320 int LaneSize = 128 / VT.getScalarSizeInBits();
7321 const int NumBytes = VT.getSizeInBits() / 8;
7322 const int NumEltBytes = VT.getScalarSizeInBits() / 8;
7324 assert((Subtarget.hasSSSE3() && VT.is128BitVector()) ||
7325 (Subtarget.hasAVX2() && VT.is256BitVector()) ||
7326 (Subtarget.hasBWI() && VT.is512BitVector()));
7328 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7330 SmallVector<SDValue, 64> PSHUFBMask(NumBytes);
7331 // Sign bit set in i8 mask means zero element.
7332 SDValue ZeroMask = DAG.getConstant(0x80, DL, MVT::i8);
7334 for (int i = 0; i < NumBytes; ++i) {
7335 int M = Mask[i / NumEltBytes];
7337 PSHUFBMask[i] = DAG.getUNDEF(MVT::i8);
7340 if (Zeroable[i / NumEltBytes]) {
7341 PSHUFBMask[i] = ZeroMask;
7348 // PSHUFB can't cross lanes, ensure this doesn't happen.
7349 if ((M / LaneSize) != ((i / NumEltBytes) / LaneSize))
7353 M = M * NumEltBytes + (i % NumEltBytes);
7354 PSHUFBMask[i] = DAG.getConstant(M, DL, MVT::i8);
7357 MVT I8VT = MVT::getVectorVT(MVT::i8, NumBytes);
7358 return DAG.getBitcast(
7359 VT, DAG.getNode(X86ISD::PSHUFB, DL, I8VT, DAG.getBitcast(I8VT, V1),
7360 DAG.getBuildVector(I8VT, DL, PSHUFBMask)));
7363 // X86 has dedicated unpack instructions that can handle specific blend
7364 // operations: UNPCKH and UNPCKL.
7365 static SDValue lowerVectorShuffleWithUNPCK(const SDLoc &DL, MVT VT,
7366 ArrayRef<int> Mask, SDValue V1,
7367 SDValue V2, SelectionDAG &DAG) {
7368 int NumElts = VT.getVectorNumElements();
7369 int NumEltsInLane = 128 / VT.getScalarSizeInBits();
7370 SmallVector<int, 8> Unpckl(NumElts);
7371 SmallVector<int, 8> Unpckh(NumElts);
7373 for (int i = 0; i < NumElts; ++i) {
7374 unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
7375 int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
7376 int HiPos = LoPos + NumEltsInLane / 2;
7381 if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
7382 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
7383 if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
7384 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
7386 // Commute and try again.
7387 ShuffleVectorSDNode::commuteMask(Unpckl);
7388 if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
7389 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
7391 ShuffleVectorSDNode::commuteMask(Unpckh);
7392 if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
7393 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
7398 /// \brief Try to emit a bitmask instruction for a shuffle.
7400 /// This handles cases where we can model a blend exactly as a bitmask due to
7401 /// one of the inputs being zeroable.
7402 static SDValue lowerVectorShuffleAsBitMask(const SDLoc &DL, MVT VT, SDValue V1,
7403 SDValue V2, ArrayRef<int> Mask,
7404 SelectionDAG &DAG) {
7405 MVT EltVT = VT.getVectorElementType();
7406 int NumEltBits = EltVT.getSizeInBits();
7407 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
7408 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
7409 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7411 if (EltVT.isFloatingPoint()) {
7412 Zero = DAG.getBitcast(EltVT, Zero);
7413 AllOnes = DAG.getBitcast(EltVT, AllOnes);
7415 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
7416 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7418 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7421 if (Mask[i] % Size != i)
7422 return SDValue(); // Not a blend.
7424 V = Mask[i] < Size ? V1 : V2;
7425 else if (V != (Mask[i] < Size ? V1 : V2))
7426 return SDValue(); // Can only let one input through the mask.
7428 VMaskOps[i] = AllOnes;
7431 return SDValue(); // No non-zeroable elements!
7433 SDValue VMask = DAG.getBuildVector(VT, DL, VMaskOps);
7434 V = DAG.getNode(VT.isFloatingPoint()
7435 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
7440 /// \brief Try to emit a blend instruction for a shuffle using bit math.
7442 /// This is used as a fallback approach when first class blend instructions are
7443 /// unavailable. Currently it is only suitable for integer vectors, but could
7444 /// be generalized for floating point vectors if desirable.
7445 static SDValue lowerVectorShuffleAsBitBlend(const SDLoc &DL, MVT VT, SDValue V1,
7446 SDValue V2, ArrayRef<int> Mask,
7447 SelectionDAG &DAG) {
7448 assert(VT.isInteger() && "Only supports integer vector types!");
7449 MVT EltVT = VT.getVectorElementType();
7450 int NumEltBits = EltVT.getSizeInBits();
7451 SDValue Zero = DAG.getConstant(0, DL, EltVT);
7452 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7454 SmallVector<SDValue, 16> MaskOps;
7455 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7456 if (Mask[i] >= 0 && Mask[i] != i && Mask[i] != i + Size)
7457 return SDValue(); // Shuffled input!
7458 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
7461 SDValue V1Mask = DAG.getBuildVector(VT, DL, MaskOps);
7462 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
7463 // We have to cast V2 around.
7464 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
7465 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
7466 DAG.getBitcast(MaskVT, V1Mask),
7467 DAG.getBitcast(MaskVT, V2)));
7468 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
7471 /// \brief Try to emit a blend instruction for a shuffle.
7473 /// This doesn't do any checks for the availability of instructions for blending
7474 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7475 /// be matched in the backend with the type given. What it does check for is
7476 /// that the shuffle mask is a blend, or convertible into a blend with zero.
7477 static SDValue lowerVectorShuffleAsBlend(const SDLoc &DL, MVT VT, SDValue V1,
7478 SDValue V2, ArrayRef<int> Original,
7479 const X86Subtarget &Subtarget,
7480 SelectionDAG &DAG) {
7481 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7482 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7483 SmallVector<int, 8> Mask(Original.begin(), Original.end());
7484 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7485 bool ForceV1Zero = false, ForceV2Zero = false;
7487 // Attempt to generate the binary blend mask. If an input is zero then
7488 // we can use any lane.
7489 // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
7490 unsigned BlendMask = 0;
7491 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7497 if (M == i + Size) {
7498 BlendMask |= 1u << i;
7509 BlendMask |= 1u << i;
7514 return SDValue(); // Shuffled input!
7517 // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
7519 V1 = getZeroVector(VT, Subtarget, DAG, DL);
7521 V2 = getZeroVector(VT, Subtarget, DAG, DL);
7523 auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
7524 unsigned ScaledMask = 0;
7525 for (int i = 0; i != Size; ++i)
7526 if (BlendMask & (1u << i))
7527 for (int j = 0; j != Scale; ++j)
7528 ScaledMask |= 1u << (i * Scale + j);
7532 switch (VT.SimpleTy) {
7537 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7538 DAG.getConstant(BlendMask, DL, MVT::i8));
7542 assert(Subtarget.hasAVX2() && "256-bit integer blends require AVX2!");
7546 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7547 // that instruction.
7548 if (Subtarget.hasAVX2()) {
7549 // Scale the blend by the number of 32-bit dwords per element.
7550 int Scale = VT.getScalarSizeInBits() / 32;
7551 BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7552 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7553 V1 = DAG.getBitcast(BlendVT, V1);
7554 V2 = DAG.getBitcast(BlendVT, V2);
7555 return DAG.getBitcast(
7556 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7557 DAG.getConstant(BlendMask, DL, MVT::i8)));
7561 // For integer shuffles we need to expand the mask and cast the inputs to
7562 // v8i16s prior to blending.
7563 int Scale = 8 / VT.getVectorNumElements();
7564 BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7565 V1 = DAG.getBitcast(MVT::v8i16, V1);
7566 V2 = DAG.getBitcast(MVT::v8i16, V2);
7567 return DAG.getBitcast(VT,
7568 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7569 DAG.getConstant(BlendMask, DL, MVT::i8)));
7573 assert(Subtarget.hasAVX2() && "256-bit integer blends require AVX2!");
7574 SmallVector<int, 8> RepeatedMask;
7575 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7576 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7577 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7579 for (int i = 0; i < 8; ++i)
7580 if (RepeatedMask[i] >= 8)
7581 BlendMask |= 1u << i;
7582 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7583 DAG.getConstant(BlendMask, DL, MVT::i8));
7589 assert((VT.is128BitVector() || Subtarget.hasAVX2()) &&
7590 "256-bit byte-blends require AVX2 support!");
7592 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
7593 if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
7596 // Scale the blend by the number of bytes per element.
7597 int Scale = VT.getScalarSizeInBits() / 8;
7599 // This form of blend is always done on bytes. Compute the byte vector
7601 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
7603 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7604 // mix of LLVM's code generator and the x86 backend. We tell the code
7605 // generator that boolean values in the elements of an x86 vector register
7606 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7607 // mapping a select to operand #1, and 'false' mapping to operand #2. The
7608 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7609 // of the element (the remaining are ignored) and 0 in that high bit would
7610 // mean operand #1 while 1 in the high bit would mean operand #2. So while
7611 // the LLVM model for boolean values in vector elements gets the relevant
7612 // bit set, it is set backwards and over constrained relative to x86's
7614 SmallVector<SDValue, 32> VSELECTMask;
7615 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7616 for (int j = 0; j < Scale; ++j)
7617 VSELECTMask.push_back(
7618 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7619 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7622 V1 = DAG.getBitcast(BlendVT, V1);
7623 V2 = DAG.getBitcast(BlendVT, V2);
7624 return DAG.getBitcast(
7625 VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7626 DAG.getBuildVector(BlendVT, DL, VSELECTMask), V1, V2));
7630 llvm_unreachable("Not a supported integer vector type!");
7634 /// \brief Try to lower as a blend of elements from two inputs followed by
7635 /// a single-input permutation.
7637 /// This matches the pattern where we can blend elements from two inputs and
7638 /// then reduce the shuffle to a single-input permutation.
7639 static SDValue lowerVectorShuffleAsBlendAndPermute(const SDLoc &DL, MVT VT,
7640 SDValue V1, SDValue V2,
7642 SelectionDAG &DAG) {
7643 // We build up the blend mask while checking whether a blend is a viable way
7644 // to reduce the shuffle.
7645 SmallVector<int, 32> BlendMask(Mask.size(), -1);
7646 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7648 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7652 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7654 if (BlendMask[Mask[i] % Size] < 0)
7655 BlendMask[Mask[i] % Size] = Mask[i];
7656 else if (BlendMask[Mask[i] % Size] != Mask[i])
7657 return SDValue(); // Can't blend in the needed input!
7659 PermuteMask[i] = Mask[i] % Size;
7662 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7663 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7666 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7667 /// blends and permutes.
7669 /// This matches the extremely common pattern for handling combined
7670 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7671 /// operations. It will try to pick the best arrangement of shuffles and
7673 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(const SDLoc &DL,
7677 SelectionDAG &DAG) {
7678 // Shuffle the input elements into the desired positions in V1 and V2 and
7679 // blend them together.
7680 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7681 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7682 SmallVector<int, 32> BlendMask(Mask.size(), -1);
7683 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7684 if (Mask[i] >= 0 && Mask[i] < Size) {
7685 V1Mask[i] = Mask[i];
7687 } else if (Mask[i] >= Size) {
7688 V2Mask[i] = Mask[i] - Size;
7689 BlendMask[i] = i + Size;
7692 // Try to lower with the simpler initial blend strategy unless one of the
7693 // input shuffles would be a no-op. We prefer to shuffle inputs as the
7694 // shuffle may be able to fold with a load or other benefit. However, when
7695 // we'll have to do 2x as many shuffles in order to achieve this, blending
7696 // first is a better strategy.
7697 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7698 if (SDValue BlendPerm =
7699 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7702 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7703 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7704 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7707 /// \brief Try to lower a vector shuffle as a byte rotation.
7709 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7710 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7711 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7712 /// try to generically lower a vector shuffle through such an pattern. It
7713 /// does not check for the profitability of lowering either as PALIGNR or
7714 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7715 /// This matches shuffle vectors that look like:
7717 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7719 /// Essentially it concatenates V1 and V2, shifts right by some number of
7720 /// elements, and takes the low elements as the result. Note that while this is
7721 /// specified as a *right shift* because x86 is little-endian, it is a *left
7722 /// rotate* of the vector lanes.
7723 static SDValue lowerVectorShuffleAsByteRotate(const SDLoc &DL, MVT VT,
7724 SDValue V1, SDValue V2,
7726 const X86Subtarget &Subtarget,
7727 SelectionDAG &DAG) {
7728 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7730 int NumElts = Mask.size();
7731 int NumLanes = VT.getSizeInBits() / 128;
7732 int NumLaneElts = NumElts / NumLanes;
7734 // We need to detect various ways of spelling a rotation:
7735 // [11, 12, 13, 14, 15, 0, 1, 2]
7736 // [-1, 12, 13, 14, -1, -1, 1, -1]
7737 // [-1, -1, -1, -1, -1, -1, 1, 2]
7738 // [ 3, 4, 5, 6, 7, 8, 9, 10]
7739 // [-1, 4, 5, 6, -1, -1, 9, -1]
7740 // [-1, 4, 5, 6, -1, -1, -1, -1]
7743 for (int l = 0; l < NumElts; l += NumLaneElts) {
7744 for (int i = 0; i < NumLaneElts; ++i) {
7745 if (Mask[l + i] < 0)
7748 // Get the mod-Size index and lane correct it.
7749 int LaneIdx = (Mask[l + i] % NumElts) - l;
7750 // Make sure it was in this lane.
7751 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7754 // Determine where a rotated vector would have started.
7755 int StartIdx = i - LaneIdx;
7757 // The identity rotation isn't interesting, stop.
7760 // If we found the tail of a vector the rotation must be the missing
7761 // front. If we found the head of a vector, it must be how much of the
7763 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7766 Rotation = CandidateRotation;
7767 else if (Rotation != CandidateRotation)
7768 // The rotations don't match, so we can't match this mask.
7771 // Compute which value this mask is pointing at.
7772 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7774 // Compute which of the two target values this index should be assigned
7775 // to. This reflects whether the high elements are remaining or the low
7776 // elements are remaining.
7777 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7779 // Either set up this value if we've not encountered it before, or check
7780 // that it remains consistent.
7783 else if (TargetV != MaskV)
7784 // This may be a rotation, but it pulls from the inputs in some
7785 // unsupported interleaving.
7790 // Check that we successfully analyzed the mask, and normalize the results.
7791 assert(Rotation != 0 && "Failed to locate a viable rotation!");
7792 assert((Lo || Hi) && "Failed to find a rotated input vector!");
7798 // Cast the inputs to i8 vector of correct length to match PALIGNR or
7800 MVT ByteVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7801 Lo = DAG.getBitcast(ByteVT, Lo);
7802 Hi = DAG.getBitcast(ByteVT, Hi);
7804 // The actual rotate instruction rotates bytes, so we need to scale the
7805 // rotation based on how many bytes are in the vector lane.
7806 int Scale = 16 / NumLaneElts;
7808 // SSSE3 targets can use the palignr instruction.
7809 if (Subtarget.hasSSSE3()) {
7810 assert((!VT.is512BitVector() || Subtarget.hasBWI()) &&
7811 "512-bit PALIGNR requires BWI instructions");
7812 return DAG.getBitcast(
7813 VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, Lo, Hi,
7814 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7817 assert(VT.is128BitVector() &&
7818 "Rotate-based lowering only supports 128-bit lowering!");
7819 assert(Mask.size() <= 16 &&
7820 "Can shuffle at most 16 bytes in a 128-bit vector!");
7821 assert(ByteVT == MVT::v16i8 &&
7822 "SSE2 rotate lowering only needed for v16i8!");
7824 // Default SSE2 implementation
7825 int LoByteShift = 16 - Rotation * Scale;
7826 int HiByteShift = Rotation * Scale;
7828 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Lo,
7829 DAG.getConstant(LoByteShift, DL, MVT::i8));
7830 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Hi,
7831 DAG.getConstant(HiByteShift, DL, MVT::i8));
7832 return DAG.getBitcast(VT,
7833 DAG.getNode(ISD::OR, DL, MVT::v16i8, LoShift, HiShift));
7836 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7838 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7839 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7840 /// matches elements from one of the input vectors shuffled to the left or
7841 /// right with zeroable elements 'shifted in'. It handles both the strictly
7842 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7845 /// PSHL : (little-endian) left bit shift.
7846 /// [ zz, 0, zz, 2 ]
7847 /// [ -1, 4, zz, -1 ]
7848 /// PSRL : (little-endian) right bit shift.
7850 /// [ -1, -1, 7, zz]
7851 /// PSLLDQ : (little-endian) left byte shift
7852 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
7853 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
7854 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
7855 /// PSRLDQ : (little-endian) right byte shift
7856 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
7857 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
7858 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
7859 static SDValue lowerVectorShuffleAsShift(const SDLoc &DL, MVT VT, SDValue V1,
7860 SDValue V2, ArrayRef<int> Mask,
7861 const X86Subtarget &Subtarget,
7862 SelectionDAG &DAG) {
7863 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7865 int Size = Mask.size();
7866 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7868 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7869 for (int i = 0; i < Size; i += Scale)
7870 for (int j = 0; j < Shift; ++j)
7871 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7877 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7878 for (int i = 0; i != Size; i += Scale) {
7879 unsigned Pos = Left ? i + Shift : i;
7880 unsigned Low = Left ? i : i + Shift;
7881 unsigned Len = Scale - Shift;
7882 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7883 Low + (V == V1 ? 0 : Size)))
7887 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7888 bool ByteShift = ShiftEltBits > 64;
7889 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7890 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7891 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7893 // Normalize the scale for byte shifts to still produce an i64 element
7895 Scale = ByteShift ? Scale / 2 : Scale;
7897 // We need to round trip through the appropriate type for the shift.
7898 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7899 MVT ShiftVT = ByteShift ? MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8)
7900 : MVT::getVectorVT(ShiftSVT, Size / Scale);
7901 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7902 "Illegal integer vector type");
7903 V = DAG.getBitcast(ShiftVT, V);
7905 V = DAG.getNode(OpCode, DL, ShiftVT, V,
7906 DAG.getConstant(ShiftAmt, DL, MVT::i8));
7907 return DAG.getBitcast(VT, V);
7910 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7911 // keep doubling the size of the integer elements up to that. We can
7912 // then shift the elements of the integer vector by whole multiples of
7913 // their width within the elements of the larger integer vector. Test each
7914 // multiple to see if we can find a match with the moved element indices
7915 // and that the shifted in elements are all zeroable.
7916 unsigned MaxWidth = (VT.is512BitVector() && !Subtarget.hasBWI() ? 64 : 128);
7917 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= MaxWidth; Scale *= 2)
7918 for (int Shift = 1; Shift != Scale; ++Shift)
7919 for (bool Left : {true, false})
7920 if (CheckZeros(Shift, Scale, Left))
7921 for (SDValue V : {V1, V2})
7922 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7929 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7930 static SDValue lowerVectorShuffleWithSSE4A(const SDLoc &DL, MVT VT, SDValue V1,
7931 SDValue V2, ArrayRef<int> Mask,
7932 SelectionDAG &DAG) {
7933 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7934 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7936 int Size = Mask.size();
7937 int HalfSize = Size / 2;
7938 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7940 // Upper half must be undefined.
7941 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7944 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7945 // Remainder of lower half result is zero and upper half is all undef.
7946 auto LowerAsEXTRQ = [&]() {
7947 // Determine the extraction length from the part of the
7948 // lower half that isn't zeroable.
7950 for (; Len > 0; --Len)
7951 if (!Zeroable[Len - 1])
7953 assert(Len > 0 && "Zeroable shuffle mask");
7955 // Attempt to match first Len sequential elements from the lower half.
7958 for (int i = 0; i != Len; ++i) {
7962 SDValue &V = (M < Size ? V1 : V2);
7965 // The extracted elements must start at a valid index and all mask
7966 // elements must be in the lower half.
7967 if (i > M || M >= HalfSize)
7970 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7981 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7982 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7983 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7984 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7985 DAG.getConstant(BitLen, DL, MVT::i8),
7986 DAG.getConstant(BitIdx, DL, MVT::i8));
7989 if (SDValue ExtrQ = LowerAsEXTRQ())
7992 // INSERTQ: Extract lowest Len elements from lower half of second source and
7993 // insert over first source, starting at Idx.
7994 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7995 auto LowerAsInsertQ = [&]() {
7996 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7999 // Attempt to match first source from mask before insertion point.
8000 if (isUndefInRange(Mask, 0, Idx)) {
8002 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
8004 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
8010 // Extend the extraction length looking to match both the insertion of
8011 // the second source and the remaining elements of the first.
8012 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
8017 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
8019 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
8025 // Match the remaining elements of the lower half.
8026 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
8028 } else if ((!Base || (Base == V1)) &&
8029 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
8031 } else if ((!Base || (Base == V2)) &&
8032 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
8039 // We may not have a base (first source) - this can safely be undefined.
8041 Base = DAG.getUNDEF(VT);
8043 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
8044 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
8045 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
8046 DAG.getConstant(BitLen, DL, MVT::i8),
8047 DAG.getConstant(BitIdx, DL, MVT::i8));
8054 if (SDValue InsertQ = LowerAsInsertQ())
8060 /// \brief Lower a vector shuffle as a zero or any extension.
8062 /// Given a specific number of elements, element bit width, and extension
8063 /// stride, produce either a zero or any extension based on the available
8064 /// features of the subtarget. The extended elements are consecutive and
8065 /// begin and can start from an offseted element index in the input; to
8066 /// avoid excess shuffling the offset must either being in the bottom lane
8067 /// or at the start of a higher lane. All extended elements must be from
8069 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
8070 const SDLoc &DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
8071 ArrayRef<int> Mask, const X86Subtarget &Subtarget, SelectionDAG &DAG) {
8072 assert(Scale > 1 && "Need a scale to extend.");
8073 int EltBits = VT.getScalarSizeInBits();
8074 int NumElements = VT.getVectorNumElements();
8075 int NumEltsPerLane = 128 / EltBits;
8076 int OffsetLane = Offset / NumEltsPerLane;
8077 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
8078 "Only 8, 16, and 32 bit elements can be extended.");
8079 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
8080 assert(0 <= Offset && "Extension offset must be positive.");
8081 assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
8082 "Extension offset must be in the first lane or start an upper lane.");
8084 // Check that an index is in same lane as the base offset.
8085 auto SafeOffset = [&](int Idx) {
8086 return OffsetLane == (Idx / NumEltsPerLane);
8089 // Shift along an input so that the offset base moves to the first element.
8090 auto ShuffleOffset = [&](SDValue V) {
8094 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
8095 for (int i = 0; i * Scale < NumElements; ++i) {
8096 int SrcIdx = i + Offset;
8097 ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
8099 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
8102 // Found a valid zext mask! Try various lowering strategies based on the
8103 // input type and available ISA extensions.
8104 if (Subtarget.hasSSE41()) {
8105 // Not worth offseting 128-bit vectors if scale == 2, a pattern using
8106 // PUNPCK will catch this in a later shuffle match.
8107 if (Offset && Scale == 2 && VT.is128BitVector())
8109 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
8110 NumElements / Scale);
8111 InputV = ShuffleOffset(InputV);
8113 // For 256-bit vectors, we only need the lower (128-bit) input half.
8114 if (VT.is256BitVector())
8115 InputV = extract128BitVector(InputV, 0, DAG, DL);
8117 InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV);
8118 return DAG.getBitcast(VT, InputV);
8121 assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
8123 // For any extends we can cheat for larger element sizes and use shuffle
8124 // instructions that can fold with a load and/or copy.
8125 if (AnyExt && EltBits == 32) {
8126 int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
8128 return DAG.getBitcast(
8129 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8130 DAG.getBitcast(MVT::v4i32, InputV),
8131 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8133 if (AnyExt && EltBits == 16 && Scale > 2) {
8134 int PSHUFDMask[4] = {Offset / 2, -1,
8135 SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
8136 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8137 DAG.getBitcast(MVT::v4i32, InputV),
8138 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
8139 int PSHUFWMask[4] = {1, -1, -1, -1};
8140 unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
8141 return DAG.getBitcast(
8142 VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
8143 DAG.getBitcast(MVT::v8i16, InputV),
8144 getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
8147 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
8149 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget.hasSSE4A()) {
8150 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
8151 assert(VT.is128BitVector() && "Unexpected vector width!");
8153 int LoIdx = Offset * EltBits;
8154 SDValue Lo = DAG.getBitcast(
8155 MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
8156 DAG.getConstant(EltBits, DL, MVT::i8),
8157 DAG.getConstant(LoIdx, DL, MVT::i8)));
8159 if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
8160 !SafeOffset(Offset + 1))
8161 return DAG.getBitcast(VT, Lo);
8163 int HiIdx = (Offset + 1) * EltBits;
8164 SDValue Hi = DAG.getBitcast(
8165 MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
8166 DAG.getConstant(EltBits, DL, MVT::i8),
8167 DAG.getConstant(HiIdx, DL, MVT::i8)));
8168 return DAG.getBitcast(VT,
8169 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
8172 // If this would require more than 2 unpack instructions to expand, use
8173 // pshufb when available. We can only use more than 2 unpack instructions
8174 // when zero extending i8 elements which also makes it easier to use pshufb.
8175 if (Scale > 4 && EltBits == 8 && Subtarget.hasSSSE3()) {
8176 assert(NumElements == 16 && "Unexpected byte vector width!");
8177 SDValue PSHUFBMask[16];
8178 for (int i = 0; i < 16; ++i) {
8179 int Idx = Offset + (i / Scale);
8180 PSHUFBMask[i] = DAG.getConstant(
8181 (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
8183 InputV = DAG.getBitcast(MVT::v16i8, InputV);
8184 return DAG.getBitcast(
8185 VT, DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
8186 DAG.getBuildVector(MVT::v16i8, DL, PSHUFBMask)));
8189 // If we are extending from an offset, ensure we start on a boundary that
8190 // we can unpack from.
8191 int AlignToUnpack = Offset % (NumElements / Scale);
8192 if (AlignToUnpack) {
8193 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
8194 for (int i = AlignToUnpack; i < NumElements; ++i)
8195 ShMask[i - AlignToUnpack] = i;
8196 InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
8197 Offset -= AlignToUnpack;
8200 // Otherwise emit a sequence of unpacks.
8202 unsigned UnpackLoHi = X86ISD::UNPCKL;
8203 if (Offset >= (NumElements / 2)) {
8204 UnpackLoHi = X86ISD::UNPCKH;
8205 Offset -= (NumElements / 2);
8208 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
8209 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
8210 : getZeroVector(InputVT, Subtarget, DAG, DL);
8211 InputV = DAG.getBitcast(InputVT, InputV);
8212 InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
8216 } while (Scale > 1);
8217 return DAG.getBitcast(VT, InputV);
8220 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
8222 /// This routine will try to do everything in its power to cleverly lower
8223 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
8224 /// check for the profitability of this lowering, it tries to aggressively
8225 /// match this pattern. It will use all of the micro-architectural details it
8226 /// can to emit an efficient lowering. It handles both blends with all-zero
8227 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
8228 /// masking out later).
8230 /// The reason we have dedicated lowering for zext-style shuffles is that they
8231 /// are both incredibly common and often quite performance sensitive.
8232 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
8233 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
8234 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
8235 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8237 int Bits = VT.getSizeInBits();
8238 int NumLanes = Bits / 128;
8239 int NumElements = VT.getVectorNumElements();
8240 int NumEltsPerLane = NumElements / NumLanes;
8241 assert(VT.getScalarSizeInBits() <= 32 &&
8242 "Exceeds 32-bit integer zero extension limit");
8243 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
8245 // Define a helper function to check a particular ext-scale and lower to it if
8247 auto Lower = [&](int Scale) -> SDValue {
8252 for (int i = 0; i < NumElements; ++i) {
8255 continue; // Valid anywhere but doesn't tell us anything.
8256 if (i % Scale != 0) {
8257 // Each of the extended elements need to be zeroable.
8261 // We no longer are in the anyext case.
8266 // Each of the base elements needs to be consecutive indices into the
8267 // same input vector.
8268 SDValue V = M < NumElements ? V1 : V2;
8269 M = M % NumElements;
8272 Offset = M - (i / Scale);
8273 } else if (InputV != V)
8274 return SDValue(); // Flip-flopping inputs.
8276 // Offset must start in the lowest 128-bit lane or at the start of an
8278 // FIXME: Is it ever worth allowing a negative base offset?
8279 if (!((0 <= Offset && Offset < NumEltsPerLane) ||
8280 (Offset % NumEltsPerLane) == 0))
8283 // If we are offsetting, all referenced entries must come from the same
8285 if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
8288 if ((M % NumElements) != (Offset + (i / Scale)))
8289 return SDValue(); // Non-consecutive strided elements.
8293 // If we fail to find an input, we have a zero-shuffle which should always
8294 // have already been handled.
8295 // FIXME: Maybe handle this here in case during blending we end up with one?
8299 // If we are offsetting, don't extend if we only match a single input, we
8300 // can always do better by using a basic PSHUF or PUNPCK.
8301 if (Offset != 0 && Matches < 2)
8304 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
8305 DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
8308 // The widest scale possible for extending is to a 64-bit integer.
8309 assert(Bits % 64 == 0 &&
8310 "The number of bits in a vector must be divisible by 64 on x86!");
8311 int NumExtElements = Bits / 64;
8313 // Each iteration, try extending the elements half as much, but into twice as
8315 for (; NumExtElements < NumElements; NumExtElements *= 2) {
8316 assert(NumElements % NumExtElements == 0 &&
8317 "The input vector size must be divisible by the extended size.");
8318 if (SDValue V = Lower(NumElements / NumExtElements))
8322 // General extends failed, but 128-bit vectors may be able to use MOVQ.
8326 // Returns one of the source operands if the shuffle can be reduced to a
8327 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
8328 auto CanZExtLowHalf = [&]() {
8329 for (int i = NumElements / 2; i != NumElements; ++i)
8332 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
8334 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
8339 if (SDValue V = CanZExtLowHalf()) {
8340 V = DAG.getBitcast(MVT::v2i64, V);
8341 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
8342 return DAG.getBitcast(VT, V);
8345 // No viable ext lowering found.
8349 /// \brief Try to get a scalar value for a specific element of a vector.
8351 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
8352 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
8353 SelectionDAG &DAG) {
8354 MVT VT = V.getSimpleValueType();
8355 MVT EltVT = VT.getVectorElementType();
8356 V = peekThroughBitcasts(V);
8358 // If the bitcasts shift the element size, we can't extract an equivalent
8360 MVT NewVT = V.getSimpleValueType();
8361 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
8364 if (V.getOpcode() == ISD::BUILD_VECTOR ||
8365 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
8366 // Ensure the scalar operand is the same size as the destination.
8367 // FIXME: Add support for scalar truncation where possible.
8368 SDValue S = V.getOperand(Idx);
8369 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
8370 return DAG.getBitcast(EltVT, S);
8376 /// \brief Helper to test for a load that can be folded with x86 shuffles.
8378 /// This is particularly important because the set of instructions varies
8379 /// significantly based on whether the operand is a load or not.
8380 static bool isShuffleFoldableLoad(SDValue V) {
8381 V = peekThroughBitcasts(V);
8382 return ISD::isNON_EXTLoad(V.getNode());
8385 /// \brief Try to lower insertion of a single element into a zero vector.
8387 /// This is a common pattern that we have especially efficient patterns to lower
8388 /// across all subtarget feature sets.
8389 static SDValue lowerVectorShuffleAsElementInsertion(
8390 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
8391 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
8392 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8394 MVT EltVT = VT.getVectorElementType();
8396 int V2Index = std::find_if(Mask.begin(), Mask.end(),
8397 [&Mask](int M) { return M >= (int)Mask.size(); }) -
8399 bool IsV1Zeroable = true;
8400 for (int i = 0, Size = Mask.size(); i < Size; ++i)
8401 if (i != V2Index && !Zeroable[i]) {
8402 IsV1Zeroable = false;
8406 // Check for a single input from a SCALAR_TO_VECTOR node.
8407 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
8408 // all the smarts here sunk into that routine. However, the current
8409 // lowering of BUILD_VECTOR makes that nearly impossible until the old
8410 // vector shuffle lowering is dead.
8411 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
8413 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
8414 // We need to zext the scalar if it is smaller than an i32.
8415 V2S = DAG.getBitcast(EltVT, V2S);
8416 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
8417 // Using zext to expand a narrow element won't work for non-zero
8422 // Zero-extend directly to i32.
8424 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
8426 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
8427 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
8428 EltVT == MVT::i16) {
8429 // Either not inserting from the low element of the input or the input
8430 // element size is too small to use VZEXT_MOVL to clear the high bits.
8434 if (!IsV1Zeroable) {
8435 // If V1 can't be treated as a zero vector we have fewer options to lower
8436 // this. We can't support integer vectors or non-zero targets cheaply, and
8437 // the V1 elements can't be permuted in any way.
8438 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
8439 if (!VT.isFloatingPoint() || V2Index != 0)
8441 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8442 V1Mask[V2Index] = -1;
8443 if (!isNoopShuffleMask(V1Mask))
8445 // This is essentially a special case blend operation, but if we have
8446 // general purpose blend operations, they are always faster. Bail and let
8447 // the rest of the lowering handle these as blends.
8448 if (Subtarget.hasSSE41())
8451 // Otherwise, use MOVSD or MOVSS.
8452 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8453 "Only two types of floating point element types to handle!");
8454 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8458 // This lowering only works for the low element with floating point vectors.
8459 if (VT.isFloatingPoint() && V2Index != 0)
8462 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8464 V2 = DAG.getBitcast(VT, V2);
8467 // If we have 4 or fewer lanes we can cheaply shuffle the element into
8468 // the desired position. Otherwise it is more efficient to do a vector
8469 // shift left. We know that we can do a vector shift left because all
8470 // the inputs are zero.
8471 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8472 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8473 V2Shuffle[V2Index] = 0;
8474 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8476 V2 = DAG.getBitcast(MVT::v16i8, V2);
8478 X86ISD::VSHLDQ, DL, MVT::v16i8, V2,
8479 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
8480 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
8481 DAG.getDataLayout(), VT)));
8482 V2 = DAG.getBitcast(VT, V2);
8488 /// Try to lower broadcast of a single - truncated - integer element,
8489 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
8491 /// This assumes we have AVX2.
8492 static SDValue lowerVectorShuffleAsTruncBroadcast(const SDLoc &DL, MVT VT,
8493 SDValue V0, int BroadcastIdx,
8494 const X86Subtarget &Subtarget,
8495 SelectionDAG &DAG) {
8496 assert(Subtarget.hasAVX2() &&
8497 "We can only lower integer broadcasts with AVX2!");
8499 EVT EltVT = VT.getVectorElementType();
8500 EVT V0VT = V0.getValueType();
8502 assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
8503 assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
8505 EVT V0EltVT = V0VT.getVectorElementType();
8506 if (!V0EltVT.isInteger())
8509 const unsigned EltSize = EltVT.getSizeInBits();
8510 const unsigned V0EltSize = V0EltVT.getSizeInBits();
8512 // This is only a truncation if the original element type is larger.
8513 if (V0EltSize <= EltSize)
8516 assert(((V0EltSize % EltSize) == 0) &&
8517 "Scalar type sizes must all be powers of 2 on x86!");
8519 const unsigned V0Opc = V0.getOpcode();
8520 const unsigned Scale = V0EltSize / EltSize;
8521 const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
8523 if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
8524 V0Opc != ISD::BUILD_VECTOR)
8527 SDValue Scalar = V0.getOperand(V0BroadcastIdx);
8529 // If we're extracting non-least-significant bits, shift so we can truncate.
8530 // Hopefully, we can fold away the trunc/srl/load into the broadcast.
8531 // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
8532 // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
8533 if (const int OffsetIdx = BroadcastIdx % Scale)
8534 Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
8535 DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
8537 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
8538 DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
8541 /// \brief Try to lower broadcast of a single element.
8543 /// For convenience, this code also bundles all of the subtarget feature set
8544 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8545 /// a convenient way to factor it out.
8546 /// FIXME: This is very similar to LowerVectorBroadcast - can we merge them?
8547 static SDValue lowerVectorShuffleAsBroadcast(const SDLoc &DL, MVT VT,
8548 SDValue V1, SDValue V2,
8550 const X86Subtarget &Subtarget,
8551 SelectionDAG &DAG) {
8552 if (!((Subtarget.hasSSE3() && VT == MVT::v2f64) ||
8553 (Subtarget.hasAVX() && VT.isFloatingPoint()) ||
8554 (Subtarget.hasAVX2() && VT.isInteger())))
8557 // With MOVDDUP (v2f64) we can broadcast from a register or a load, otherwise
8558 // we can only broadcast from a register with AVX2.
8559 unsigned NumElts = Mask.size();
8560 unsigned Opcode = VT == MVT::v2f64 ? X86ISD::MOVDDUP : X86ISD::VBROADCAST;
8561 bool BroadcastFromReg = (Opcode == X86ISD::MOVDDUP) || Subtarget.hasAVX2();
8563 // Check that the mask is a broadcast.
8564 int BroadcastIdx = -1;
8565 for (int i = 0; i != (int)NumElts; ++i) {
8566 SmallVector<int, 8> BroadcastMask(NumElts, i);
8567 if (isShuffleEquivalent(V1, V2, Mask, BroadcastMask)) {
8573 if (BroadcastIdx < 0)
8575 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8576 "a sorted mask where the broadcast "
8579 // Go up the chain of (vector) values to find a scalar load that we can
8580 // combine with the broadcast.
8583 switch (V.getOpcode()) {
8584 case ISD::BITCAST: {
8585 SDValue VSrc = V.getOperand(0);
8586 MVT SrcVT = VSrc.getSimpleValueType();
8587 if (VT.getScalarSizeInBits() != SrcVT.getScalarSizeInBits())
8592 case ISD::CONCAT_VECTORS: {
8593 int OperandSize = Mask.size() / V.getNumOperands();
8594 V = V.getOperand(BroadcastIdx / OperandSize);
8595 BroadcastIdx %= OperandSize;
8598 case ISD::INSERT_SUBVECTOR: {
8599 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8600 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8604 int BeginIdx = (int)ConstantIdx->getZExtValue();
8606 BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
8607 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8608 BroadcastIdx -= BeginIdx;
8619 // Check if this is a broadcast of a scalar. We special case lowering
8620 // for scalars so that we can more effectively fold with loads.
8621 // First, look through bitcast: if the original value has a larger element
8622 // type than the shuffle, the broadcast element is in essence truncated.
8623 // Make that explicit to ease folding.
8624 if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
8625 if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
8626 DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
8627 return TruncBroadcast;
8629 MVT BroadcastVT = VT;
8631 // Peek through any bitcast (only useful for loads).
8632 SDValue BC = peekThroughBitcasts(V);
8634 // Also check the simpler case, where we can directly reuse the scalar.
8635 if (V.getOpcode() == ISD::BUILD_VECTOR ||
8636 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8637 V = V.getOperand(BroadcastIdx);
8639 // If we can't broadcast from a register, check that the input is a load.
8640 if (!BroadcastFromReg && !isShuffleFoldableLoad(V))
8642 } else if (MayFoldLoad(BC) && !cast<LoadSDNode>(BC)->isVolatile()) {
8643 // 32-bit targets need to load i64 as a f64 and then bitcast the result.
8644 if (!Subtarget.is64Bit() && VT.getScalarType() == MVT::i64) {
8645 BroadcastVT = MVT::getVectorVT(MVT::f64, VT.getVectorNumElements());
8646 Opcode = (BroadcastVT.is128BitVector() ? X86ISD::MOVDDUP : Opcode);
8649 // If we are broadcasting a load that is only used by the shuffle
8650 // then we can reduce the vector load to the broadcasted scalar load.
8651 LoadSDNode *Ld = cast<LoadSDNode>(BC);
8652 SDValue BaseAddr = Ld->getOperand(1);
8653 EVT SVT = BroadcastVT.getScalarType();
8654 unsigned Offset = BroadcastIdx * SVT.getStoreSize();
8655 SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
8656 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
8657 DAG.getMachineFunction().getMachineMemOperand(
8658 Ld->getMemOperand(), Offset, SVT.getStoreSize()));
8660 // Make sure the newly-created LOAD is in the same position as Ld in
8661 // terms of dependency. We create a TokenFactor for Ld and V,
8662 // and update uses of Ld's output chain to use the TokenFactor.
8663 if (Ld->hasAnyUseOfValue(1)) {
8664 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
8665 SDValue(Ld, 1), SDValue(V.getNode(), 1));
8666 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
8667 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
8668 SDValue(V.getNode(), 1));
8670 } else if (!BroadcastFromReg) {
8671 // We can't broadcast from a vector register.
8673 } else if (BroadcastIdx != 0) {
8674 // We can only broadcast from the zero-element of a vector register,
8675 // but it can be advantageous to broadcast from the zero-element of a
8677 if (!VT.is256BitVector() && !VT.is512BitVector())
8680 // VPERMQ/VPERMPD can perform the cross-lane shuffle directly.
8681 if (VT == MVT::v4f64 || VT == MVT::v4i64)
8684 // Only broadcast the zero-element of a 128-bit subvector.
8685 unsigned EltSize = VT.getScalarSizeInBits();
8686 if (((BroadcastIdx * EltSize) % 128) != 0)
8689 MVT ExtVT = MVT::getVectorVT(VT.getScalarType(), 128 / EltSize);
8690 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtVT, V,
8691 DAG.getIntPtrConstant(BroadcastIdx, DL));
8694 if (Opcode == X86ISD::MOVDDUP && !V.getValueType().isVector())
8695 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
8696 DAG.getBitcast(MVT::f64, V));
8698 // Bitcast back to the same scalar type as BroadcastVT.
8699 MVT SrcVT = V.getSimpleValueType();
8700 if (SrcVT.getScalarType() != BroadcastVT.getScalarType()) {
8701 assert(SrcVT.getScalarSizeInBits() == BroadcastVT.getScalarSizeInBits() &&
8702 "Unexpected vector element size");
8703 if (SrcVT.isVector()) {
8704 unsigned NumSrcElts = SrcVT.getVectorNumElements();
8705 SrcVT = MVT::getVectorVT(BroadcastVT.getScalarType(), NumSrcElts);
8707 SrcVT = BroadcastVT.getScalarType();
8709 V = DAG.getBitcast(SrcVT, V);
8712 return DAG.getBitcast(VT, DAG.getNode(Opcode, DL, BroadcastVT, V));
8715 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8716 // INSERTPS when the V1 elements are already in the correct locations
8717 // because otherwise we can just always use two SHUFPS instructions which
8718 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8719 // perform INSERTPS if a single V1 element is out of place and all V2
8720 // elements are zeroable.
8721 static bool matchVectorShuffleAsInsertPS(SDValue &V1, SDValue &V2,
8722 unsigned &InsertPSMask,
8723 const SmallBitVector &Zeroable,
8725 SelectionDAG &DAG) {
8726 assert(V1.getSimpleValueType().is128BitVector() && "Bad operand type!");
8727 assert(V2.getSimpleValueType().is128BitVector() && "Bad operand type!");
8728 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8730 int V1DstIndex = -1;
8731 int V2DstIndex = -1;
8732 bool V1UsedInPlace = false;
8734 for (int i = 0; i < 4; ++i) {
8735 // Synthesize a zero mask from the zeroable elements (includes undefs).
8741 // Flag if we use any V1 inputs in place.
8743 V1UsedInPlace = true;
8747 // We can only insert a single non-zeroable element.
8748 if (V1DstIndex >= 0 || V2DstIndex >= 0)
8752 // V1 input out of place for insertion.
8755 // V2 input for insertion.
8760 // Don't bother if we have no (non-zeroable) element for insertion.
8761 if (V1DstIndex < 0 && V2DstIndex < 0)
8764 // Determine element insertion src/dst indices. The src index is from the
8765 // start of the inserted vector, not the start of the concatenated vector.
8766 unsigned V2SrcIndex = 0;
8767 if (V1DstIndex >= 0) {
8768 // If we have a V1 input out of place, we use V1 as the V2 element insertion
8769 // and don't use the original V2 at all.
8770 V2SrcIndex = Mask[V1DstIndex];
8771 V2DstIndex = V1DstIndex;
8774 V2SrcIndex = Mask[V2DstIndex] - 4;
8777 // If no V1 inputs are used in place, then the result is created only from
8778 // the zero mask and the V2 insertion - so remove V1 dependency.
8780 V1 = DAG.getUNDEF(MVT::v4f32);
8782 // Insert the V2 element into the desired position.
8783 InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8784 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8788 static SDValue lowerVectorShuffleAsInsertPS(const SDLoc &DL, SDValue V1,
8789 SDValue V2, ArrayRef<int> Mask,
8790 SelectionDAG &DAG) {
8791 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8792 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8793 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8795 // Attempt to match the insertps pattern.
8796 unsigned InsertPSMask;
8797 if (!matchVectorShuffleAsInsertPS(V1, V2, InsertPSMask, Zeroable, Mask, DAG))
8800 // Insert the V2 element into the desired position.
8801 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8802 DAG.getConstant(InsertPSMask, DL, MVT::i8));
8805 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8806 /// UNPCK instruction.
8808 /// This specifically targets cases where we end up with alternating between
8809 /// the two inputs, and so can permute them into something that feeds a single
8810 /// UNPCK instruction. Note that this routine only targets integer vectors
8811 /// because for floating point vectors we have a generalized SHUFPS lowering
8812 /// strategy that handles everything that doesn't *exactly* match an unpack,
8813 /// making this clever lowering unnecessary.
8814 static SDValue lowerVectorShuffleAsPermuteAndUnpack(const SDLoc &DL, MVT VT,
8815 SDValue V1, SDValue V2,
8817 SelectionDAG &DAG) {
8818 assert(!VT.isFloatingPoint() &&
8819 "This routine only supports integer vectors.");
8820 assert(VT.is128BitVector() &&
8821 "This routine only works on 128-bit vectors.");
8822 assert(!V2.isUndef() &&
8823 "This routine should only be used when blending two inputs.");
8824 assert(Mask.size() >= 2 && "Single element masks are invalid.");
8826 int Size = Mask.size();
8829 count_if(Mask, [Size](int M) { return M >= 0 && M % Size < Size / 2; });
8831 count_if(Mask, [Size](int M) { return M % Size >= Size / 2; });
8833 bool UnpackLo = NumLoInputs >= NumHiInputs;
8835 auto TryUnpack = [&](int ScalarSize, int Scale) {
8836 SmallVector<int, 16> V1Mask((unsigned)Size, -1);
8837 SmallVector<int, 16> V2Mask((unsigned)Size, -1);
8839 for (int i = 0; i < Size; ++i) {
8843 // Each element of the unpack contains Scale elements from this mask.
8844 int UnpackIdx = i / Scale;
8846 // We only handle the case where V1 feeds the first slots of the unpack.
8847 // We rely on canonicalization to ensure this is the case.
8848 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8851 // Setup the mask for this input. The indexing is tricky as we have to
8852 // handle the unpack stride.
8853 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8854 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8858 // If we will have to shuffle both inputs to use the unpack, check whether
8859 // we can just unpack first and shuffle the result. If so, skip this unpack.
8860 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8861 !isNoopShuffleMask(V2Mask))
8864 // Shuffle the inputs into place.
8865 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8866 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8868 // Cast the inputs to the type we will use to unpack them.
8869 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), Size / Scale);
8870 V1 = DAG.getBitcast(UnpackVT, V1);
8871 V2 = DAG.getBitcast(UnpackVT, V2);
8873 // Unpack the inputs and cast the result back to the desired type.
8874 return DAG.getBitcast(
8875 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8879 // We try each unpack from the largest to the smallest to try and find one
8880 // that fits this mask.
8881 int OrigScalarSize = VT.getScalarSizeInBits();
8882 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2)
8883 if (SDValue Unpack = TryUnpack(ScalarSize, ScalarSize / OrigScalarSize))
8886 // If none of the unpack-rooted lowerings worked (or were profitable) try an
8888 if (NumLoInputs == 0 || NumHiInputs == 0) {
8889 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8890 "We have to have *some* inputs!");
8891 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8893 // FIXME: We could consider the total complexity of the permute of each
8894 // possible unpacking. Or at the least we should consider how many
8895 // half-crossings are created.
8896 // FIXME: We could consider commuting the unpacks.
8898 SmallVector<int, 32> PermMask((unsigned)Size, -1);
8899 for (int i = 0; i < Size; ++i) {
8903 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8906 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8908 return DAG.getVectorShuffle(
8909 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8911 DAG.getUNDEF(VT), PermMask);
8917 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8919 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8920 /// support for floating point shuffles but not integer shuffles. These
8921 /// instructions will incur a domain crossing penalty on some chips though so
8922 /// it is better to avoid lowering through this for integer vectors where
8924 static SDValue lowerV2F64VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
8925 SDValue V1, SDValue V2,
8926 const X86Subtarget &Subtarget,
8927 SelectionDAG &DAG) {
8928 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8929 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8930 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8933 // Check for being able to broadcast a single element.
8934 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(
8935 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8938 // Straight shuffle of a single input vector. Simulate this by using the
8939 // single input as both of the "inputs" to this instruction..
8940 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8942 if (Subtarget.hasAVX()) {
8943 // If we have AVX, we can use VPERMILPS which will allow folding a load
8944 // into the shuffle.
8945 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8946 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8949 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8950 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8952 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8953 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8955 // If we have a single input, insert that into V1 if we can do so cheaply.
8956 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8957 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8958 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8960 // Try inverting the insertion since for v2 masks it is easy to do and we
8961 // can't reliably sort the mask one way or the other.
8962 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8963 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8964 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8965 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8969 // Try to use one of the special instruction patterns to handle two common
8970 // blend patterns if a zero-blend above didn't work.
8971 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8972 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8973 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8974 // We can either use a special instruction to load over the low double or
8975 // to move just the low double.
8977 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8979 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8981 if (Subtarget.hasSSE41())
8982 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8986 // Use dedicated unpack instructions for masks that match their pattern.
8988 lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8991 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8992 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8993 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8996 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8998 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8999 /// the integer unit to minimize domain crossing penalties. However, for blends
9000 /// it falls back to the floating point shuffle operation with appropriate bit
9002 static SDValue lowerV2I64VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
9003 SDValue V1, SDValue V2,
9004 const X86Subtarget &Subtarget,
9005 SelectionDAG &DAG) {
9006 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
9007 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
9008 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
9011 // Check for being able to broadcast a single element.
9012 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(
9013 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
9016 // Straight shuffle of a single input vector. For everything from SSE2
9017 // onward this has a single fast instruction with no scary immediates.
9018 // We have to map the mask as it is actually a v4i32 shuffle instruction.
9019 V1 = DAG.getBitcast(MVT::v4i32, V1);
9020 int WidenedMask[4] = {
9021 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
9022 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
9023 return DAG.getBitcast(
9025 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
9026 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
9028 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
9029 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
9030 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
9031 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
9033 // If we have a blend of two same-type PACKUS operations and the blend aligns
9034 // with the low and high halves, we can just merge the PACKUS operations.
9035 // This is particularly important as it lets us merge shuffles that this
9036 // routine itself creates.
9037 auto GetPackNode = [](SDValue V) {
9038 V = peekThroughBitcasts(V);
9039 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
9041 if (SDValue V1Pack = GetPackNode(V1))
9042 if (SDValue V2Pack = GetPackNode(V2)) {
9043 EVT PackVT = V1Pack.getValueType();
9044 if (PackVT == V2Pack.getValueType())
9045 return DAG.getBitcast(MVT::v2i64,
9046 DAG.getNode(X86ISD::PACKUS, DL, PackVT,
9047 Mask[0] == 0 ? V1Pack.getOperand(0)
9048 : V1Pack.getOperand(1),
9049 Mask[1] == 2 ? V2Pack.getOperand(0)
9050 : V2Pack.getOperand(1)));
9053 // Try to use shift instructions.
9054 if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask,
9058 // When loading a scalar and then shuffling it into a vector we can often do
9059 // the insertion cheaply.
9060 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9061 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
9063 // Try inverting the insertion since for v2 masks it is easy to do and we
9064 // can't reliably sort the mask one way or the other.
9065 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
9066 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9067 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
9070 // We have different paths for blend lowering, but they all must use the
9071 // *exact* same predicate.
9072 bool IsBlendSupported = Subtarget.hasSSE41();
9073 if (IsBlendSupported)
9074 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
9078 // Use dedicated unpack instructions for masks that match their pattern.
9080 lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
9083 // Try to use byte rotation instructions.
9084 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
9085 if (Subtarget.hasSSSE3())
9086 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9087 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
9090 // If we have direct support for blends, we should lower by decomposing into
9091 // a permute. That will be faster than the domain cross.
9092 if (IsBlendSupported)
9093 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
9096 // We implement this with SHUFPD which is pretty lame because it will likely
9097 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
9098 // However, all the alternatives are still more cycles and newer chips don't
9099 // have this problem. It would be really nice if x86 had better shuffles here.
9100 V1 = DAG.getBitcast(MVT::v2f64, V1);
9101 V2 = DAG.getBitcast(MVT::v2f64, V2);
9102 return DAG.getBitcast(MVT::v2i64,
9103 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
9106 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
9108 /// This is used to disable more specialized lowerings when the shufps lowering
9109 /// will happen to be efficient.
9110 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
9111 // This routine only handles 128-bit shufps.
9112 assert(Mask.size() == 4 && "Unsupported mask size!");
9113 assert(Mask[0] >= -1 && Mask[0] < 8 && "Out of bound mask element!");
9114 assert(Mask[1] >= -1 && Mask[1] < 8 && "Out of bound mask element!");
9115 assert(Mask[2] >= -1 && Mask[2] < 8 && "Out of bound mask element!");
9116 assert(Mask[3] >= -1 && Mask[3] < 8 && "Out of bound mask element!");
9118 // To lower with a single SHUFPS we need to have the low half and high half
9119 // each requiring a single input.
9120 if (Mask[0] >= 0 && Mask[1] >= 0 && (Mask[0] < 4) != (Mask[1] < 4))
9122 if (Mask[2] >= 0 && Mask[3] >= 0 && (Mask[2] < 4) != (Mask[3] < 4))
9128 /// \brief Lower a vector shuffle using the SHUFPS instruction.
9130 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
9131 /// It makes no assumptions about whether this is the *best* lowering, it simply
9133 static SDValue lowerVectorShuffleWithSHUFPS(const SDLoc &DL, MVT VT,
9134 ArrayRef<int> Mask, SDValue V1,
9135 SDValue V2, SelectionDAG &DAG) {
9136 SDValue LowV = V1, HighV = V2;
9137 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
9139 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
9141 if (NumV2Elements == 1) {
9143 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
9146 // Compute the index adjacent to V2Index and in the same half by toggling
9148 int V2AdjIndex = V2Index ^ 1;
9150 if (Mask[V2AdjIndex] < 0) {
9151 // Handles all the cases where we have a single V2 element and an undef.
9152 // This will only ever happen in the high lanes because we commute the
9153 // vector otherwise.
9155 std::swap(LowV, HighV);
9156 NewMask[V2Index] -= 4;
9158 // Handle the case where the V2 element ends up adjacent to a V1 element.
9159 // To make this work, blend them together as the first step.
9160 int V1Index = V2AdjIndex;
9161 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
9162 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9163 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
9165 // Now proceed to reconstruct the final blend as we have the necessary
9166 // high or low half formed.
9173 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
9174 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
9176 } else if (NumV2Elements == 2) {
9177 if (Mask[0] < 4 && Mask[1] < 4) {
9178 // Handle the easy case where we have V1 in the low lanes and V2 in the
9182 } else if (Mask[2] < 4 && Mask[3] < 4) {
9183 // We also handle the reversed case because this utility may get called
9184 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
9185 // arrange things in the right direction.
9191 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
9192 // trying to place elements directly, just blend them and set up the final
9193 // shuffle to place them.
9195 // The first two blend mask elements are for V1, the second two are for
9197 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
9198 Mask[2] < 4 ? Mask[2] : Mask[3],
9199 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
9200 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
9201 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9202 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
9204 // Now we do a normal shuffle of V1 by giving V1 as both operands to
9207 NewMask[0] = Mask[0] < 4 ? 0 : 2;
9208 NewMask[1] = Mask[0] < 4 ? 2 : 0;
9209 NewMask[2] = Mask[2] < 4 ? 1 : 3;
9210 NewMask[3] = Mask[2] < 4 ? 3 : 1;
9213 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
9214 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
9217 /// \brief Lower 4-lane 32-bit floating point shuffles.
9219 /// Uses instructions exclusively from the floating point unit to minimize
9220 /// domain crossing penalties, as these are sufficient to implement all v4f32
9222 static SDValue lowerV4F32VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
9223 SDValue V1, SDValue V2,
9224 const X86Subtarget &Subtarget,
9225 SelectionDAG &DAG) {
9226 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
9227 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
9228 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9230 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
9232 if (NumV2Elements == 0) {
9233 // Check for being able to broadcast a single element.
9234 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(
9235 DL, MVT::v4f32, V1, V2, Mask, Subtarget, DAG))
9238 // Use even/odd duplicate instructions for masks that match their pattern.
9239 if (Subtarget.hasSSE3()) {
9240 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9241 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
9242 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
9243 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
9246 if (Subtarget.hasAVX()) {
9247 // If we have AVX, we can use VPERMILPS which will allow folding a load
9248 // into the shuffle.
9249 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
9250 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9253 // Otherwise, use a straight shuffle of a single input vector. We pass the
9254 // input vector to both operands to simulate this with a SHUFPS.
9255 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
9256 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9259 // There are special ways we can lower some single-element blends. However, we
9260 // have custom ways we can lower more complex single-element blends below that
9261 // we defer to if both this and BLENDPS fail to match, so restrict this to
9262 // when the V2 input is targeting element 0 of the mask -- that is the fast
9264 if (NumV2Elements == 1 && Mask[0] >= 4)
9265 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
9266 Mask, Subtarget, DAG))
9269 if (Subtarget.hasSSE41()) {
9270 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
9274 // Use INSERTPS if we can complete the shuffle efficiently.
9275 if (SDValue V = lowerVectorShuffleAsInsertPS(DL, V1, V2, Mask, DAG))
9278 if (!isSingleSHUFPSMask(Mask))
9279 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
9280 DL, MVT::v4f32, V1, V2, Mask, DAG))
9284 // Use low/high mov instructions.
9285 if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5}))
9286 return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V2);
9287 if (isShuffleEquivalent(V1, V2, Mask, {2, 3, 6, 7}))
9288 return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V2, V1);
9290 // Use dedicated unpack instructions for masks that match their pattern.
9292 lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
9295 // Otherwise fall back to a SHUFPS lowering strategy.
9296 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
9299 /// \brief Lower 4-lane i32 vector shuffles.
9301 /// We try to handle these with integer-domain shuffles where we can, but for
9302 /// blends we use the floating point domain blend instructions.
9303 static SDValue lowerV4I32VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
9304 SDValue V1, SDValue V2,
9305 const X86Subtarget &Subtarget,
9306 SelectionDAG &DAG) {
9307 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
9308 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
9309 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9311 // Whenever we can lower this as a zext, that instruction is strictly faster
9312 // than any alternative. It also allows us to fold memory operands into the
9313 // shuffle in many cases.
9314 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
9315 Mask, Subtarget, DAG))
9318 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
9320 if (NumV2Elements == 0) {
9321 // Check for being able to broadcast a single element.
9322 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(
9323 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
9326 // Straight shuffle of a single input vector. For everything from SSE2
9327 // onward this has a single fast instruction with no scary immediates.
9328 // We coerce the shuffle pattern to be compatible with UNPCK instructions
9329 // but we aren't actually going to use the UNPCK instruction because doing
9330 // so prevents folding a load into this instruction or making a copy.
9331 const int UnpackLoMask[] = {0, 0, 1, 1};
9332 const int UnpackHiMask[] = {2, 2, 3, 3};
9333 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
9334 Mask = UnpackLoMask;
9335 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
9336 Mask = UnpackHiMask;
9338 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
9339 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9342 // Try to use shift instructions.
9343 if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask,
9347 // There are special ways we can lower some single-element blends.
9348 if (NumV2Elements == 1)
9349 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
9350 Mask, Subtarget, DAG))
9353 // We have different paths for blend lowering, but they all must use the
9354 // *exact* same predicate.
9355 bool IsBlendSupported = Subtarget.hasSSE41();
9356 if (IsBlendSupported)
9357 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
9361 if (SDValue Masked =
9362 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
9365 // Use dedicated unpack instructions for masks that match their pattern.
9367 lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
9370 // Try to use byte rotation instructions.
9371 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
9372 if (Subtarget.hasSSSE3())
9373 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9374 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
9377 // If we have direct support for blends, we should lower by decomposing into
9378 // a permute. That will be faster than the domain cross.
9379 if (IsBlendSupported)
9380 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
9383 // Try to lower by permuting the inputs into an unpack instruction.
9384 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
9388 // We implement this with SHUFPS because it can blend from two vectors.
9389 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
9390 // up the inputs, bypassing domain shift penalties that we would encur if we
9391 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
9393 return DAG.getBitcast(
9395 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
9396 DAG.getBitcast(MVT::v4f32, V2), Mask));
9399 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
9400 /// shuffle lowering, and the most complex part.
9402 /// The lowering strategy is to try to form pairs of input lanes which are
9403 /// targeted at the same half of the final vector, and then use a dword shuffle
9404 /// to place them onto the right half, and finally unpack the paired lanes into
9405 /// their final position.
9407 /// The exact breakdown of how to form these dword pairs and align them on the
9408 /// correct sides is really tricky. See the comments within the function for
9409 /// more of the details.
9411 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
9412 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
9413 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
9414 /// vector, form the analogous 128-bit 8-element Mask.
9415 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
9416 const SDLoc &DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
9417 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
9418 assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
9419 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
9421 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
9422 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
9423 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
9425 SmallVector<int, 4> LoInputs;
9426 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
9427 [](int M) { return M >= 0; });
9428 std::sort(LoInputs.begin(), LoInputs.end());
9429 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
9430 SmallVector<int, 4> HiInputs;
9431 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
9432 [](int M) { return M >= 0; });
9433 std::sort(HiInputs.begin(), HiInputs.end());
9434 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
9436 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
9437 int NumHToL = LoInputs.size() - NumLToL;
9439 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
9440 int NumHToH = HiInputs.size() - NumLToH;
9441 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
9442 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
9443 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
9444 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
9446 // If we are splatting two values from one half - one to each half, then
9447 // we can shuffle that half so each is splatted to a dword, then splat those
9448 // to their respective halves.
9449 auto SplatHalfs = [&](int LoInput, int HiInput, unsigned ShufWOp,
9451 int PSHUFHalfMask[] = {LoInput % 4, LoInput % 4, HiInput % 4, HiInput % 4};
9452 int PSHUFDMask[] = {DOffset + 0, DOffset + 0, DOffset + 1, DOffset + 1};
9453 V = DAG.getNode(ShufWOp, DL, VT, V,
9454 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
9455 V = DAG.getBitcast(PSHUFDVT, V);
9456 V = DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, V,
9457 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
9458 return DAG.getBitcast(VT, V);
9461 if (NumLToL == 1 && NumLToH == 1 && (NumHToL + NumHToH) == 0)
9462 return SplatHalfs(LToLInputs[0], LToHInputs[0], X86ISD::PSHUFLW, 0);
9463 if (NumHToL == 1 && NumHToH == 1 && (NumLToL + NumLToH) == 0)
9464 return SplatHalfs(HToLInputs[0], HToHInputs[0], X86ISD::PSHUFHW, 2);
9466 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
9467 // such inputs we can swap two of the dwords across the half mark and end up
9468 // with <=2 inputs to each half in each half. Once there, we can fall through
9469 // to the generic code below. For example:
9471 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
9472 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
9474 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
9475 // and an existing 2-into-2 on the other half. In this case we may have to
9476 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
9477 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
9478 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
9479 // because any other situation (including a 3-into-1 or 1-into-3 in the other
9480 // half than the one we target for fixing) will be fixed when we re-enter this
9481 // path. We will also combine away any sequence of PSHUFD instructions that
9482 // result into a single instruction. Here is an example of the tricky case:
9484 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
9485 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
9487 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
9489 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
9490 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
9492 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
9493 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
9495 // The result is fine to be handled by the generic logic.
9496 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
9497 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
9498 int AOffset, int BOffset) {
9499 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
9500 "Must call this with A having 3 or 1 inputs from the A half.");
9501 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
9502 "Must call this with B having 1 or 3 inputs from the B half.");
9503 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
9504 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
9506 bool ThreeAInputs = AToAInputs.size() == 3;
9508 // Compute the index of dword with only one word among the three inputs in
9509 // a half by taking the sum of the half with three inputs and subtracting
9510 // the sum of the actual three inputs. The difference is the remaining
9513 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
9514 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
9515 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
9516 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
9517 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
9518 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
9519 int TripleNonInputIdx =
9520 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
9521 TripleDWord = TripleNonInputIdx / 2;
9523 // We use xor with one to compute the adjacent DWord to whichever one the
9525 OneInputDWord = (OneInput / 2) ^ 1;
9527 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
9528 // and BToA inputs. If there is also such a problem with the BToB and AToB
9529 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
9530 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
9531 // is essential that we don't *create* a 3<-1 as then we might oscillate.
9532 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
9533 // Compute how many inputs will be flipped by swapping these DWords. We
9535 // to balance this to ensure we don't form a 3-1 shuffle in the other
9537 int NumFlippedAToBInputs =
9538 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
9539 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
9540 int NumFlippedBToBInputs =
9541 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
9542 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
9543 if ((NumFlippedAToBInputs == 1 &&
9544 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
9545 (NumFlippedBToBInputs == 1 &&
9546 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
9547 // We choose whether to fix the A half or B half based on whether that
9548 // half has zero flipped inputs. At zero, we may not be able to fix it
9549 // with that half. We also bias towards fixing the B half because that
9550 // will more commonly be the high half, and we have to bias one way.
9551 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
9552 ArrayRef<int> Inputs) {
9553 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
9554 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
9555 PinnedIdx ^ 1) != Inputs.end();
9556 // Determine whether the free index is in the flipped dword or the
9557 // unflipped dword based on where the pinned index is. We use this bit
9558 // in an xor to conditionally select the adjacent dword.
9559 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
9560 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9561 FixFreeIdx) != Inputs.end();
9562 if (IsFixIdxInput == IsFixFreeIdxInput)
9564 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9565 FixFreeIdx) != Inputs.end();
9566 assert(IsFixIdxInput != IsFixFreeIdxInput &&
9567 "We need to be changing the number of flipped inputs!");
9568 int PSHUFHalfMask[] = {0, 1, 2, 3};
9569 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
9570 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
9572 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
9575 if (M >= 0 && M == FixIdx)
9577 else if (M >= 0 && M == FixFreeIdx)
9580 if (NumFlippedBToBInputs != 0) {
9582 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
9583 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
9585 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
9586 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
9587 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
9592 int PSHUFDMask[] = {0, 1, 2, 3};
9593 PSHUFDMask[ADWord] = BDWord;
9594 PSHUFDMask[BDWord] = ADWord;
9597 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9598 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9600 // Adjust the mask to match the new locations of A and B.
9602 if (M >= 0 && M/2 == ADWord)
9603 M = 2 * BDWord + M % 2;
9604 else if (M >= 0 && M/2 == BDWord)
9605 M = 2 * ADWord + M % 2;
9607 // Recurse back into this routine to re-compute state now that this isn't
9608 // a 3 and 1 problem.
9609 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
9612 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
9613 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
9614 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
9615 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
9617 // At this point there are at most two inputs to the low and high halves from
9618 // each half. That means the inputs can always be grouped into dwords and
9619 // those dwords can then be moved to the correct half with a dword shuffle.
9620 // We use at most one low and one high word shuffle to collect these paired
9621 // inputs into dwords, and finally a dword shuffle to place them.
9622 int PSHUFLMask[4] = {-1, -1, -1, -1};
9623 int PSHUFHMask[4] = {-1, -1, -1, -1};
9624 int PSHUFDMask[4] = {-1, -1, -1, -1};
9626 // First fix the masks for all the inputs that are staying in their
9627 // original halves. This will then dictate the targets of the cross-half
9629 auto fixInPlaceInputs =
9630 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
9631 MutableArrayRef<int> SourceHalfMask,
9632 MutableArrayRef<int> HalfMask, int HalfOffset) {
9633 if (InPlaceInputs.empty())
9635 if (InPlaceInputs.size() == 1) {
9636 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9637 InPlaceInputs[0] - HalfOffset;
9638 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
9641 if (IncomingInputs.empty()) {
9642 // Just fix all of the in place inputs.
9643 for (int Input : InPlaceInputs) {
9644 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
9645 PSHUFDMask[Input / 2] = Input / 2;
9650 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
9651 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9652 InPlaceInputs[0] - HalfOffset;
9653 // Put the second input next to the first so that they are packed into
9654 // a dword. We find the adjacent index by toggling the low bit.
9655 int AdjIndex = InPlaceInputs[0] ^ 1;
9656 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
9657 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
9658 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
9660 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
9661 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
9663 // Now gather the cross-half inputs and place them into a free dword of
9664 // their target half.
9665 // FIXME: This operation could almost certainly be simplified dramatically to
9666 // look more like the 3-1 fixing operation.
9667 auto moveInputsToRightHalf = [&PSHUFDMask](
9668 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
9669 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
9670 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
9672 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
9673 return SourceHalfMask[Word] >= 0 && SourceHalfMask[Word] != Word;
9675 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
9677 int LowWord = Word & ~1;
9678 int HighWord = Word | 1;
9679 return isWordClobbered(SourceHalfMask, LowWord) ||
9680 isWordClobbered(SourceHalfMask, HighWord);
9683 if (IncomingInputs.empty())
9686 if (ExistingInputs.empty()) {
9687 // Map any dwords with inputs from them into the right half.
9688 for (int Input : IncomingInputs) {
9689 // If the source half mask maps over the inputs, turn those into
9690 // swaps and use the swapped lane.
9691 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
9692 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] < 0) {
9693 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
9694 Input - SourceOffset;
9695 // We have to swap the uses in our half mask in one sweep.
9696 for (int &M : HalfMask)
9697 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
9699 else if (M == Input)
9700 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9702 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
9703 Input - SourceOffset &&
9704 "Previous placement doesn't match!");
9706 // Note that this correctly re-maps both when we do a swap and when
9707 // we observe the other side of the swap above. We rely on that to
9708 // avoid swapping the members of the input list directly.
9709 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9712 // Map the input's dword into the correct half.
9713 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] < 0)
9714 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
9716 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
9718 "Previous placement doesn't match!");
9721 // And just directly shift any other-half mask elements to be same-half
9722 // as we will have mirrored the dword containing the element into the
9723 // same position within that half.
9724 for (int &M : HalfMask)
9725 if (M >= SourceOffset && M < SourceOffset + 4) {
9726 M = M - SourceOffset + DestOffset;
9727 assert(M >= 0 && "This should never wrap below zero!");
9732 // Ensure we have the input in a viable dword of its current half. This
9733 // is particularly tricky because the original position may be clobbered
9734 // by inputs being moved and *staying* in that half.
9735 if (IncomingInputs.size() == 1) {
9736 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9737 int InputFixed = std::find(std::begin(SourceHalfMask),
9738 std::end(SourceHalfMask), -1) -
9739 std::begin(SourceHalfMask) + SourceOffset;
9740 SourceHalfMask[InputFixed - SourceOffset] =
9741 IncomingInputs[0] - SourceOffset;
9742 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9744 IncomingInputs[0] = InputFixed;
9746 } else if (IncomingInputs.size() == 2) {
9747 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9748 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9749 // We have two non-adjacent or clobbered inputs we need to extract from
9750 // the source half. To do this, we need to map them into some adjacent
9751 // dword slot in the source mask.
9752 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9753 IncomingInputs[1] - SourceOffset};
9755 // If there is a free slot in the source half mask adjacent to one of
9756 // the inputs, place the other input in it. We use (Index XOR 1) to
9757 // compute an adjacent index.
9758 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9759 SourceHalfMask[InputsFixed[0] ^ 1] < 0) {
9760 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9761 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9762 InputsFixed[1] = InputsFixed[0] ^ 1;
9763 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9764 SourceHalfMask[InputsFixed[1] ^ 1] < 0) {
9765 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9766 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9767 InputsFixed[0] = InputsFixed[1] ^ 1;
9768 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] < 0 &&
9769 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] < 0) {
9770 // The two inputs are in the same DWord but it is clobbered and the
9771 // adjacent DWord isn't used at all. Move both inputs to the free
9773 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9774 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9775 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9776 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9778 // The only way we hit this point is if there is no clobbering
9779 // (because there are no off-half inputs to this half) and there is no
9780 // free slot adjacent to one of the inputs. In this case, we have to
9781 // swap an input with a non-input.
9782 for (int i = 0; i < 4; ++i)
9783 assert((SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) &&
9784 "We can't handle any clobbers here!");
9785 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9786 "Cannot have adjacent inputs here!");
9788 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9789 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9791 // We also have to update the final source mask in this case because
9792 // it may need to undo the above swap.
9793 for (int &M : FinalSourceHalfMask)
9794 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9795 M = InputsFixed[1] + SourceOffset;
9796 else if (M == InputsFixed[1] + SourceOffset)
9797 M = (InputsFixed[0] ^ 1) + SourceOffset;
9799 InputsFixed[1] = InputsFixed[0] ^ 1;
9802 // Point everything at the fixed inputs.
9803 for (int &M : HalfMask)
9804 if (M == IncomingInputs[0])
9805 M = InputsFixed[0] + SourceOffset;
9806 else if (M == IncomingInputs[1])
9807 M = InputsFixed[1] + SourceOffset;
9809 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9810 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9813 llvm_unreachable("Unhandled input size!");
9816 // Now hoist the DWord down to the right half.
9817 int FreeDWord = (PSHUFDMask[DestOffset / 2] < 0 ? 0 : 1) + DestOffset / 2;
9818 assert(PSHUFDMask[FreeDWord] < 0 && "DWord not free");
9819 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9820 for (int &M : HalfMask)
9821 for (int Input : IncomingInputs)
9823 M = FreeDWord * 2 + Input % 2;
9825 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9826 /*SourceOffset*/ 4, /*DestOffset*/ 0);
9827 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9828 /*SourceOffset*/ 0, /*DestOffset*/ 4);
9830 // Now enact all the shuffles we've computed to move the inputs into their
9832 if (!isNoopShuffleMask(PSHUFLMask))
9833 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9834 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9835 if (!isNoopShuffleMask(PSHUFHMask))
9836 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9837 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9838 if (!isNoopShuffleMask(PSHUFDMask))
9841 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9842 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9844 // At this point, each half should contain all its inputs, and we can then
9845 // just shuffle them into their final position.
9846 assert(count_if(LoMask, [](int M) { return M >= 4; }) == 0 &&
9847 "Failed to lift all the high half inputs to the low mask!");
9848 assert(count_if(HiMask, [](int M) { return M >= 0 && M < 4; }) == 0 &&
9849 "Failed to lift all the low half inputs to the high mask!");
9851 // Do a half shuffle for the low mask.
9852 if (!isNoopShuffleMask(LoMask))
9853 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9854 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9856 // Do a half shuffle with the high mask after shifting its values down.
9857 for (int &M : HiMask)
9860 if (!isNoopShuffleMask(HiMask))
9861 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9862 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9867 /// Helper to form a PSHUFB-based shuffle+blend, opportunistically avoiding the
9868 /// blend if only one input is used.
9869 static SDValue lowerVectorShuffleAsBlendOfPSHUFBs(
9870 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9871 SelectionDAG &DAG, bool &V1InUse, bool &V2InUse) {
9872 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9878 int Size = Mask.size();
9879 int Scale = 16 / Size;
9880 for (int i = 0; i < 16; ++i) {
9881 if (Mask[i / Scale] < 0) {
9882 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9884 const int ZeroMask = 0x80;
9885 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9887 int V2Idx = Mask[i / Scale] < Size
9889 : (Mask[i / Scale] - Size) * Scale + i % Scale;
9890 if (Zeroable[i / Scale])
9891 V1Idx = V2Idx = ZeroMask;
9892 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9893 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9894 V1InUse |= (ZeroMask != V1Idx);
9895 V2InUse |= (ZeroMask != V2Idx);
9900 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9901 DAG.getBitcast(MVT::v16i8, V1),
9902 DAG.getBuildVector(MVT::v16i8, DL, V1Mask));
9904 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9905 DAG.getBitcast(MVT::v16i8, V2),
9906 DAG.getBuildVector(MVT::v16i8, DL, V2Mask));
9908 // If we need shuffled inputs from both, blend the two.
9910 if (V1InUse && V2InUse)
9911 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9913 V = V1InUse ? V1 : V2;
9915 // Cast the result back to the correct type.
9916 return DAG.getBitcast(VT, V);
9919 /// \brief Generic lowering of 8-lane i16 shuffles.
9921 /// This handles both single-input shuffles and combined shuffle/blends with
9922 /// two inputs. The single input shuffles are immediately delegated to
9923 /// a dedicated lowering routine.
9925 /// The blends are lowered in one of three fundamental ways. If there are few
9926 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9927 /// of the input is significantly cheaper when lowered as an interleaving of
9928 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9929 /// halves of the inputs separately (making them have relatively few inputs)
9930 /// and then concatenate them.
9931 static SDValue lowerV8I16VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
9932 SDValue V1, SDValue V2,
9933 const X86Subtarget &Subtarget,
9934 SelectionDAG &DAG) {
9935 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9936 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9937 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9939 // Whenever we can lower this as a zext, that instruction is strictly faster
9940 // than any alternative.
9941 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9942 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9945 int NumV2Inputs = count_if(Mask, [](int M) { return M >= 8; });
9947 if (NumV2Inputs == 0) {
9948 // Check for being able to broadcast a single element.
9949 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(
9950 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9953 // Try to use shift instructions.
9954 if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask,
9958 // Use dedicated unpack instructions for masks that match their pattern.
9960 lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9963 // Try to use byte rotation instructions.
9964 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9965 Mask, Subtarget, DAG))
9968 // Make a copy of the mask so it can be modified.
9969 SmallVector<int, 8> MutableMask(Mask.begin(), Mask.end());
9970 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1,
9971 MutableMask, Subtarget,
9975 assert(llvm::any_of(Mask, [](int M) { return M >= 0 && M < 8; }) &&
9976 "All single-input shuffles should be canonicalized to be V1-input "
9979 // Try to use shift instructions.
9980 if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask,
9984 // See if we can use SSE4A Extraction / Insertion.
9985 if (Subtarget.hasSSE4A())
9986 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9989 // There are special ways we can lower some single-element blends.
9990 if (NumV2Inputs == 1)
9991 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9992 Mask, Subtarget, DAG))
9995 // We have different paths for blend lowering, but they all must use the
9996 // *exact* same predicate.
9997 bool IsBlendSupported = Subtarget.hasSSE41();
9998 if (IsBlendSupported)
9999 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
10003 if (SDValue Masked =
10004 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
10007 // Use dedicated unpack instructions for masks that match their pattern.
10009 lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
10012 // Try to use byte rotation instructions.
10013 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10014 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
10017 if (SDValue BitBlend =
10018 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
10021 // Try to lower by permuting the inputs into an unpack instruction.
10022 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
10026 // If we can't directly blend but can use PSHUFB, that will be better as it
10027 // can both shuffle and set up the inefficient blend.
10028 if (!IsBlendSupported && Subtarget.hasSSSE3()) {
10029 bool V1InUse, V2InUse;
10030 return lowerVectorShuffleAsBlendOfPSHUFBs(DL, MVT::v8i16, V1, V2, Mask, DAG,
10034 // We can always bit-blend if we have to so the fallback strategy is to
10035 // decompose into single-input permutes and blends.
10036 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
10040 /// \brief Check whether a compaction lowering can be done by dropping even
10041 /// elements and compute how many times even elements must be dropped.
10043 /// This handles shuffles which take every Nth element where N is a power of
10044 /// two. Example shuffle masks:
10046 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
10047 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
10048 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
10049 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
10050 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
10051 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
10053 /// Any of these lanes can of course be undef.
10055 /// This routine only supports N <= 3.
10056 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
10059 /// \returns N above, or the number of times even elements must be dropped if
10060 /// there is such a number. Otherwise returns zero.
10061 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask,
10062 bool IsSingleInput) {
10063 // The modulus for the shuffle vector entries is based on whether this is
10064 // a single input or not.
10065 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
10066 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
10067 "We should only be called with masks with a power-of-2 size!");
10069 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
10071 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
10072 // and 2^3 simultaneously. This is because we may have ambiguity with
10073 // partially undef inputs.
10074 bool ViableForN[3] = {true, true, true};
10076 for (int i = 0, e = Mask.size(); i < e; ++i) {
10077 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
10082 bool IsAnyViable = false;
10083 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
10084 if (ViableForN[j]) {
10085 uint64_t N = j + 1;
10087 // The shuffle mask must be equal to (i * 2^N) % M.
10088 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
10089 IsAnyViable = true;
10091 ViableForN[j] = false;
10093 // Early exit if we exhaust the possible powers of two.
10098 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
10102 // Return 0 as there is no viable power of two.
10106 /// \brief Generic lowering of v16i8 shuffles.
10108 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
10109 /// detect any complexity reducing interleaving. If that doesn't help, it uses
10110 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
10111 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
10113 static SDValue lowerV16I8VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
10114 SDValue V1, SDValue V2,
10115 const X86Subtarget &Subtarget,
10116 SelectionDAG &DAG) {
10117 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
10118 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
10119 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10121 // Try to use shift instructions.
10122 if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask,
10126 // Try to use byte rotation instructions.
10127 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10128 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
10131 // Try to use a zext lowering.
10132 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
10133 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
10136 // See if we can use SSE4A Extraction / Insertion.
10137 if (Subtarget.hasSSE4A())
10138 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
10141 int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
10143 // For single-input shuffles, there are some nicer lowering tricks we can use.
10144 if (NumV2Elements == 0) {
10145 // Check for being able to broadcast a single element.
10146 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(
10147 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
10150 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
10151 // Notably, this handles splat and partial-splat shuffles more efficiently.
10152 // However, it only makes sense if the pre-duplication shuffle simplifies
10153 // things significantly. Currently, this means we need to be able to
10154 // express the pre-duplication shuffle as an i16 shuffle.
10156 // FIXME: We should check for other patterns which can be widened into an
10157 // i16 shuffle as well.
10158 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
10159 for (int i = 0; i < 16; i += 2)
10160 if (Mask[i] >= 0 && Mask[i + 1] >= 0 && Mask[i] != Mask[i + 1])
10165 auto tryToWidenViaDuplication = [&]() -> SDValue {
10166 if (!canWidenViaDuplication(Mask))
10168 SmallVector<int, 4> LoInputs;
10169 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
10170 [](int M) { return M >= 0 && M < 8; });
10171 std::sort(LoInputs.begin(), LoInputs.end());
10172 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
10174 SmallVector<int, 4> HiInputs;
10175 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
10176 [](int M) { return M >= 8; });
10177 std::sort(HiInputs.begin(), HiInputs.end());
10178 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
10181 bool TargetLo = LoInputs.size() >= HiInputs.size();
10182 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
10183 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
10185 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
10186 SmallDenseMap<int, int, 8> LaneMap;
10187 for (int I : InPlaceInputs) {
10188 PreDupI16Shuffle[I/2] = I/2;
10191 int j = TargetLo ? 0 : 4, je = j + 4;
10192 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
10193 // Check if j is already a shuffle of this input. This happens when
10194 // there are two adjacent bytes after we move the low one.
10195 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
10196 // If we haven't yet mapped the input, search for a slot into which
10198 while (j < je && PreDupI16Shuffle[j] >= 0)
10202 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
10205 // Map this input with the i16 shuffle.
10206 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
10209 // Update the lane map based on the mapping we ended up with.
10210 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
10212 V1 = DAG.getBitcast(
10214 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
10215 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
10217 // Unpack the bytes to form the i16s that will be shuffled into place.
10218 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
10219 MVT::v16i8, V1, V1);
10221 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
10222 for (int i = 0; i < 16; ++i)
10223 if (Mask[i] >= 0) {
10224 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
10225 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
10226 if (PostDupI16Shuffle[i / 2] < 0)
10227 PostDupI16Shuffle[i / 2] = MappedMask;
10229 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
10230 "Conflicting entrties in the original shuffle!");
10232 return DAG.getBitcast(
10234 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
10235 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
10237 if (SDValue V = tryToWidenViaDuplication())
10241 if (SDValue Masked =
10242 lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
10245 // Use dedicated unpack instructions for masks that match their pattern.
10247 lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
10250 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
10251 // with PSHUFB. It is important to do this before we attempt to generate any
10252 // blends but after all of the single-input lowerings. If the single input
10253 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
10254 // want to preserve that and we can DAG combine any longer sequences into
10255 // a PSHUFB in the end. But once we start blending from multiple inputs,
10256 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
10257 // and there are *very* few patterns that would actually be faster than the
10258 // PSHUFB approach because of its ability to zero lanes.
10260 // FIXME: The only exceptions to the above are blends which are exact
10261 // interleavings with direct instructions supporting them. We currently don't
10262 // handle those well here.
10263 if (Subtarget.hasSSSE3()) {
10264 bool V1InUse = false;
10265 bool V2InUse = false;
10267 SDValue PSHUFB = lowerVectorShuffleAsBlendOfPSHUFBs(
10268 DL, MVT::v16i8, V1, V2, Mask, DAG, V1InUse, V2InUse);
10270 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
10271 // do so. This avoids using them to handle blends-with-zero which is
10272 // important as a single pshufb is significantly faster for that.
10273 if (V1InUse && V2InUse) {
10274 if (Subtarget.hasSSE41())
10275 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
10276 Mask, Subtarget, DAG))
10279 // We can use an unpack to do the blending rather than an or in some
10280 // cases. Even though the or may be (very minorly) more efficient, we
10281 // preference this lowering because there are common cases where part of
10282 // the complexity of the shuffles goes away when we do the final blend as
10284 // FIXME: It might be worth trying to detect if the unpack-feeding
10285 // shuffles will both be pshufb, in which case we shouldn't bother with
10287 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
10288 DL, MVT::v16i8, V1, V2, Mask, DAG))
10295 // There are special ways we can lower some single-element blends.
10296 if (NumV2Elements == 1)
10297 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
10298 Mask, Subtarget, DAG))
10301 if (SDValue BitBlend =
10302 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
10305 // Check whether a compaction lowering can be done. This handles shuffles
10306 // which take every Nth element for some even N. See the helper function for
10309 // We special case these as they can be particularly efficiently handled with
10310 // the PACKUSB instruction on x86 and they show up in common patterns of
10311 // rearranging bytes to truncate wide elements.
10312 bool IsSingleInput = V2.isUndef();
10313 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask, IsSingleInput)) {
10314 // NumEvenDrops is the power of two stride of the elements. Another way of
10315 // thinking about it is that we need to drop the even elements this many
10316 // times to get the original input.
10318 // First we need to zero all the dropped bytes.
10319 assert(NumEvenDrops <= 3 &&
10320 "No support for dropping even elements more than 3 times.");
10321 // We use the mask type to pick which bytes are preserved based on how many
10322 // elements are dropped.
10323 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
10324 SDValue ByteClearMask = DAG.getBitcast(
10325 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
10326 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
10327 if (!IsSingleInput)
10328 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
10330 // Now pack things back together.
10331 V1 = DAG.getBitcast(MVT::v8i16, V1);
10332 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
10333 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
10334 for (int i = 1; i < NumEvenDrops; ++i) {
10335 Result = DAG.getBitcast(MVT::v8i16, Result);
10336 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
10342 // Handle multi-input cases by blending single-input shuffles.
10343 if (NumV2Elements > 0)
10344 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
10347 // The fallback path for single-input shuffles widens this into two v8i16
10348 // vectors with unpacks, shuffles those, and then pulls them back together
10352 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
10353 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
10354 for (int i = 0; i < 16; ++i)
10356 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
10358 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
10360 SDValue VLoHalf, VHiHalf;
10361 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
10362 // them out and avoid using UNPCK{L,H} to extract the elements of V as
10364 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
10365 [](int M) { return M >= 0 && M % 2 == 1; }) &&
10366 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
10367 [](int M) { return M >= 0 && M % 2 == 1; })) {
10368 // Use a mask to drop the high bytes.
10369 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
10370 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
10371 DAG.getConstant(0x00FF, DL, MVT::v8i16));
10373 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
10374 VHiHalf = DAG.getUNDEF(MVT::v8i16);
10376 // Squash the masks to point directly into VLoHalf.
10377 for (int &M : LoBlendMask)
10380 for (int &M : HiBlendMask)
10384 // Otherwise just unpack the low half of V into VLoHalf and the high half into
10385 // VHiHalf so that we can blend them as i16s.
10386 VLoHalf = DAG.getBitcast(
10387 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
10388 VHiHalf = DAG.getBitcast(
10389 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
10392 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
10393 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
10395 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
10398 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
10400 /// This routine breaks down the specific type of 128-bit shuffle and
10401 /// dispatches to the lowering routines accordingly.
10402 static SDValue lower128BitVectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
10403 MVT VT, SDValue V1, SDValue V2,
10404 const X86Subtarget &Subtarget,
10405 SelectionDAG &DAG) {
10406 switch (VT.SimpleTy) {
10408 return lowerV2I64VectorShuffle(DL, Mask, V1, V2, Subtarget, DAG);
10410 return lowerV2F64VectorShuffle(DL, Mask, V1, V2, Subtarget, DAG);
10412 return lowerV4I32VectorShuffle(DL, Mask, V1, V2, Subtarget, DAG);
10414 return lowerV4F32VectorShuffle(DL, Mask, V1, V2, Subtarget, DAG);
10416 return lowerV8I16VectorShuffle(DL, Mask, V1, V2, Subtarget, DAG);
10418 return lowerV16I8VectorShuffle(DL, Mask, V1, V2, Subtarget, DAG);
10421 llvm_unreachable("Unimplemented!");
10425 /// \brief Helper function to test whether a shuffle mask could be
10426 /// simplified by widening the elements being shuffled.
10428 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
10429 /// leaves it in an unspecified state.
10431 /// NOTE: This must handle normal vector shuffle masks and *target* vector
10432 /// shuffle masks. The latter have the special property of a '-2' representing
10433 /// a zero-ed lane of a vector.
10434 static bool canWidenShuffleElements(ArrayRef<int> Mask,
10435 SmallVectorImpl<int> &WidenedMask) {
10436 WidenedMask.assign(Mask.size() / 2, 0);
10437 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
10438 // If both elements are undef, its trivial.
10439 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
10440 WidenedMask[i/2] = SM_SentinelUndef;
10444 // Check for an undef mask and a mask value properly aligned to fit with
10445 // a pair of values. If we find such a case, use the non-undef mask's value.
10446 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
10447 WidenedMask[i/2] = Mask[i + 1] / 2;
10450 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
10451 WidenedMask[i/2] = Mask[i] / 2;
10455 // When zeroing, we need to spread the zeroing across both lanes to widen.
10456 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
10457 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
10458 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
10459 WidenedMask[i/2] = SM_SentinelZero;
10465 // Finally check if the two mask values are adjacent and aligned with
10467 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
10468 WidenedMask[i/2] = Mask[i] / 2;
10472 // Otherwise we can't safely widen the elements used in this shuffle.
10475 assert(WidenedMask.size() == Mask.size() / 2 &&
10476 "Incorrect size of mask after widening the elements!");
10481 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
10483 /// This routine just extracts two subvectors, shuffles them independently, and
10484 /// then concatenates them back together. This should work effectively with all
10485 /// AVX vector shuffle types.
10486 static SDValue splitAndLowerVectorShuffle(const SDLoc &DL, MVT VT, SDValue V1,
10487 SDValue V2, ArrayRef<int> Mask,
10488 SelectionDAG &DAG) {
10489 assert(VT.getSizeInBits() >= 256 &&
10490 "Only for 256-bit or wider vector shuffles!");
10491 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
10492 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
10494 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
10495 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
10497 int NumElements = VT.getVectorNumElements();
10498 int SplitNumElements = NumElements / 2;
10499 MVT ScalarVT = VT.getVectorElementType();
10500 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
10502 // Rather than splitting build-vectors, just build two narrower build
10503 // vectors. This helps shuffling with splats and zeros.
10504 auto SplitVector = [&](SDValue V) {
10505 V = peekThroughBitcasts(V);
10507 MVT OrigVT = V.getSimpleValueType();
10508 int OrigNumElements = OrigVT.getVectorNumElements();
10509 int OrigSplitNumElements = OrigNumElements / 2;
10510 MVT OrigScalarVT = OrigVT.getVectorElementType();
10511 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
10515 auto *BV = dyn_cast<BuildVectorSDNode>(V);
10517 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10518 DAG.getIntPtrConstant(0, DL));
10519 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10520 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
10523 SmallVector<SDValue, 16> LoOps, HiOps;
10524 for (int i = 0; i < OrigSplitNumElements; ++i) {
10525 LoOps.push_back(BV->getOperand(i));
10526 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
10528 LoV = DAG.getBuildVector(OrigSplitVT, DL, LoOps);
10529 HiV = DAG.getBuildVector(OrigSplitVT, DL, HiOps);
10531 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
10532 DAG.getBitcast(SplitVT, HiV));
10535 SDValue LoV1, HiV1, LoV2, HiV2;
10536 std::tie(LoV1, HiV1) = SplitVector(V1);
10537 std::tie(LoV2, HiV2) = SplitVector(V2);
10539 // Now create two 4-way blends of these half-width vectors.
10540 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
10541 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
10542 SmallVector<int, 32> V1BlendMask((unsigned)SplitNumElements, -1);
10543 SmallVector<int, 32> V2BlendMask((unsigned)SplitNumElements, -1);
10544 SmallVector<int, 32> BlendMask((unsigned)SplitNumElements, -1);
10545 for (int i = 0; i < SplitNumElements; ++i) {
10546 int M = HalfMask[i];
10547 if (M >= NumElements) {
10548 if (M >= NumElements + SplitNumElements)
10552 V2BlendMask[i] = M - NumElements;
10553 BlendMask[i] = SplitNumElements + i;
10554 } else if (M >= 0) {
10555 if (M >= SplitNumElements)
10559 V1BlendMask[i] = M;
10564 // Because the lowering happens after all combining takes place, we need to
10565 // manually combine these blend masks as much as possible so that we create
10566 // a minimal number of high-level vector shuffle nodes.
10568 // First try just blending the halves of V1 or V2.
10569 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
10570 return DAG.getUNDEF(SplitVT);
10571 if (!UseLoV2 && !UseHiV2)
10572 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10573 if (!UseLoV1 && !UseHiV1)
10574 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10576 SDValue V1Blend, V2Blend;
10577 if (UseLoV1 && UseHiV1) {
10579 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10581 // We only use half of V1 so map the usage down into the final blend mask.
10582 V1Blend = UseLoV1 ? LoV1 : HiV1;
10583 for (int i = 0; i < SplitNumElements; ++i)
10584 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
10585 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
10587 if (UseLoV2 && UseHiV2) {
10589 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10591 // We only use half of V2 so map the usage down into the final blend mask.
10592 V2Blend = UseLoV2 ? LoV2 : HiV2;
10593 for (int i = 0; i < SplitNumElements; ++i)
10594 if (BlendMask[i] >= SplitNumElements)
10595 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
10597 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
10599 SDValue Lo = HalfBlend(LoMask);
10600 SDValue Hi = HalfBlend(HiMask);
10601 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
10604 /// \brief Either split a vector in halves or decompose the shuffles and the
10607 /// This is provided as a good fallback for many lowerings of non-single-input
10608 /// shuffles with more than one 128-bit lane. In those cases, we want to select
10609 /// between splitting the shuffle into 128-bit components and stitching those
10610 /// back together vs. extracting the single-input shuffles and blending those
10612 static SDValue lowerVectorShuffleAsSplitOrBlend(const SDLoc &DL, MVT VT,
10613 SDValue V1, SDValue V2,
10614 ArrayRef<int> Mask,
10615 SelectionDAG &DAG) {
10616 assert(!V2.isUndef() && "This routine must not be used to lower single-input "
10617 "shuffles as it could then recurse on itself.");
10618 int Size = Mask.size();
10620 // If this can be modeled as a broadcast of two elements followed by a blend,
10621 // prefer that lowering. This is especially important because broadcasts can
10622 // often fold with memory operands.
10623 auto DoBothBroadcast = [&] {
10624 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
10627 if (V2BroadcastIdx < 0)
10628 V2BroadcastIdx = M - Size;
10629 else if (M - Size != V2BroadcastIdx)
10631 } else if (M >= 0) {
10632 if (V1BroadcastIdx < 0)
10633 V1BroadcastIdx = M;
10634 else if (M != V1BroadcastIdx)
10639 if (DoBothBroadcast())
10640 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
10643 // If the inputs all stem from a single 128-bit lane of each input, then we
10644 // split them rather than blending because the split will decompose to
10645 // unusually few instructions.
10646 int LaneCount = VT.getSizeInBits() / 128;
10647 int LaneSize = Size / LaneCount;
10648 SmallBitVector LaneInputs[2];
10649 LaneInputs[0].resize(LaneCount, false);
10650 LaneInputs[1].resize(LaneCount, false);
10651 for (int i = 0; i < Size; ++i)
10653 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
10654 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
10655 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10657 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
10658 // that the decomposed single-input shuffles don't end up here.
10659 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10662 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
10663 /// a permutation and blend of those lanes.
10665 /// This essentially blends the out-of-lane inputs to each lane into the lane
10666 /// from a permuted copy of the vector. This lowering strategy results in four
10667 /// instructions in the worst case for a single-input cross lane shuffle which
10668 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
10669 /// of. Special cases for each particular shuffle pattern should be handled
10670 /// prior to trying this lowering.
10671 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(const SDLoc &DL, MVT VT,
10672 SDValue V1, SDValue V2,
10673 ArrayRef<int> Mask,
10674 SelectionDAG &DAG) {
10675 // FIXME: This should probably be generalized for 512-bit vectors as well.
10676 assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
10677 int Size = Mask.size();
10678 int LaneSize = Size / 2;
10680 // If there are only inputs from one 128-bit lane, splitting will in fact be
10681 // less expensive. The flags track whether the given lane contains an element
10682 // that crosses to another lane.
10683 bool LaneCrossing[2] = {false, false};
10684 for (int i = 0; i < Size; ++i)
10685 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10686 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
10687 if (!LaneCrossing[0] || !LaneCrossing[1])
10688 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10690 assert(V2.isUndef() &&
10691 "This last part of this routine only works on single input shuffles");
10693 SmallVector<int, 32> FlippedBlendMask(Size);
10694 for (int i = 0; i < Size; ++i)
10695 FlippedBlendMask[i] =
10696 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
10698 : Mask[i] % LaneSize +
10699 (i / LaneSize) * LaneSize + Size);
10701 // Flip the vector, and blend the results which should now be in-lane. The
10702 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
10703 // 5 for the high source. The value 3 selects the high half of source 2 and
10704 // the value 2 selects the low half of source 2. We only use source 2 to
10705 // allow folding it into a memory operand.
10706 unsigned PERMMask = 3 | 2 << 4;
10707 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
10708 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
10709 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
10712 /// \brief Handle lowering 2-lane 128-bit shuffles.
10713 static SDValue lowerV2X128VectorShuffle(const SDLoc &DL, MVT VT, SDValue V1,
10714 SDValue V2, ArrayRef<int> Mask,
10715 const X86Subtarget &Subtarget,
10716 SelectionDAG &DAG) {
10717 // TODO: If minimizing size and one of the inputs is a zero vector and the
10718 // the zero vector has only one use, we could use a VPERM2X128 to save the
10719 // instruction bytes needed to explicitly generate the zero vector.
10721 // Blends are faster and handle all the non-lane-crossing cases.
10722 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10726 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10727 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10729 // If either input operand is a zero vector, use VPERM2X128 because its mask
10730 // allows us to replace the zero input with an implicit zero.
10731 if (!IsV1Zero && !IsV2Zero) {
10732 // Check for patterns which can be matched with a single insert of a 128-bit
10734 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10735 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10736 // With AVX2 we should use VPERMQ/VPERMPD to allow memory folding.
10737 if (Subtarget.hasAVX2() && V2.isUndef())
10740 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10741 VT.getVectorNumElements() / 2);
10742 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10743 DAG.getIntPtrConstant(0, DL));
10744 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10745 OnlyUsesV1 ? V1 : V2,
10746 DAG.getIntPtrConstant(0, DL));
10747 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10751 // Otherwise form a 128-bit permutation. After accounting for undefs,
10752 // convert the 64-bit shuffle mask selection values into 128-bit
10753 // selection bits by dividing the indexes by 2 and shifting into positions
10754 // defined by a vperm2*128 instruction's immediate control byte.
10756 // The immediate permute control byte looks like this:
10757 // [1:0] - select 128 bits from sources for low half of destination
10759 // [3] - zero low half of destination
10760 // [5:4] - select 128 bits from sources for high half of destination
10762 // [7] - zero high half of destination
10764 int MaskLO = Mask[0];
10765 if (MaskLO == SM_SentinelUndef)
10766 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10768 int MaskHI = Mask[2];
10769 if (MaskHI == SM_SentinelUndef)
10770 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10772 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10774 // If either input is a zero vector, replace it with an undef input.
10775 // Shuffle mask values < 4 are selecting elements of V1.
10776 // Shuffle mask values >= 4 are selecting elements of V2.
10777 // Adjust each half of the permute mask by clearing the half that was
10778 // selecting the zero vector and setting the zero mask bit.
10780 V1 = DAG.getUNDEF(VT);
10782 PermMask = (PermMask & 0xf0) | 0x08;
10784 PermMask = (PermMask & 0x0f) | 0x80;
10787 V2 = DAG.getUNDEF(VT);
10789 PermMask = (PermMask & 0xf0) | 0x08;
10791 PermMask = (PermMask & 0x0f) | 0x80;
10794 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10795 DAG.getConstant(PermMask, DL, MVT::i8));
10798 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10799 /// shuffling each lane.
10801 /// This will only succeed when the result of fixing the 128-bit lanes results
10802 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10803 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10804 /// the lane crosses early and then use simpler shuffles within each lane.
10806 /// FIXME: It might be worthwhile at some point to support this without
10807 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10808 /// in x86 only floating point has interesting non-repeating shuffles, and even
10809 /// those are still *marginally* more expensive.
10810 static SDValue lowerVectorShuffleByMerging128BitLanes(
10811 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10812 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
10813 assert(!V2.isUndef() && "This is only useful with multiple inputs.");
10815 int Size = Mask.size();
10816 int LaneSize = 128 / VT.getScalarSizeInBits();
10817 int NumLanes = Size / LaneSize;
10818 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10820 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10821 // check whether the in-128-bit lane shuffles share a repeating pattern.
10822 SmallVector<int, 4> Lanes((unsigned)NumLanes, -1);
10823 SmallVector<int, 4> InLaneMask((unsigned)LaneSize, -1);
10824 for (int i = 0; i < Size; ++i) {
10828 int j = i / LaneSize;
10830 if (Lanes[j] < 0) {
10831 // First entry we've seen for this lane.
10832 Lanes[j] = Mask[i] / LaneSize;
10833 } else if (Lanes[j] != Mask[i] / LaneSize) {
10834 // This doesn't match the lane selected previously!
10838 // Check that within each lane we have a consistent shuffle mask.
10839 int k = i % LaneSize;
10840 if (InLaneMask[k] < 0) {
10841 InLaneMask[k] = Mask[i] % LaneSize;
10842 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10843 // This doesn't fit a repeating in-lane mask.
10848 // First shuffle the lanes into place.
10849 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10850 VT.getSizeInBits() / 64);
10851 SmallVector<int, 8> LaneMask((unsigned)NumLanes * 2, -1);
10852 for (int i = 0; i < NumLanes; ++i)
10853 if (Lanes[i] >= 0) {
10854 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10855 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10858 V1 = DAG.getBitcast(LaneVT, V1);
10859 V2 = DAG.getBitcast(LaneVT, V2);
10860 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10862 // Cast it back to the type we actually want.
10863 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10865 // Now do a simple shuffle that isn't lane crossing.
10866 SmallVector<int, 8> NewMask((unsigned)Size, -1);
10867 for (int i = 0; i < Size; ++i)
10869 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10870 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10871 "Must not introduce lane crosses at this point!");
10873 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10876 /// Lower shuffles where an entire half of a 256-bit vector is UNDEF.
10877 /// This allows for fast cases such as subvector extraction/insertion
10878 /// or shuffling smaller vector types which can lower more efficiently.
10879 static SDValue lowerVectorShuffleWithUndefHalf(const SDLoc &DL, MVT VT,
10880 SDValue V1, SDValue V2,
10881 ArrayRef<int> Mask,
10882 const X86Subtarget &Subtarget,
10883 SelectionDAG &DAG) {
10884 assert(VT.is256BitVector() && "Expected 256-bit vector");
10886 unsigned NumElts = VT.getVectorNumElements();
10887 unsigned HalfNumElts = NumElts / 2;
10888 MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(), HalfNumElts);
10890 bool UndefLower = isUndefInRange(Mask, 0, HalfNumElts);
10891 bool UndefUpper = isUndefInRange(Mask, HalfNumElts, HalfNumElts);
10892 if (!UndefLower && !UndefUpper)
10895 // Upper half is undef and lower half is whole upper subvector.
10896 // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
10898 isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
10899 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10900 DAG.getIntPtrConstant(HalfNumElts, DL));
10901 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10902 DAG.getIntPtrConstant(0, DL));
10905 // Lower half is undef and upper half is whole lower subvector.
10906 // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
10908 isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
10909 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10910 DAG.getIntPtrConstant(0, DL));
10911 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10912 DAG.getIntPtrConstant(HalfNumElts, DL));
10915 // If the shuffle only uses two of the four halves of the input operands,
10916 // then extract them and perform the 'half' shuffle at half width.
10917 // e.g. vector_shuffle <X, X, X, X, u, u, u, u> or <X, X, u, u>
10918 int HalfIdx1 = -1, HalfIdx2 = -1;
10919 SmallVector<int, 8> HalfMask(HalfNumElts);
10920 unsigned Offset = UndefLower ? HalfNumElts : 0;
10921 for (unsigned i = 0; i != HalfNumElts; ++i) {
10922 int M = Mask[i + Offset];
10928 // Determine which of the 4 half vectors this element is from.
10929 // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
10930 int HalfIdx = M / HalfNumElts;
10932 // Determine the element index into its half vector source.
10933 int HalfElt = M % HalfNumElts;
10935 // We can shuffle with up to 2 half vectors, set the new 'half'
10936 // shuffle mask accordingly.
10937 if (HalfIdx1 < 0 || HalfIdx1 == HalfIdx) {
10938 HalfMask[i] = HalfElt;
10939 HalfIdx1 = HalfIdx;
10942 if (HalfIdx2 < 0 || HalfIdx2 == HalfIdx) {
10943 HalfMask[i] = HalfElt + HalfNumElts;
10944 HalfIdx2 = HalfIdx;
10948 // Too many half vectors referenced.
10951 assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
10953 // Only shuffle the halves of the inputs when useful.
10954 int NumLowerHalves =
10955 (HalfIdx1 == 0 || HalfIdx1 == 2) + (HalfIdx2 == 0 || HalfIdx2 == 2);
10956 int NumUpperHalves =
10957 (HalfIdx1 == 1 || HalfIdx1 == 3) + (HalfIdx2 == 1 || HalfIdx2 == 3);
10959 // uuuuXXXX - don't extract uppers just to insert again.
10960 if (UndefLower && NumUpperHalves != 0)
10963 // XXXXuuuu - don't extract both uppers, instead shuffle and then extract.
10964 if (UndefUpper && NumUpperHalves == 2)
10967 // AVX2 - XXXXuuuu - always extract lowers.
10968 if (Subtarget.hasAVX2() && !(UndefUpper && NumUpperHalves == 0)) {
10969 // AVX2 supports efficient immediate 64-bit element cross-lane shuffles.
10970 if (VT == MVT::v4f64 || VT == MVT::v4i64)
10972 // AVX2 supports variable 32-bit element cross-lane shuffles.
10973 if (VT == MVT::v8f32 || VT == MVT::v8i32) {
10974 // XXXXuuuu - don't extract lowers and uppers.
10975 if (UndefUpper && NumLowerHalves != 0 && NumUpperHalves != 0)
10980 auto GetHalfVector = [&](int HalfIdx) {
10982 return DAG.getUNDEF(HalfVT);
10983 SDValue V = (HalfIdx < 2 ? V1 : V2);
10984 HalfIdx = (HalfIdx % 2) * HalfNumElts;
10985 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
10986 DAG.getIntPtrConstant(HalfIdx, DL));
10989 SDValue Half1 = GetHalfVector(HalfIdx1);
10990 SDValue Half2 = GetHalfVector(HalfIdx2);
10991 SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
10992 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
10993 DAG.getIntPtrConstant(Offset, DL));
10996 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10999 /// This returns true if the elements from a particular input are already in the
11000 /// slot required by the given mask and require no permutation.
11001 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
11002 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
11003 int Size = Mask.size();
11004 for (int i = 0; i < Size; ++i)
11005 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
11011 /// Handle case where shuffle sources are coming from the same 128-bit lane and
11012 /// every lane can be represented as the same repeating mask - allowing us to
11013 /// shuffle the sources with the repeating shuffle and then permute the result
11014 /// to the destination lanes.
11015 static SDValue lowerShuffleAsRepeatedMaskAndLanePermute(
11016 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11017 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
11018 int NumElts = VT.getVectorNumElements();
11019 int NumLanes = VT.getSizeInBits() / 128;
11020 int NumLaneElts = NumElts / NumLanes;
11022 // On AVX2 we may be able to just shuffle the lowest elements and then
11023 // broadcast the result.
11024 if (Subtarget.hasAVX2()) {
11025 for (unsigned BroadcastSize : {16, 32, 64}) {
11026 if (BroadcastSize <= VT.getScalarSizeInBits())
11028 int NumBroadcastElts = BroadcastSize / VT.getScalarSizeInBits();
11030 // Attempt to match a repeating pattern every NumBroadcastElts,
11031 // accounting for UNDEFs but only references the lowest 128-bit
11032 // lane of the inputs.
11033 auto FindRepeatingBroadcastMask = [&](SmallVectorImpl<int> &RepeatMask) {
11034 for (int i = 0; i != NumElts; i += NumBroadcastElts)
11035 for (int j = 0; j != NumBroadcastElts; ++j) {
11036 int M = Mask[i + j];
11039 int &R = RepeatMask[j];
11040 if (0 != ((M % NumElts) / NumLaneElts))
11042 if (0 <= R && R != M)
11049 SmallVector<int, 8> RepeatMask((unsigned)NumElts, -1);
11050 if (!FindRepeatingBroadcastMask(RepeatMask))
11053 // Shuffle the (lowest) repeated elements in place for broadcast.
11054 SDValue RepeatShuf = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatMask);
11056 // Shuffle the actual broadcast.
11057 SmallVector<int, 8> BroadcastMask((unsigned)NumElts, -1);
11058 for (int i = 0; i != NumElts; i += NumBroadcastElts)
11059 for (int j = 0; j != NumBroadcastElts; ++j)
11060 BroadcastMask[i + j] = j;
11061 return DAG.getVectorShuffle(VT, DL, RepeatShuf, DAG.getUNDEF(VT),
11066 // Bail if the shuffle mask doesn't cross 128-bit lanes.
11067 if (!is128BitLaneCrossingShuffleMask(VT, Mask))
11070 // Bail if we already have a repeated lane shuffle mask.
11071 SmallVector<int, 8> RepeatedShuffleMask;
11072 if (is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedShuffleMask))
11075 // On AVX2 targets we can permute 256-bit vectors as 64-bit sub-lanes
11076 // (with PERMQ/PERMPD), otherwise we can only permute whole 128-bit lanes.
11077 int SubLaneScale = Subtarget.hasAVX2() && VT.is256BitVector() ? 2 : 1;
11078 int NumSubLanes = NumLanes * SubLaneScale;
11079 int NumSubLaneElts = NumLaneElts / SubLaneScale;
11081 // Check that all the sources are coming from the same lane and see if we can
11082 // form a repeating shuffle mask (local to each sub-lane). At the same time,
11083 // determine the source sub-lane for each destination sub-lane.
11084 int TopSrcSubLane = -1;
11085 SmallVector<int, 8> Dst2SrcSubLanes((unsigned)NumSubLanes, -1);
11086 SmallVector<int, 8> RepeatedSubLaneMasks[2] = {
11087 SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef),
11088 SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef)};
11090 for (int DstSubLane = 0; DstSubLane != NumSubLanes; ++DstSubLane) {
11091 // Extract the sub-lane mask, check that it all comes from the same lane
11092 // and normalize the mask entries to come from the first lane.
11094 SmallVector<int, 8> SubLaneMask((unsigned)NumSubLaneElts, -1);
11095 for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
11096 int M = Mask[(DstSubLane * NumSubLaneElts) + Elt];
11099 int Lane = (M % NumElts) / NumLaneElts;
11100 if ((0 <= SrcLane) && (SrcLane != Lane))
11103 int LocalM = (M % NumLaneElts) + (M < NumElts ? 0 : NumElts);
11104 SubLaneMask[Elt] = LocalM;
11107 // Whole sub-lane is UNDEF.
11111 // Attempt to match against the candidate repeated sub-lane masks.
11112 for (int SubLane = 0; SubLane != SubLaneScale; ++SubLane) {
11113 auto MatchMasks = [NumSubLaneElts](ArrayRef<int> M1, ArrayRef<int> M2) {
11114 for (int i = 0; i != NumSubLaneElts; ++i) {
11115 if (M1[i] < 0 || M2[i] < 0)
11117 if (M1[i] != M2[i])
11123 auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane];
11124 if (!MatchMasks(SubLaneMask, RepeatedSubLaneMask))
11127 // Merge the sub-lane mask into the matching repeated sub-lane mask.
11128 for (int i = 0; i != NumSubLaneElts; ++i) {
11129 int M = SubLaneMask[i];
11132 assert((RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] == M) &&
11133 "Unexpected mask element");
11134 RepeatedSubLaneMask[i] = M;
11137 // Track the top most source sub-lane - by setting the remaining to UNDEF
11138 // we can greatly simplify shuffle matching.
11139 int SrcSubLane = (SrcLane * SubLaneScale) + SubLane;
11140 TopSrcSubLane = std::max(TopSrcSubLane, SrcSubLane);
11141 Dst2SrcSubLanes[DstSubLane] = SrcSubLane;
11145 // Bail if we failed to find a matching repeated sub-lane mask.
11146 if (Dst2SrcSubLanes[DstSubLane] < 0)
11149 assert(0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes &&
11150 "Unexpected source lane");
11152 // Create a repeating shuffle mask for the entire vector.
11153 SmallVector<int, 8> RepeatedMask((unsigned)NumElts, -1);
11154 for (int SubLane = 0; SubLane <= TopSrcSubLane; ++SubLane) {
11155 int Lane = SubLane / SubLaneScale;
11156 auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane % SubLaneScale];
11157 for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
11158 int M = RepeatedSubLaneMask[Elt];
11161 int Idx = (SubLane * NumSubLaneElts) + Elt;
11162 RepeatedMask[Idx] = M + (Lane * NumLaneElts);
11165 SDValue RepeatedShuffle = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatedMask);
11167 // Shuffle each source sub-lane to its destination.
11168 SmallVector<int, 8> SubLaneMask((unsigned)NumElts, -1);
11169 for (int i = 0; i != NumElts; i += NumSubLaneElts) {
11170 int SrcSubLane = Dst2SrcSubLanes[i / NumSubLaneElts];
11171 if (SrcSubLane < 0)
11173 for (int j = 0; j != NumSubLaneElts; ++j)
11174 SubLaneMask[i + j] = j + (SrcSubLane * NumSubLaneElts);
11177 return DAG.getVectorShuffle(VT, DL, RepeatedShuffle, DAG.getUNDEF(VT),
11181 static SDValue lowerVectorShuffleWithSHUFPD(const SDLoc &DL, MVT VT,
11182 ArrayRef<int> Mask, SDValue V1,
11183 SDValue V2, SelectionDAG &DAG) {
11185 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
11186 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
11187 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
11188 int NumElts = VT.getVectorNumElements();
11189 bool ShufpdMask = true;
11190 bool CommutableMask = true;
11191 unsigned Immediate = 0;
11192 for (int i = 0; i < NumElts; ++i) {
11195 int Val = (i & 6) + NumElts * (i & 1);
11196 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
11197 if (Mask[i] < Val || Mask[i] > Val + 1)
11198 ShufpdMask = false;
11199 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
11200 CommutableMask = false;
11201 Immediate |= (Mask[i] % 2) << i;
11204 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
11205 DAG.getConstant(Immediate, DL, MVT::i8));
11206 if (CommutableMask)
11207 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
11208 DAG.getConstant(Immediate, DL, MVT::i8));
11212 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
11214 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
11215 /// isn't available.
11216 static SDValue lowerV4F64VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
11217 SDValue V1, SDValue V2,
11218 const X86Subtarget &Subtarget,
11219 SelectionDAG &DAG) {
11220 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
11221 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
11222 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
11224 SmallVector<int, 4> WidenedMask;
11225 if (canWidenShuffleElements(Mask, WidenedMask))
11226 if (SDValue V = lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask,
11230 if (V2.isUndef()) {
11231 // Check for being able to broadcast a single element.
11232 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(
11233 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
11236 // Use low duplicate instructions for masks that match their pattern.
11237 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
11238 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
11240 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
11241 // Non-half-crossing single input shuffles can be lowered with an
11242 // interleaved permutation.
11243 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
11244 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
11245 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
11246 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
11249 // With AVX2 we have direct support for this permutation.
11250 if (Subtarget.hasAVX2())
11251 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
11252 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
11254 // Try to create an in-lane repeating shuffle mask and then shuffle the
11255 // the results into the target lanes.
11256 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
11257 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
11260 // Otherwise, fall back.
11261 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
11265 // Use dedicated unpack instructions for masks that match their pattern.
11267 lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
11270 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
11274 // Check if the blend happens to exactly fit that of SHUFPD.
11276 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
11279 // Try to create an in-lane repeating shuffle mask and then shuffle the
11280 // the results into the target lanes.
11281 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
11282 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
11285 // Try to simplify this by merging 128-bit lanes to enable a lane-based
11286 // shuffle. However, if we have AVX2 and either inputs are already in place,
11287 // we will be able to shuffle even across lanes the other input in a single
11288 // instruction so skip this pattern.
11289 if (!(Subtarget.hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
11290 isShuffleMaskInputInPlace(1, Mask))))
11291 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
11292 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
11295 // If we have AVX2 then we always want to lower with a blend because an v4 we
11296 // can fully permute the elements.
11297 if (Subtarget.hasAVX2())
11298 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
11301 // Otherwise fall back on generic lowering.
11302 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
11305 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
11307 /// This routine is only called when we have AVX2 and thus a reasonable
11308 /// instruction set for v4i64 shuffling..
11309 static SDValue lowerV4I64VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
11310 SDValue V1, SDValue V2,
11311 const X86Subtarget &Subtarget,
11312 SelectionDAG &DAG) {
11313 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
11314 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
11315 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
11316 assert(Subtarget.hasAVX2() && "We can only lower v4i64 with AVX2!");
11318 SmallVector<int, 4> WidenedMask;
11319 if (canWidenShuffleElements(Mask, WidenedMask))
11320 if (SDValue V = lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask,
11324 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
11328 // Check for being able to broadcast a single element.
11329 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1, V2,
11330 Mask, Subtarget, DAG))
11333 if (V2.isUndef()) {
11334 // When the shuffle is mirrored between the 128-bit lanes of the unit, we
11335 // can use lower latency instructions that will operate on both lanes.
11336 SmallVector<int, 2> RepeatedMask;
11337 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
11338 SmallVector<int, 4> PSHUFDMask;
11339 scaleShuffleMask(2, RepeatedMask, PSHUFDMask);
11340 return DAG.getBitcast(
11342 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
11343 DAG.getBitcast(MVT::v8i32, V1),
11344 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
11347 // AVX2 provides a direct instruction for permuting a single input across
11349 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
11350 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
11353 // Try to use shift instructions.
11354 if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask,
11358 // Use dedicated unpack instructions for masks that match their pattern.
11360 lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
11363 // Try to simplify this by merging 128-bit lanes to enable a lane-based
11364 // shuffle. However, if we have AVX2 and either inputs are already in place,
11365 // we will be able to shuffle even across lanes the other input in a single
11366 // instruction so skip this pattern.
11367 if (!(Subtarget.hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
11368 isShuffleMaskInputInPlace(1, Mask))))
11369 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
11370 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
11373 // Otherwise fall back on generic blend lowering.
11374 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
11378 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
11380 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
11381 /// isn't available.
11382 static SDValue lowerV8F32VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
11383 SDValue V1, SDValue V2,
11384 const X86Subtarget &Subtarget,
11385 SelectionDAG &DAG) {
11386 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
11387 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
11388 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11390 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
11394 // Check for being able to broadcast a single element.
11395 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1, V2,
11396 Mask, Subtarget, DAG))
11399 // If the shuffle mask is repeated in each 128-bit lane, we have many more
11400 // options to efficiently lower the shuffle.
11401 SmallVector<int, 4> RepeatedMask;
11402 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
11403 assert(RepeatedMask.size() == 4 &&
11404 "Repeated masks must be half the mask width!");
11406 // Use even/odd duplicate instructions for masks that match their pattern.
11407 if (isShuffleEquivalent(V1, V2, RepeatedMask, {0, 0, 2, 2}))
11408 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
11409 if (isShuffleEquivalent(V1, V2, RepeatedMask, {1, 1, 3, 3}))
11410 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
11413 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
11414 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
11416 // Use dedicated unpack instructions for masks that match their pattern.
11418 lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
11421 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
11422 // have already handled any direct blends.
11423 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
11426 // Try to create an in-lane repeating shuffle mask and then shuffle the
11427 // the results into the target lanes.
11428 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
11429 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
11432 // If we have a single input shuffle with different shuffle patterns in the
11433 // two 128-bit lanes use the variable mask to VPERMILPS.
11434 if (V2.isUndef()) {
11435 SDValue VPermMask[8];
11436 for (int i = 0; i < 8; ++i)
11437 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
11438 : DAG.getConstant(Mask[i], DL, MVT::i32);
11439 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
11440 return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
11441 DAG.getBuildVector(MVT::v8i32, DL, VPermMask));
11443 if (Subtarget.hasAVX2())
11444 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32,
11445 DAG.getBuildVector(MVT::v8i32, DL, VPermMask), V1);
11447 // Otherwise, fall back.
11448 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
11452 // Try to simplify this by merging 128-bit lanes to enable a lane-based
11454 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
11455 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
11458 // If we have AVX2 then we always want to lower with a blend because at v8 we
11459 // can fully permute the elements.
11460 if (Subtarget.hasAVX2())
11461 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
11464 // Otherwise fall back on generic lowering.
11465 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
11468 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
11470 /// This routine is only called when we have AVX2 and thus a reasonable
11471 /// instruction set for v8i32 shuffling..
11472 static SDValue lowerV8I32VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
11473 SDValue V1, SDValue V2,
11474 const X86Subtarget &Subtarget,
11475 SelectionDAG &DAG) {
11476 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
11477 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
11478 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11479 assert(Subtarget.hasAVX2() && "We can only lower v8i32 with AVX2!");
11481 // Whenever we can lower this as a zext, that instruction is strictly faster
11482 // than any alternative. It also allows us to fold memory operands into the
11483 // shuffle in many cases.
11484 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
11485 Mask, Subtarget, DAG))
11488 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
11492 // Check for being able to broadcast a single element.
11493 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1, V2,
11494 Mask, Subtarget, DAG))
11497 // If the shuffle mask is repeated in each 128-bit lane we can use more
11498 // efficient instructions that mirror the shuffles across the two 128-bit
11500 SmallVector<int, 4> RepeatedMask;
11501 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
11502 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
11504 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
11505 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
11507 // Use dedicated unpack instructions for masks that match their pattern.
11509 lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
11513 // Try to use shift instructions.
11514 if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask,
11518 // Try to use byte rotation instructions.
11519 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
11520 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
11523 // Try to create an in-lane repeating shuffle mask and then shuffle the
11524 // the results into the target lanes.
11525 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
11526 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
11529 // If the shuffle patterns aren't repeated but it is a single input, directly
11530 // generate a cross-lane VPERMD instruction.
11531 if (V2.isUndef()) {
11532 SDValue VPermMask[8];
11533 for (int i = 0; i < 8; ++i)
11534 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
11535 : DAG.getConstant(Mask[i], DL, MVT::i32);
11536 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8i32,
11537 DAG.getBuildVector(MVT::v8i32, DL, VPermMask), V1);
11540 // Try to simplify this by merging 128-bit lanes to enable a lane-based
11542 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
11543 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
11546 // Otherwise fall back on generic blend lowering.
11547 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
11551 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
11553 /// This routine is only called when we have AVX2 and thus a reasonable
11554 /// instruction set for v16i16 shuffling..
11555 static SDValue lowerV16I16VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
11556 SDValue V1, SDValue V2,
11557 const X86Subtarget &Subtarget,
11558 SelectionDAG &DAG) {
11559 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
11560 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
11561 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11562 assert(Subtarget.hasAVX2() && "We can only lower v16i16 with AVX2!");
11564 // Whenever we can lower this as a zext, that instruction is strictly faster
11565 // than any alternative. It also allows us to fold memory operands into the
11566 // shuffle in many cases.
11567 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
11568 Mask, Subtarget, DAG))
11571 // Check for being able to broadcast a single element.
11572 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1, V2,
11573 Mask, Subtarget, DAG))
11576 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
11580 // Use dedicated unpack instructions for masks that match their pattern.
11582 lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
11585 // Try to use shift instructions.
11586 if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask,
11590 // Try to use byte rotation instructions.
11591 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
11592 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
11595 // Try to create an in-lane repeating shuffle mask and then shuffle the
11596 // the results into the target lanes.
11597 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
11598 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
11601 if (V2.isUndef()) {
11602 // There are no generalized cross-lane shuffle operations available on i16
11604 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
11605 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
11608 SmallVector<int, 8> RepeatedMask;
11609 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
11610 // As this is a single-input shuffle, the repeated mask should be
11611 // a strictly valid v8i16 mask that we can pass through to the v8i16
11612 // lowering to handle even the v16 case.
11613 return lowerV8I16GeneralSingleInputVectorShuffle(
11614 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
11618 if (SDValue PSHUFB = lowerVectorShuffleWithPSHUFB(DL, MVT::v16i16, Mask, V1,
11619 V2, Subtarget, DAG))
11622 // Try to simplify this by merging 128-bit lanes to enable a lane-based
11624 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
11625 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
11628 // Otherwise fall back on generic lowering.
11629 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
11632 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
11634 /// This routine is only called when we have AVX2 and thus a reasonable
11635 /// instruction set for v32i8 shuffling..
11636 static SDValue lowerV32I8VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
11637 SDValue V1, SDValue V2,
11638 const X86Subtarget &Subtarget,
11639 SelectionDAG &DAG) {
11640 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
11641 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
11642 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11643 assert(Subtarget.hasAVX2() && "We can only lower v32i8 with AVX2!");
11645 // Whenever we can lower this as a zext, that instruction is strictly faster
11646 // than any alternative. It also allows us to fold memory operands into the
11647 // shuffle in many cases.
11648 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
11649 Mask, Subtarget, DAG))
11652 // Check for being able to broadcast a single element.
11653 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1, V2,
11654 Mask, Subtarget, DAG))
11657 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
11661 // Use dedicated unpack instructions for masks that match their pattern.
11663 lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
11666 // Try to use shift instructions.
11667 if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask,
11671 // Try to use byte rotation instructions.
11672 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
11673 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11676 // Try to create an in-lane repeating shuffle mask and then shuffle the
11677 // the results into the target lanes.
11678 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
11679 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11682 // There are no generalized cross-lane shuffle operations available on i8
11684 if (V2.isUndef() && is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
11685 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2, Mask,
11688 if (SDValue PSHUFB = lowerVectorShuffleWithPSHUFB(DL, MVT::v32i8, Mask, V1,
11689 V2, Subtarget, DAG))
11692 // Try to simplify this by merging 128-bit lanes to enable a lane-based
11694 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
11695 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11698 // Otherwise fall back on generic lowering.
11699 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
11702 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
11704 /// This routine either breaks down the specific type of a 256-bit x86 vector
11705 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
11706 /// together based on the available instructions.
11707 static SDValue lower256BitVectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
11708 MVT VT, SDValue V1, SDValue V2,
11709 const X86Subtarget &Subtarget,
11710 SelectionDAG &DAG) {
11711 // If we have a single input to the zero element, insert that into V1 if we
11712 // can do so cheaply.
11713 int NumElts = VT.getVectorNumElements();
11714 int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
11716 if (NumV2Elements == 1 && Mask[0] >= NumElts)
11717 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
11718 DL, VT, V1, V2, Mask, Subtarget, DAG))
11721 // Handle special cases where the lower or upper half is UNDEF.
11723 lowerVectorShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
11726 // There is a really nice hard cut-over between AVX1 and AVX2 that means we
11727 // can check for those subtargets here and avoid much of the subtarget
11728 // querying in the per-vector-type lowering routines. With AVX1 we have
11729 // essentially *zero* ability to manipulate a 256-bit vector with integer
11730 // types. Since we'll use floating point types there eventually, just
11731 // immediately cast everything to a float and operate entirely in that domain.
11732 if (VT.isInteger() && !Subtarget.hasAVX2()) {
11733 int ElementBits = VT.getScalarSizeInBits();
11734 if (ElementBits < 32) {
11735 // No floating point type available, if we can't use the bit operations
11736 // for masking/blending then decompose into 128-bit vectors.
11737 if (SDValue V = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
11739 if (SDValue V = lowerVectorShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
11741 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11744 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
11745 VT.getVectorNumElements());
11746 V1 = DAG.getBitcast(FpVT, V1);
11747 V2 = DAG.getBitcast(FpVT, V2);
11748 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
11751 switch (VT.SimpleTy) {
11753 return lowerV4F64VectorShuffle(DL, Mask, V1, V2, Subtarget, DAG);
11755 return lowerV4I64VectorShuffle(DL, Mask, V1, V2, Subtarget, DAG);
11757 return lowerV8F32VectorShuffle(DL, Mask, V1, V2, Subtarget, DAG);
11759 return lowerV8I32VectorShuffle(DL, Mask, V1, V2, Subtarget, DAG);
11761 return lowerV16I16VectorShuffle(DL, Mask, V1, V2, Subtarget, DAG);
11763 return lowerV32I8VectorShuffle(DL, Mask, V1, V2, Subtarget, DAG);
11766 llvm_unreachable("Not a valid 256-bit x86 vector type!");
11770 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
11771 static SDValue lowerV4X128VectorShuffle(const SDLoc &DL, MVT VT,
11772 ArrayRef<int> Mask, SDValue V1,
11773 SDValue V2, SelectionDAG &DAG) {
11774 assert(VT.getScalarSizeInBits() == 64 &&
11775 "Unexpected element type size for 128bit shuffle.");
11777 // To handle 256 bit vector requires VLX and most probably
11778 // function lowerV2X128VectorShuffle() is better solution.
11779 assert(VT.is512BitVector() && "Unexpected vector size for 512bit shuffle.");
11781 SmallVector<int, 4> WidenedMask;
11782 if (!canWidenShuffleElements(Mask, WidenedMask))
11785 SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
11786 // Insure elements came from the same Op.
11787 int MaxOp1Index = VT.getVectorNumElements()/2 - 1;
11788 for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
11789 if (WidenedMask[i] == SM_SentinelZero)
11791 if (WidenedMask[i] == SM_SentinelUndef)
11794 SDValue Op = WidenedMask[i] > MaxOp1Index ? V2 : V1;
11795 unsigned OpIndex = (i < Size/2) ? 0 : 1;
11796 if (Ops[OpIndex].isUndef())
11798 else if (Ops[OpIndex] != Op)
11802 // Form a 128-bit permutation.
11803 // Convert the 64-bit shuffle mask selection values into 128-bit selection
11804 // bits defined by a vshuf64x2 instruction's immediate control byte.
11805 unsigned PermMask = 0, Imm = 0;
11806 unsigned ControlBitsNum = WidenedMask.size() / 2;
11808 for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
11809 // Use first element in place of undef mask.
11810 Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
11811 PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
11814 return DAG.getNode(X86ISD::SHUF128, DL, VT, Ops[0], Ops[1],
11815 DAG.getConstant(PermMask, DL, MVT::i8));
11818 static SDValue lowerVectorShuffleWithPERMV(const SDLoc &DL, MVT VT,
11819 ArrayRef<int> Mask, SDValue V1,
11820 SDValue V2, SelectionDAG &DAG) {
11822 assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
11824 MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
11825 MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
11827 SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
11829 return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
11831 return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
11834 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
11835 static SDValue lowerV8F64VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
11836 SDValue V1, SDValue V2,
11837 const X86Subtarget &Subtarget,
11838 SelectionDAG &DAG) {
11839 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11840 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11841 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11843 if (V2.isUndef()) {
11844 // Use low duplicate instructions for masks that match their pattern.
11845 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
11846 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v8f64, V1);
11848 if (!is128BitLaneCrossingShuffleMask(MVT::v8f64, Mask)) {
11849 // Non-half-crossing single input shuffles can be lowered with an
11850 // interleaved permutation.
11851 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
11852 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3) |
11853 ((Mask[4] == 5) << 4) | ((Mask[5] == 5) << 5) |
11854 ((Mask[6] == 7) << 6) | ((Mask[7] == 7) << 7);
11855 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f64, V1,
11856 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
11859 SmallVector<int, 4> RepeatedMask;
11860 if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask))
11861 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8f64, V1,
11862 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
11865 if (SDValue Shuf128 =
11866 lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
11869 if (SDValue Unpck =
11870 lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
11873 // Check if the blend happens to exactly fit that of SHUFPD.
11875 lowerVectorShuffleWithSHUFPD(DL, MVT::v8f64, Mask, V1, V2, DAG))
11878 return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
11881 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
11882 static SDValue lowerV16F32VectorShuffle(SDLoc DL, ArrayRef<int> Mask,
11883 SDValue V1, SDValue V2,
11884 const X86Subtarget &Subtarget,
11885 SelectionDAG &DAG) {
11886 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11887 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11888 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11890 // If the shuffle mask is repeated in each 128-bit lane, we have many more
11891 // options to efficiently lower the shuffle.
11892 SmallVector<int, 4> RepeatedMask;
11893 if (is128BitLaneRepeatedShuffleMask(MVT::v16f32, Mask, RepeatedMask)) {
11894 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
11896 // Use even/odd duplicate instructions for masks that match their pattern.
11897 if (isShuffleEquivalent(V1, V2, RepeatedMask, {0, 0, 2, 2}))
11898 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v16f32, V1);
11899 if (isShuffleEquivalent(V1, V2, RepeatedMask, {1, 1, 3, 3}))
11900 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v16f32, V1);
11903 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v16f32, V1,
11904 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
11906 // Use dedicated unpack instructions for masks that match their pattern.
11907 if (SDValue Unpck =
11908 lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
11911 // Otherwise, fall back to a SHUFPS sequence.
11912 return lowerVectorShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask, V1, V2, DAG);
11915 return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
11918 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
11919 static SDValue lowerV8I64VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
11920 SDValue V1, SDValue V2,
11921 const X86Subtarget &Subtarget,
11922 SelectionDAG &DAG) {
11923 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11924 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11925 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11927 if (SDValue Shuf128 =
11928 lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
11931 if (V2.isUndef()) {
11932 // When the shuffle is mirrored between the 128-bit lanes of the unit, we
11933 // can use lower latency instructions that will operate on all four
11935 SmallVector<int, 2> Repeated128Mask;
11936 if (is128BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated128Mask)) {
11937 SmallVector<int, 4> PSHUFDMask;
11938 scaleShuffleMask(2, Repeated128Mask, PSHUFDMask);
11939 return DAG.getBitcast(
11941 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32,
11942 DAG.getBitcast(MVT::v16i32, V1),
11943 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
11946 SmallVector<int, 4> Repeated256Mask;
11947 if (is256BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated256Mask))
11948 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8i64, V1,
11949 getV4X86ShuffleImm8ForMask(Repeated256Mask, DL, DAG));
11952 // Try to use shift instructions.
11953 if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask,
11957 if (SDValue Unpck =
11958 lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
11961 return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
11964 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
11965 static SDValue lowerV16I32VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
11966 SDValue V1, SDValue V2,
11967 const X86Subtarget &Subtarget,
11968 SelectionDAG &DAG) {
11969 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11970 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11971 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11973 // If the shuffle mask is repeated in each 128-bit lane we can use more
11974 // efficient instructions that mirror the shuffles across the four 128-bit
11976 SmallVector<int, 4> RepeatedMask;
11977 if (is128BitLaneRepeatedShuffleMask(MVT::v16i32, Mask, RepeatedMask)) {
11978 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
11980 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32, V1,
11981 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
11983 // Use dedicated unpack instructions for masks that match their pattern.
11985 lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
11989 // Try to use shift instructions.
11990 if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask,
11994 // Try to use byte rotation instructions.
11995 if (Subtarget.hasBWI())
11996 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
11997 DL, MVT::v16i32, V1, V2, Mask, Subtarget, DAG))
12000 return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
12003 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
12004 static SDValue lowerV32I16VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
12005 SDValue V1, SDValue V2,
12006 const X86Subtarget &Subtarget,
12007 SelectionDAG &DAG) {
12008 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
12009 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
12010 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
12011 assert(Subtarget.hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
12013 // Use dedicated unpack instructions for masks that match their pattern.
12015 lowerVectorShuffleWithUNPCK(DL, MVT::v32i16, Mask, V1, V2, DAG))
12018 // Try to use shift instructions.
12019 if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v32i16, V1, V2, Mask,
12023 // Try to use byte rotation instructions.
12024 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
12025 DL, MVT::v32i16, V1, V2, Mask, Subtarget, DAG))
12028 if (V2.isUndef()) {
12029 SmallVector<int, 8> RepeatedMask;
12030 if (is128BitLaneRepeatedShuffleMask(MVT::v32i16, Mask, RepeatedMask)) {
12031 // As this is a single-input shuffle, the repeated mask should be
12032 // a strictly valid v8i16 mask that we can pass through to the v8i16
12033 // lowering to handle even the v32 case.
12034 return lowerV8I16GeneralSingleInputVectorShuffle(
12035 DL, MVT::v32i16, V1, RepeatedMask, Subtarget, DAG);
12039 return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
12042 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
12043 static SDValue lowerV64I8VectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
12044 SDValue V1, SDValue V2,
12045 const X86Subtarget &Subtarget,
12046 SelectionDAG &DAG) {
12047 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
12048 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
12049 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
12050 assert(Subtarget.hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
12052 // Use dedicated unpack instructions for masks that match their pattern.
12054 lowerVectorShuffleWithUNPCK(DL, MVT::v64i8, Mask, V1, V2, DAG))
12057 // Try to use shift instructions.
12058 if (SDValue Shift = lowerVectorShuffleAsShift(DL, MVT::v64i8, V1, V2, Mask,
12062 // Try to use byte rotation instructions.
12063 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
12064 DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
12067 if (SDValue PSHUFB = lowerVectorShuffleWithPSHUFB(DL, MVT::v64i8, Mask, V1,
12068 V2, Subtarget, DAG))
12071 // FIXME: Implement direct support for this type!
12072 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
12075 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
12077 /// This routine either breaks down the specific type of a 512-bit x86 vector
12078 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
12079 /// together based on the available instructions.
12080 static SDValue lower512BitVectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
12081 MVT VT, SDValue V1, SDValue V2,
12082 const X86Subtarget &Subtarget,
12083 SelectionDAG &DAG) {
12084 assert(Subtarget.hasAVX512() &&
12085 "Cannot lower 512-bit vectors w/ basic ISA!");
12087 // Check for being able to broadcast a single element.
12088 if (SDValue Broadcast =
12089 lowerVectorShuffleAsBroadcast(DL, VT, V1, V2, Mask, Subtarget, DAG))
12092 // Dispatch to each element type for lowering. If we don't have support for
12093 // specific element type shuffles at 512 bits, immediately split them and
12094 // lower them. Each lowering routine of a given type is allowed to assume that
12095 // the requisite ISA extensions for that element type are available.
12096 switch (VT.SimpleTy) {
12098 return lowerV8F64VectorShuffle(DL, Mask, V1, V2, Subtarget, DAG);
12100 return lowerV16F32VectorShuffle(DL, Mask, V1, V2, Subtarget, DAG);
12102 return lowerV8I64VectorShuffle(DL, Mask, V1, V2, Subtarget, DAG);
12104 return lowerV16I32VectorShuffle(DL, Mask, V1, V2, Subtarget, DAG);
12106 return lowerV32I16VectorShuffle(DL, Mask, V1, V2, Subtarget, DAG);
12108 return lowerV64I8VectorShuffle(DL, Mask, V1, V2, Subtarget, DAG);
12111 llvm_unreachable("Not a valid 512-bit x86 vector type!");
12115 // Lower vXi1 vector shuffles.
12116 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
12117 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
12118 // vector, shuffle and then truncate it back.
12119 static SDValue lower1BitVectorShuffle(const SDLoc &DL, ArrayRef<int> Mask,
12120 MVT VT, SDValue V1, SDValue V2,
12121 const X86Subtarget &Subtarget,
12122 SelectionDAG &DAG) {
12123 assert(Subtarget.hasAVX512() &&
12124 "Cannot lower 512-bit vectors w/o basic ISA!");
12126 switch (VT.SimpleTy) {
12128 llvm_unreachable("Expected a vector of i1 elements");
12130 ExtVT = MVT::v2i64;
12133 ExtVT = MVT::v4i32;
12136 ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
12139 ExtVT = MVT::v16i32;
12142 ExtVT = MVT::v32i16;
12145 ExtVT = MVT::v64i8;
12149 if (ISD::isBuildVectorAllZeros(V1.getNode()))
12150 V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
12151 else if (ISD::isBuildVectorAllOnes(V1.getNode()))
12152 V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
12154 V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
12157 V2 = DAG.getUNDEF(ExtVT);
12158 else if (ISD::isBuildVectorAllZeros(V2.getNode()))
12159 V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
12160 else if (ISD::isBuildVectorAllOnes(V2.getNode()))
12161 V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
12163 V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
12164 return DAG.getNode(ISD::TRUNCATE, DL, VT,
12165 DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
12167 /// \brief Top-level lowering for x86 vector shuffles.
12169 /// This handles decomposition, canonicalization, and lowering of all x86
12170 /// vector shuffles. Most of the specific lowering strategies are encapsulated
12171 /// above in helper routines. The canonicalization attempts to widen shuffles
12172 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
12173 /// s.t. only one of the two inputs needs to be tested, etc.
12174 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget &Subtarget,
12175 SelectionDAG &DAG) {
12176 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
12177 ArrayRef<int> Mask = SVOp->getMask();
12178 SDValue V1 = Op.getOperand(0);
12179 SDValue V2 = Op.getOperand(1);
12180 MVT VT = Op.getSimpleValueType();
12181 int NumElements = VT.getVectorNumElements();
12183 bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
12185 assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
12186 "Can't lower MMX shuffles");
12188 bool V1IsUndef = V1.isUndef();
12189 bool V2IsUndef = V2.isUndef();
12190 if (V1IsUndef && V2IsUndef)
12191 return DAG.getUNDEF(VT);
12193 // When we create a shuffle node we put the UNDEF node to second operand,
12194 // but in some cases the first operand may be transformed to UNDEF.
12195 // In this case we should just commute the node.
12197 return DAG.getCommutedVectorShuffle(*SVOp);
12199 // Check for non-undef masks pointing at an undef vector and make the masks
12200 // undef as well. This makes it easier to match the shuffle based solely on
12204 if (M >= NumElements) {
12205 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
12206 for (int &M : NewMask)
12207 if (M >= NumElements)
12209 return DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
12212 // We actually see shuffles that are entirely re-arrangements of a set of
12213 // zero inputs. This mostly happens while decomposing complex shuffles into
12214 // simple ones. Directly lower these as a buildvector of zeros.
12215 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
12216 if (Zeroable.all())
12217 return getZeroVector(VT, Subtarget, DAG, DL);
12219 // Try to collapse shuffles into using a vector type with fewer elements but
12220 // wider element types. We cap this to not form integers or floating point
12221 // elements wider than 64 bits, but it might be interesting to form i128
12222 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
12223 SmallVector<int, 16> WidenedMask;
12224 if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
12225 canWidenShuffleElements(Mask, WidenedMask)) {
12226 MVT NewEltVT = VT.isFloatingPoint()
12227 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
12228 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
12229 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
12230 // Make sure that the new vector type is legal. For example, v2f64 isn't
12232 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
12233 V1 = DAG.getBitcast(NewVT, V1);
12234 V2 = DAG.getBitcast(NewVT, V2);
12235 return DAG.getBitcast(
12236 VT, DAG.getVectorShuffle(NewVT, DL, V1, V2, WidenedMask));
12240 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
12243 ++NumUndefElements;
12244 else if (M < NumElements)
12249 // Commute the shuffle as needed such that more elements come from V1 than
12250 // V2. This allows us to match the shuffle pattern strictly on how many
12251 // elements come from V1 without handling the symmetric cases.
12252 if (NumV2Elements > NumV1Elements)
12253 return DAG.getCommutedVectorShuffle(*SVOp);
12255 assert(NumV1Elements > 0 && "No V1 indices");
12256 assert((NumV2Elements > 0 || V2IsUndef) && "V2 not undef, but not used");
12258 // When the number of V1 and V2 elements are the same, try to minimize the
12259 // number of uses of V2 in the low half of the vector. When that is tied,
12260 // ensure that the sum of indices for V1 is equal to or lower than the sum
12261 // indices for V2. When those are equal, try to ensure that the number of odd
12262 // indices for V1 is lower than the number of odd indices for V2.
12263 if (NumV1Elements == NumV2Elements) {
12264 int LowV1Elements = 0, LowV2Elements = 0;
12265 for (int M : Mask.slice(0, NumElements / 2))
12266 if (M >= NumElements)
12270 if (LowV2Elements > LowV1Elements)
12271 return DAG.getCommutedVectorShuffle(*SVOp);
12272 if (LowV2Elements == LowV1Elements) {
12273 int SumV1Indices = 0, SumV2Indices = 0;
12274 for (int i = 0, Size = Mask.size(); i < Size; ++i)
12275 if (Mask[i] >= NumElements)
12277 else if (Mask[i] >= 0)
12279 if (SumV2Indices < SumV1Indices)
12280 return DAG.getCommutedVectorShuffle(*SVOp);
12281 if (SumV2Indices == SumV1Indices) {
12282 int NumV1OddIndices = 0, NumV2OddIndices = 0;
12283 for (int i = 0, Size = Mask.size(); i < Size; ++i)
12284 if (Mask[i] >= NumElements)
12285 NumV2OddIndices += i % 2;
12286 else if (Mask[i] >= 0)
12287 NumV1OddIndices += i % 2;
12288 if (NumV2OddIndices < NumV1OddIndices)
12289 return DAG.getCommutedVectorShuffle(*SVOp);
12294 // For each vector width, delegate to a specialized lowering routine.
12295 if (VT.is128BitVector())
12296 return lower128BitVectorShuffle(DL, Mask, VT, V1, V2, Subtarget, DAG);
12298 if (VT.is256BitVector())
12299 return lower256BitVectorShuffle(DL, Mask, VT, V1, V2, Subtarget, DAG);
12301 if (VT.is512BitVector())
12302 return lower512BitVectorShuffle(DL, Mask, VT, V1, V2, Subtarget, DAG);
12305 return lower1BitVectorShuffle(DL, Mask, VT, V1, V2, Subtarget, DAG);
12307 llvm_unreachable("Unimplemented!");
12310 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
12311 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
12312 const X86Subtarget &Subtarget,
12313 SelectionDAG &DAG) {
12314 SDValue Cond = Op.getOperand(0);
12315 SDValue LHS = Op.getOperand(1);
12316 SDValue RHS = Op.getOperand(2);
12318 MVT VT = Op.getSimpleValueType();
12320 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
12322 auto *CondBV = cast<BuildVectorSDNode>(Cond);
12324 // Only non-legal VSELECTs reach this lowering, convert those into generic
12325 // shuffles and re-use the shuffle lowering path for blends.
12326 SmallVector<int, 32> Mask;
12327 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
12328 SDValue CondElt = CondBV->getOperand(i);
12330 isa<ConstantSDNode>(CondElt) ? i + (isNullConstant(CondElt) ? Size : 0)
12333 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
12336 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
12337 // A vselect where all conditions and data are constants can be optimized into
12338 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
12339 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
12340 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
12341 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
12344 // Try to lower this to a blend-style vector shuffle. This can handle all
12345 // constant condition cases.
12346 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
12349 // Variable blends are only legal from SSE4.1 onward.
12350 if (!Subtarget.hasSSE41())
12353 // Only some types will be legal on some subtargets. If we can emit a legal
12354 // VSELECT-matching blend, return Op, and but if we need to expand, return
12356 switch (Op.getSimpleValueType().SimpleTy) {
12358 // Most of the vector types have blends past SSE4.1.
12362 // The byte blends for AVX vectors were introduced only in AVX2.
12363 if (Subtarget.hasAVX2())
12370 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
12371 if (Subtarget.hasBWI() && Subtarget.hasVLX())
12374 // FIXME: We should custom lower this by fixing the condition and using i8
12380 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
12381 MVT VT = Op.getSimpleValueType();
12384 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
12387 if (VT.getSizeInBits() == 8) {
12388 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
12389 Op.getOperand(0), Op.getOperand(1));
12390 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
12391 DAG.getValueType(VT));
12392 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12395 if (VT.getSizeInBits() == 16) {
12396 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
12397 if (isNullConstant(Op.getOperand(1)))
12398 return DAG.getNode(
12399 ISD::TRUNCATE, dl, MVT::i16,
12400 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12401 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
12402 Op.getOperand(1)));
12403 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
12404 Op.getOperand(0), Op.getOperand(1));
12405 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
12406 DAG.getValueType(VT));
12407 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12410 if (VT == MVT::f32) {
12411 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
12412 // the result back to FR32 register. It's only worth matching if the
12413 // result has a single use which is a store or a bitcast to i32. And in
12414 // the case of a store, it's not worth it if the index is a constant 0,
12415 // because a MOVSSmr can be used instead, which is smaller and faster.
12416 if (!Op.hasOneUse())
12418 SDNode *User = *Op.getNode()->use_begin();
12419 if ((User->getOpcode() != ISD::STORE ||
12420 isNullConstant(Op.getOperand(1))) &&
12421 (User->getOpcode() != ISD::BITCAST ||
12422 User->getValueType(0) != MVT::i32))
12424 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12425 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
12427 return DAG.getBitcast(MVT::f32, Extract);
12430 if (VT == MVT::i32 || VT == MVT::i64) {
12431 // ExtractPS/pextrq works with constant index.
12432 if (isa<ConstantSDNode>(Op.getOperand(1)))
12438 /// Extract one bit from mask vector, like v16i1 or v8i1.
12439 /// AVX-512 feature.
12441 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
12442 SDValue Vec = Op.getOperand(0);
12444 MVT VecVT = Vec.getSimpleValueType();
12445 SDValue Idx = Op.getOperand(1);
12446 MVT EltVT = Op.getSimpleValueType();
12448 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
12449 assert((VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI()) &&
12450 "Unexpected vector type in ExtractBitFromMaskVector");
12452 // variable index can't be handled in mask registers,
12453 // extend vector to VR512
12454 if (!isa<ConstantSDNode>(Idx)) {
12455 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
12456 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
12457 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
12458 ExtVT.getVectorElementType(), Ext, Idx);
12459 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
12462 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12463 if (!Subtarget.hasDQI() && (VecVT.getVectorNumElements() <= 8)) {
12464 // Use kshiftlw/rw instruction.
12465 VecVT = MVT::v16i1;
12466 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VecVT,
12467 DAG.getUNDEF(VecVT),
12469 DAG.getIntPtrConstant(0, dl));
12471 unsigned MaxSift = VecVT.getVectorNumElements() - 1;
12472 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
12473 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
12474 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
12475 DAG.getConstant(MaxSift, dl, MVT::i8));
12476 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
12477 DAG.getIntPtrConstant(0, dl));
12481 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
12482 SelectionDAG &DAG) const {
12484 SDValue Vec = Op.getOperand(0);
12485 MVT VecVT = Vec.getSimpleValueType();
12486 SDValue Idx = Op.getOperand(1);
12488 if (Op.getSimpleValueType() == MVT::i1)
12489 return ExtractBitFromMaskVector(Op, DAG);
12491 if (!isa<ConstantSDNode>(Idx)) {
12492 if (VecVT.is512BitVector() ||
12493 (VecVT.is256BitVector() && Subtarget.hasInt256() &&
12494 VecVT.getVectorElementType().getSizeInBits() == 32)) {
12497 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
12498 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
12499 MaskEltVT.getSizeInBits());
12501 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
12502 auto PtrVT = getPointerTy(DAG.getDataLayout());
12503 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
12504 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
12505 DAG.getConstant(0, dl, PtrVT));
12506 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
12507 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
12508 DAG.getConstant(0, dl, PtrVT));
12513 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12515 // If this is a 256-bit vector result, first extract the 128-bit vector and
12516 // then extract the element from the 128-bit vector.
12517 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
12518 // Get the 128-bit vector.
12519 Vec = extract128BitVector(Vec, IdxVal, DAG, dl);
12520 MVT EltVT = VecVT.getVectorElementType();
12522 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
12523 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
12525 // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
12526 // this can be done with a mask.
12527 IdxVal &= ElemsPerChunk - 1;
12528 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
12529 DAG.getConstant(IdxVal, dl, MVT::i32));
12532 assert(VecVT.is128BitVector() && "Unexpected vector length");
12534 if (Subtarget.hasSSE41())
12535 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
12538 MVT VT = Op.getSimpleValueType();
12539 // TODO: handle v16i8.
12540 if (VT.getSizeInBits() == 16) {
12542 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
12543 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
12544 DAG.getBitcast(MVT::v4i32, Vec), Idx));
12546 // Transform it so it match pextrw which produces a 32-bit result.
12547 MVT EltVT = MVT::i32;
12548 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT, Vec, Idx);
12549 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
12550 DAG.getValueType(VT));
12551 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
12554 if (VT.getSizeInBits() == 32) {
12558 // SHUFPS the element to the lowest double word, then movss.
12559 int Mask[4] = { static_cast<int>(IdxVal), -1, -1, -1 };
12560 Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
12561 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
12562 DAG.getIntPtrConstant(0, dl));
12565 if (VT.getSizeInBits() == 64) {
12566 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
12567 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
12568 // to match extract_elt for f64.
12572 // UNPCKHPD the element to the lowest double word, then movsd.
12573 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
12574 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
12575 int Mask[2] = { 1, -1 };
12576 Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
12577 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
12578 DAG.getIntPtrConstant(0, dl));
12584 /// Insert one bit to mask vector, like v16i1 or v8i1.
12585 /// AVX-512 feature.
12587 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
12589 SDValue Vec = Op.getOperand(0);
12590 SDValue Elt = Op.getOperand(1);
12591 SDValue Idx = Op.getOperand(2);
12592 MVT VecVT = Vec.getSimpleValueType();
12594 if (!isa<ConstantSDNode>(Idx)) {
12595 // Non constant index. Extend source and destination,
12596 // insert element and then truncate the result.
12597 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
12598 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
12599 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
12600 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
12601 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
12602 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
12605 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12606 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
12608 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
12609 DAG.getConstant(IdxVal, dl, MVT::i8));
12612 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
12615 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
12616 SelectionDAG &DAG) const {
12617 MVT VT = Op.getSimpleValueType();
12618 MVT EltVT = VT.getVectorElementType();
12619 unsigned NumElts = VT.getVectorNumElements();
12621 if (EltVT == MVT::i1)
12622 return InsertBitToMaskVector(Op, DAG);
12625 SDValue N0 = Op.getOperand(0);
12626 SDValue N1 = Op.getOperand(1);
12627 SDValue N2 = Op.getOperand(2);
12628 if (!isa<ConstantSDNode>(N2))
12630 auto *N2C = cast<ConstantSDNode>(N2);
12631 unsigned IdxVal = N2C->getZExtValue();
12633 // If we are clearing out a element, we do this more efficiently with a
12634 // blend shuffle than a costly integer insertion.
12635 // TODO: would other rematerializable values (e.g. allbits) benefit as well?
12636 // TODO: pre-SSE41 targets will tend to use bit masking - this could still
12637 // be beneficial if we are inserting several zeros and can combine the masks.
12638 if (X86::isZeroNode(N1) && Subtarget.hasSSE41() && NumElts <= 8) {
12639 SmallVector<int, 8> ClearMask;
12640 for (unsigned i = 0; i != NumElts; ++i)
12641 ClearMask.push_back(i == IdxVal ? i + NumElts : i);
12642 SDValue ZeroVector = getZeroVector(VT, Subtarget, DAG, dl);
12643 return DAG.getVectorShuffle(VT, dl, N0, ZeroVector, ClearMask);
12646 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
12647 // into that, and then insert the subvector back into the result.
12648 if (VT.is256BitVector() || VT.is512BitVector()) {
12649 // With a 256-bit vector, we can insert into the zero element efficiently
12650 // using a blend if we have AVX or AVX2 and the right data type.
12651 if (VT.is256BitVector() && IdxVal == 0) {
12652 // TODO: It is worthwhile to cast integer to floating point and back
12653 // and incur a domain crossing penalty if that's what we'll end up
12654 // doing anyway after extracting to a 128-bit vector.
12655 if ((Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
12656 (Subtarget.hasAVX2() && EltVT == MVT::i32)) {
12657 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
12658 N2 = DAG.getIntPtrConstant(1, dl);
12659 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
12663 // Get the desired 128-bit vector chunk.
12664 SDValue V = extract128BitVector(N0, IdxVal, DAG, dl);
12666 // Insert the element into the desired chunk.
12667 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
12668 assert(isPowerOf2_32(NumEltsIn128));
12669 // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
12670 unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
12672 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
12673 DAG.getConstant(IdxIn128, dl, MVT::i32));
12675 // Insert the changed part back into the bigger vector
12676 return insert128BitVector(N0, V, IdxVal, DAG, dl);
12678 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
12680 if (Subtarget.hasSSE41()) {
12681 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
12683 if (VT == MVT::v8i16) {
12684 Opc = X86ISD::PINSRW;
12686 assert(VT == MVT::v16i8);
12687 Opc = X86ISD::PINSRB;
12690 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
12692 if (N1.getValueType() != MVT::i32)
12693 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12694 if (N2.getValueType() != MVT::i32)
12695 N2 = DAG.getIntPtrConstant(IdxVal, dl);
12696 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
12699 if (EltVT == MVT::f32) {
12700 // Bits [7:6] of the constant are the source select. This will always be
12701 // zero here. The DAG Combiner may combine an extract_elt index into
12702 // these bits. For example (insert (extract, 3), 2) could be matched by
12703 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
12704 // Bits [5:4] of the constant are the destination select. This is the
12705 // value of the incoming immediate.
12706 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
12707 // combine either bitwise AND or insert of float 0.0 to set these bits.
12709 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
12710 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
12711 // If this is an insertion of 32-bits into the low 32-bits of
12712 // a vector, we prefer to generate a blend with immediate rather
12713 // than an insertps. Blends are simpler operations in hardware and so
12714 // will always have equal or better performance than insertps.
12715 // But if optimizing for size and there's a load folding opportunity,
12716 // generate insertps because blendps does not have a 32-bit memory
12718 N2 = DAG.getIntPtrConstant(1, dl);
12719 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
12720 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
12722 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
12723 // Create this as a scalar to vector..
12724 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
12725 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
12728 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
12729 // PINSR* works with constant index.
12734 if (EltVT == MVT::i8)
12737 if (EltVT.getSizeInBits() == 16) {
12738 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
12739 // as its second argument.
12740 if (N1.getValueType() != MVT::i32)
12741 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
12742 if (N2.getValueType() != MVT::i32)
12743 N2 = DAG.getIntPtrConstant(IdxVal, dl);
12744 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
12749 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
12751 MVT OpVT = Op.getSimpleValueType();
12753 // If this is a 256-bit vector result, first insert into a 128-bit
12754 // vector and then insert into the 256-bit vector.
12755 if (!OpVT.is128BitVector()) {
12756 // Insert into a 128-bit vector.
12757 unsigned SizeFactor = OpVT.getSizeInBits()/128;
12758 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
12759 OpVT.getVectorNumElements() / SizeFactor);
12761 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
12763 // Insert the 128-bit vector.
12764 return insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
12767 if (OpVT == MVT::v1i64 &&
12768 Op.getOperand(0).getValueType() == MVT::i64)
12769 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
12771 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
12772 assert(OpVT.is128BitVector() && "Expected an SSE type!");
12773 return DAG.getBitcast(
12774 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
12777 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
12778 // a simple subregister reference or explicit instructions to grab
12779 // upper bits of a vector.
12780 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
12781 SelectionDAG &DAG) {
12783 SDValue In = Op.getOperand(0);
12784 SDValue Idx = Op.getOperand(1);
12785 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12786 MVT ResVT = Op.getSimpleValueType();
12787 MVT InVT = In.getSimpleValueType();
12789 if (Subtarget.hasFp256()) {
12790 if (ResVT.is128BitVector() &&
12791 (InVT.is256BitVector() || InVT.is512BitVector()) &&
12792 isa<ConstantSDNode>(Idx)) {
12793 return extract128BitVector(In, IdxVal, DAG, dl);
12795 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
12796 isa<ConstantSDNode>(Idx)) {
12797 return extract256BitVector(In, IdxVal, DAG, dl);
12803 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
12804 // simple superregister reference or explicit instructions to insert
12805 // the upper bits of a vector.
12806 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
12807 SelectionDAG &DAG) {
12808 if (!Subtarget.hasAVX())
12812 SDValue Vec = Op.getOperand(0);
12813 SDValue SubVec = Op.getOperand(1);
12814 SDValue Idx = Op.getOperand(2);
12816 if (!isa<ConstantSDNode>(Idx))
12819 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12820 MVT OpVT = Op.getSimpleValueType();
12821 MVT SubVecVT = SubVec.getSimpleValueType();
12823 // Fold two 16-byte subvector loads into one 32-byte load:
12824 // (insert_subvector (insert_subvector undef, (load addr), 0),
12825 // (load addr + 16), Elts/2)
12827 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
12828 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
12829 OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
12830 auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
12831 if (Idx2 && Idx2->getZExtValue() == 0) {
12832 // If needed, look through bitcasts to get to the load.
12833 SDValue SubVec2 = peekThroughBitcasts(Vec.getOperand(1));
12834 if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
12836 unsigned Alignment = FirstLd->getAlignment();
12837 unsigned AS = FirstLd->getAddressSpace();
12838 const X86TargetLowering *TLI = Subtarget.getTargetLowering();
12839 if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
12840 OpVT, AS, Alignment, &Fast) && Fast) {
12841 SDValue Ops[] = { SubVec2, SubVec };
12842 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
12849 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
12850 SubVecVT.is128BitVector())
12851 return insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
12853 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
12854 return insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
12856 if (OpVT.getVectorElementType() == MVT::i1)
12857 return insert1BitVector(Op, DAG, Subtarget);
12862 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
12863 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
12864 // one of the above mentioned nodes. It has to be wrapped because otherwise
12865 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
12866 // be used to form addressing mode. These wrapped nodes will be selected
12869 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
12870 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
12872 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12873 // global base reg.
12874 unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
12875 unsigned WrapperKind = X86ISD::Wrapper;
12876 CodeModel::Model M = DAG.getTarget().getCodeModel();
12878 if (Subtarget.isPICStyleRIPRel() &&
12879 (M == CodeModel::Small || M == CodeModel::Kernel))
12880 WrapperKind = X86ISD::WrapperRIP;
12882 auto PtrVT = getPointerTy(DAG.getDataLayout());
12883 SDValue Result = DAG.getTargetConstantPool(
12884 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
12886 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12887 // With PIC, the address is actually $g + Offset.
12890 DAG.getNode(ISD::ADD, DL, PtrVT,
12891 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12897 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
12898 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
12900 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12901 // global base reg.
12902 unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
12903 unsigned WrapperKind = X86ISD::Wrapper;
12904 CodeModel::Model M = DAG.getTarget().getCodeModel();
12906 if (Subtarget.isPICStyleRIPRel() &&
12907 (M == CodeModel::Small || M == CodeModel::Kernel))
12908 WrapperKind = X86ISD::WrapperRIP;
12910 auto PtrVT = getPointerTy(DAG.getDataLayout());
12911 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
12913 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12915 // With PIC, the address is actually $g + Offset.
12918 DAG.getNode(ISD::ADD, DL, PtrVT,
12919 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12925 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
12926 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
12928 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12929 // global base reg.
12930 const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
12931 unsigned char OpFlag = Subtarget.classifyGlobalReference(nullptr, *Mod);
12932 unsigned WrapperKind = X86ISD::Wrapper;
12933 CodeModel::Model M = DAG.getTarget().getCodeModel();
12935 if (Subtarget.isPICStyleRIPRel() &&
12936 (M == CodeModel::Small || M == CodeModel::Kernel))
12937 WrapperKind = X86ISD::WrapperRIP;
12939 auto PtrVT = getPointerTy(DAG.getDataLayout());
12940 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
12943 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12945 // With PIC, the address is actually $g + Offset.
12946 if (isPositionIndependent() && !Subtarget.is64Bit()) {
12948 DAG.getNode(ISD::ADD, DL, PtrVT,
12949 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12952 // For symbols that require a load from a stub to get the address, emit the
12954 if (isGlobalStubReference(OpFlag))
12955 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
12956 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
12962 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12963 // Create the TargetBlockAddressAddress node.
12964 unsigned char OpFlags =
12965 Subtarget.classifyBlockAddressReference();
12966 CodeModel::Model M = DAG.getTarget().getCodeModel();
12967 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12968 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12970 auto PtrVT = getPointerTy(DAG.getDataLayout());
12971 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
12973 if (Subtarget.isPICStyleRIPRel() &&
12974 (M == CodeModel::Small || M == CodeModel::Kernel))
12975 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12977 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12979 // With PIC, the address is actually $g + Offset.
12980 if (isGlobalRelativeToPICBase(OpFlags)) {
12981 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12982 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12988 SDValue X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV,
12989 const SDLoc &dl, int64_t Offset,
12990 SelectionDAG &DAG) const {
12991 // Create the TargetGlobalAddress node, folding in the constant
12992 // offset if it is legal.
12993 unsigned char OpFlags = Subtarget.classifyGlobalReference(GV);
12994 CodeModel::Model M = DAG.getTarget().getCodeModel();
12995 auto PtrVT = getPointerTy(DAG.getDataLayout());
12997 if (OpFlags == X86II::MO_NO_FLAG &&
12998 X86::isOffsetSuitableForCodeModel(Offset, M)) {
12999 // A direct static reference to a global.
13000 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
13003 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
13006 if (Subtarget.isPICStyleRIPRel() &&
13007 (M == CodeModel::Small || M == CodeModel::Kernel))
13008 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
13010 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
13012 // With PIC, the address is actually $g + Offset.
13013 if (isGlobalRelativeToPICBase(OpFlags)) {
13014 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
13015 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
13018 // For globals that require a load from a stub to get the address, emit the
13020 if (isGlobalStubReference(OpFlags))
13021 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
13022 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
13024 // If there was a non-zero offset that we didn't fold, create an explicit
13025 // addition for it.
13027 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
13028 DAG.getConstant(Offset, dl, PtrVT));
13034 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
13035 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
13036 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
13037 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
13041 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
13042 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
13043 unsigned char OperandFlags, bool LocalDynamic = false) {
13044 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13045 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13047 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13048 GA->getValueType(0),
13052 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
13056 SDValue Ops[] = { Chain, TGA, *InFlag };
13057 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
13059 SDValue Ops[] = { Chain, TGA };
13060 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
13063 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
13064 MFI->setAdjustsStack(true);
13065 MFI->setHasCalls(true);
13067 SDValue Flag = Chain.getValue(1);
13068 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
13071 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
13073 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13076 SDLoc dl(GA); // ? function entry point might be better
13077 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
13078 DAG.getNode(X86ISD::GlobalBaseReg,
13079 SDLoc(), PtrVT), InFlag);
13080 InFlag = Chain.getValue(1);
13082 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
13085 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
13087 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13089 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
13090 X86::RAX, X86II::MO_TLSGD);
13093 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
13099 // Get the start address of the TLS block for this module.
13100 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
13101 .getInfo<X86MachineFunctionInfo>();
13102 MFI->incNumLocalDynamicTLSAccesses();
13106 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
13107 X86II::MO_TLSLD, /*LocalDynamic=*/true);
13110 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
13111 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
13112 InFlag = Chain.getValue(1);
13113 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
13114 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
13117 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
13121 unsigned char OperandFlags = X86II::MO_DTPOFF;
13122 unsigned WrapperKind = X86ISD::Wrapper;
13123 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13124 GA->getValueType(0),
13125 GA->getOffset(), OperandFlags);
13126 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
13128 // Add x@dtpoff with the base.
13129 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
13132 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
13133 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
13134 const EVT PtrVT, TLSModel::Model model,
13135 bool is64Bit, bool isPIC) {
13138 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
13139 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
13140 is64Bit ? 257 : 256));
13142 SDValue ThreadPointer =
13143 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
13144 MachinePointerInfo(Ptr));
13146 unsigned char OperandFlags = 0;
13147 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
13149 unsigned WrapperKind = X86ISD::Wrapper;
13150 if (model == TLSModel::LocalExec) {
13151 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
13152 } else if (model == TLSModel::InitialExec) {
13154 OperandFlags = X86II::MO_GOTTPOFF;
13155 WrapperKind = X86ISD::WrapperRIP;
13157 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
13160 llvm_unreachable("Unexpected model");
13163 // emit "addl x@ntpoff,%eax" (local exec)
13164 // or "addl x@indntpoff,%eax" (initial exec)
13165 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
13167 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
13168 GA->getOffset(), OperandFlags);
13169 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
13171 if (model == TLSModel::InitialExec) {
13172 if (isPIC && !is64Bit) {
13173 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
13174 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
13178 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
13179 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
13182 // The address of the thread local variable is the add of the thread
13183 // pointer with the offset of the variable.
13184 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
13188 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
13190 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
13192 if (DAG.getTarget().Options.EmulatedTLS)
13193 return LowerToTLSEmulatedModel(GA, DAG);
13195 const GlobalValue *GV = GA->getGlobal();
13196 auto PtrVT = getPointerTy(DAG.getDataLayout());
13197 bool PositionIndependent = isPositionIndependent();
13199 if (Subtarget.isTargetELF()) {
13200 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
13202 case TLSModel::GeneralDynamic:
13203 if (Subtarget.is64Bit())
13204 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
13205 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
13206 case TLSModel::LocalDynamic:
13207 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
13208 Subtarget.is64Bit());
13209 case TLSModel::InitialExec:
13210 case TLSModel::LocalExec:
13211 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget.is64Bit(),
13212 PositionIndependent);
13214 llvm_unreachable("Unknown TLS model.");
13217 if (Subtarget.isTargetDarwin()) {
13218 // Darwin only has one model of TLS. Lower to that.
13219 unsigned char OpFlag = 0;
13220 unsigned WrapperKind = Subtarget.isPICStyleRIPRel() ?
13221 X86ISD::WrapperRIP : X86ISD::Wrapper;
13223 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
13224 // global base reg.
13225 bool PIC32 = PositionIndependent && !Subtarget.is64Bit();
13227 OpFlag = X86II::MO_TLVP_PIC_BASE;
13229 OpFlag = X86II::MO_TLVP;
13231 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
13232 GA->getValueType(0),
13233 GA->getOffset(), OpFlag);
13234 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
13236 // With PIC32, the address is actually $g + Offset.
13238 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
13239 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
13242 // Lowering the machine isd will make sure everything is in the right
13244 SDValue Chain = DAG.getEntryNode();
13245 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13246 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, DL, true), DL);
13247 SDValue Args[] = { Chain, Offset };
13248 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
13249 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
13250 DAG.getIntPtrConstant(0, DL, true),
13251 Chain.getValue(1), DL);
13253 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
13254 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13255 MFI->setAdjustsStack(true);
13257 // And our return value (tls address) is in the standard call return value
13259 unsigned Reg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
13260 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
13263 if (Subtarget.isTargetKnownWindowsMSVC() ||
13264 Subtarget.isTargetWindowsItanium() ||
13265 Subtarget.isTargetWindowsGNU()) {
13266 // Just use the implicit TLS architecture
13267 // Need to generate someting similar to:
13268 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
13270 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
13271 // mov rcx, qword [rdx+rcx*8]
13272 // mov eax, .tls$:tlsvar
13273 // [rax+rcx] contains the address
13274 // Windows 64bit: gs:0x58
13275 // Windows 32bit: fs:__tls_array
13278 SDValue Chain = DAG.getEntryNode();
13280 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
13281 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
13282 // use its literal value of 0x2C.
13283 Value *Ptr = Constant::getNullValue(Subtarget.is64Bit()
13284 ? Type::getInt8PtrTy(*DAG.getContext(),
13286 : Type::getInt32PtrTy(*DAG.getContext(),
13289 SDValue TlsArray = Subtarget.is64Bit()
13290 ? DAG.getIntPtrConstant(0x58, dl)
13291 : (Subtarget.isTargetWindowsGNU()
13292 ? DAG.getIntPtrConstant(0x2C, dl)
13293 : DAG.getExternalSymbol("_tls_array", PtrVT));
13295 SDValue ThreadPointer =
13296 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr));
13299 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
13300 res = ThreadPointer;
13302 // Load the _tls_index variable
13303 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
13304 if (Subtarget.is64Bit())
13305 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
13306 MachinePointerInfo(), MVT::i32);
13308 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo());
13310 auto &DL = DAG.getDataLayout();
13312 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
13313 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
13315 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
13318 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo());
13320 // Get the offset of start of .tls section
13321 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
13322 GA->getValueType(0),
13323 GA->getOffset(), X86II::MO_SECREL);
13324 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
13326 // The address of the thread local variable is the add of the thread
13327 // pointer with the offset of the variable.
13328 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
13331 llvm_unreachable("TLS not implemented for this target.");
13334 /// Lower SRA_PARTS and friends, which return two i32 values
13335 /// and take a 2 x i32 value to shift plus a shift amount.
13336 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
13337 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
13338 MVT VT = Op.getSimpleValueType();
13339 unsigned VTBits = VT.getSizeInBits();
13341 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
13342 SDValue ShOpLo = Op.getOperand(0);
13343 SDValue ShOpHi = Op.getOperand(1);
13344 SDValue ShAmt = Op.getOperand(2);
13345 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
13346 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
13348 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
13349 DAG.getConstant(VTBits - 1, dl, MVT::i8));
13350 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
13351 DAG.getConstant(VTBits - 1, dl, MVT::i8))
13352 : DAG.getConstant(0, dl, VT);
13354 SDValue Tmp2, Tmp3;
13355 if (Op.getOpcode() == ISD::SHL_PARTS) {
13356 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
13357 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
13359 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
13360 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
13363 // If the shift amount is larger or equal than the width of a part we can't
13364 // rely on the results of shld/shrd. Insert a test and select the appropriate
13365 // values for large shift amounts.
13366 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
13367 DAG.getConstant(VTBits, dl, MVT::i8));
13368 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13369 AndNode, DAG.getConstant(0, dl, MVT::i8));
13372 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
13373 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
13374 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
13376 if (Op.getOpcode() == ISD::SHL_PARTS) {
13377 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
13378 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
13380 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
13381 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
13384 SDValue Ops[2] = { Lo, Hi };
13385 return DAG.getMergeValues(Ops, dl);
13388 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
13389 SelectionDAG &DAG) const {
13390 SDValue Src = Op.getOperand(0);
13391 MVT SrcVT = Src.getSimpleValueType();
13392 MVT VT = Op.getSimpleValueType();
13395 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13396 if (SrcVT.isVector()) {
13397 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
13398 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
13399 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
13400 DAG.getUNDEF(SrcVT)));
13402 if (SrcVT.getVectorElementType() == MVT::i1) {
13403 if (SrcVT == MVT::v2i1 && TLI.isTypeLegal(SrcVT))
13404 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13405 DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v2i64, Src));
13406 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
13407 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13408 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
13413 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
13414 "Unknown SINT_TO_FP to lower!");
13416 // These are really Legal; return the operand so the caller accepts it as
13418 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
13420 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
13421 Subtarget.is64Bit()) {
13425 SDValue ValueToStore = Op.getOperand(0);
13426 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
13427 !Subtarget.is64Bit())
13428 // Bitcasting to f64 here allows us to do a single 64-bit store from
13429 // an SSE register, avoiding the store forwarding penalty that would come
13430 // with two 32-bit stores.
13431 ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
13433 unsigned Size = SrcVT.getSizeInBits()/8;
13434 MachineFunction &MF = DAG.getMachineFunction();
13435 auto PtrVT = getPointerTy(MF.getDataLayout());
13436 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
13437 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13438 SDValue Chain = DAG.getStore(
13439 DAG.getEntryNode(), dl, ValueToStore, StackSlot,
13440 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI));
13441 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
13444 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
13446 SelectionDAG &DAG) const {
13450 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
13452 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
13454 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
13456 unsigned ByteSize = SrcVT.getSizeInBits()/8;
13458 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
13459 MachineMemOperand *MMO;
13461 int SSFI = FI->getIndex();
13462 MMO = DAG.getMachineFunction().getMachineMemOperand(
13463 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
13464 MachineMemOperand::MOLoad, ByteSize, ByteSize);
13466 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
13467 StackSlot = StackSlot.getOperand(1);
13469 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
13470 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
13472 Tys, Ops, SrcVT, MMO);
13475 Chain = Result.getValue(1);
13476 SDValue InFlag = Result.getValue(2);
13478 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
13479 // shouldn't be necessary except that RFP cannot be live across
13480 // multiple blocks. When stackifier is fixed, they can be uncoupled.
13481 MachineFunction &MF = DAG.getMachineFunction();
13482 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
13483 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
13484 auto PtrVT = getPointerTy(MF.getDataLayout());
13485 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13486 Tys = DAG.getVTList(MVT::Other);
13488 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
13490 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
13491 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
13492 MachineMemOperand::MOStore, SSFISize, SSFISize);
13494 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
13495 Ops, Op.getValueType(), MMO);
13496 Result = DAG.getLoad(
13497 Op.getValueType(), DL, Chain, StackSlot,
13498 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI));
13504 /// 64-bit unsigned integer to double expansion.
13505 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
13506 SelectionDAG &DAG) const {
13507 // This algorithm is not obvious. Here it is what we're trying to output:
13510 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
13511 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
13513 haddpd %xmm0, %xmm0
13515 pshufd $0x4e, %xmm0, %xmm1
13521 LLVMContext *Context = DAG.getContext();
13523 // Build some magic constants.
13524 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
13525 Constant *C0 = ConstantDataVector::get(*Context, CV0);
13526 auto PtrVT = getPointerTy(DAG.getDataLayout());
13527 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
13529 SmallVector<Constant*,2> CV1;
13531 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
13532 APInt(64, 0x4330000000000000ULL))));
13534 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
13535 APInt(64, 0x4530000000000000ULL))));
13536 Constant *C1 = ConstantVector::get(CV1);
13537 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
13539 // Load the 64-bit value into an XMM register.
13540 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
13543 DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
13544 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13545 /* Alignment = */ 16);
13547 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
13550 DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
13551 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13552 /* Alignment = */ 16);
13553 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
13554 // TODO: Are there any fast-math-flags to propagate here?
13555 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
13558 if (Subtarget.hasSSE3()) {
13559 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
13560 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
13562 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
13563 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
13565 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
13566 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
13569 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
13570 DAG.getIntPtrConstant(0, dl));
13573 /// 32-bit unsigned integer to float expansion.
13574 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
13575 SelectionDAG &DAG) const {
13577 // FP constant to bias correct the final result.
13578 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
13581 // Load the 32-bit value into an XMM register.
13582 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
13585 // Zero out the upper parts of the register.
13586 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
13588 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13589 DAG.getBitcast(MVT::v2f64, Load),
13590 DAG.getIntPtrConstant(0, dl));
13592 // Or the load with the bias.
13593 SDValue Or = DAG.getNode(
13594 ISD::OR, dl, MVT::v2i64,
13595 DAG.getBitcast(MVT::v2i64,
13596 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
13597 DAG.getBitcast(MVT::v2i64,
13598 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
13600 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13601 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
13603 // Subtract the bias.
13604 // TODO: Are there any fast-math-flags to propagate here?
13605 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
13607 // Handle final rounding.
13608 MVT DestVT = Op.getSimpleValueType();
13610 if (DestVT.bitsLT(MVT::f64))
13611 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
13612 DAG.getIntPtrConstant(0, dl));
13613 if (DestVT.bitsGT(MVT::f64))
13614 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
13616 // Handle final rounding.
13620 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
13621 const X86Subtarget &Subtarget) {
13622 // The algorithm is the following:
13623 // #ifdef __SSE4_1__
13624 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
13625 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
13626 // (uint4) 0x53000000, 0xaa);
13628 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13629 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
13631 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13632 // return (float4) lo + fhi;
13634 // We shouldn't use it when unsafe-fp-math is enabled though: we might later
13635 // reassociate the two FADDs, and if we do that, the algorithm fails
13636 // spectacularly (PR24512).
13637 // FIXME: If we ever have some kind of Machine FMF, this should be marked
13638 // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
13639 // there's also the MachineCombiner reassociations happening on Machine IR.
13640 if (DAG.getTarget().Options.UnsafeFPMath)
13644 SDValue V = Op->getOperand(0);
13645 MVT VecIntVT = V.getSimpleValueType();
13646 bool Is128 = VecIntVT == MVT::v4i32;
13647 MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
13648 // If we convert to something else than the supported type, e.g., to v4f64,
13650 if (VecFloatVT != Op->getSimpleValueType(0))
13653 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
13654 "Unsupported custom type");
13656 // In the #idef/#else code, we have in common:
13657 // - The vector of constants:
13663 // Create the splat vector for 0x4b000000.
13664 SDValue VecCstLow = DAG.getConstant(0x4b000000, DL, VecIntVT);
13665 // Create the splat vector for 0x53000000.
13666 SDValue VecCstHigh = DAG.getConstant(0x53000000, DL, VecIntVT);
13668 // Create the right shift.
13669 SDValue VecCstShift = DAG.getConstant(16, DL, VecIntVT);
13670 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
13673 if (Subtarget.hasSSE41()) {
13674 MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
13675 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
13676 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
13677 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
13678 // Low will be bitcasted right away, so do not bother bitcasting back to its
13680 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
13681 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
13682 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
13683 // (uint4) 0x53000000, 0xaa);
13684 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
13685 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
13686 // High will be bitcasted right away, so do not bother bitcasting back to
13687 // its original type.
13688 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
13689 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
13691 SDValue VecCstMask = DAG.getConstant(0xffff, DL, VecIntVT);
13692 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
13693 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
13694 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
13696 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
13697 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
13700 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
13701 SDValue VecCstFAdd = DAG.getConstantFP(
13702 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, VecFloatVT);
13704 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
13705 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
13706 // TODO: Are there any fast-math-flags to propagate here?
13708 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
13709 // return (float4) lo + fhi;
13710 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
13711 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
13714 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
13715 SelectionDAG &DAG) const {
13716 SDValue N0 = Op.getOperand(0);
13717 MVT SVT = N0.getSimpleValueType();
13720 if (SVT.getVectorElementType() == MVT::i1) {
13721 if (SVT == MVT::v2i1)
13722 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
13723 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64, N0));
13724 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
13725 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
13726 DAG.getNode(ISD::ZERO_EXTEND, dl, IntegerVT, N0));
13729 switch (SVT.SimpleTy) {
13731 llvm_unreachable("Custom UINT_TO_FP is not supported!");
13736 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
13737 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
13738 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
13742 return lowerUINT_TO_FP_vXi32(Op, DAG, Subtarget);
13745 assert(Subtarget.hasAVX512());
13746 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
13747 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
13751 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
13752 SelectionDAG &DAG) const {
13753 SDValue N0 = Op.getOperand(0);
13755 auto PtrVT = getPointerTy(DAG.getDataLayout());
13757 if (Op.getSimpleValueType().isVector())
13758 return lowerUINT_TO_FP_vec(Op, DAG);
13760 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
13761 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
13762 // the optimization here.
13763 if (DAG.SignBitIsZero(N0))
13764 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
13766 MVT SrcVT = N0.getSimpleValueType();
13767 MVT DstVT = Op.getSimpleValueType();
13769 if (Subtarget.hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
13770 (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget.is64Bit()))) {
13771 // Conversions from unsigned i32 to f32/f64 are legal,
13772 // using VCVTUSI2SS/SD. Same for i64 in 64-bit mode.
13776 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13777 return LowerUINT_TO_FP_i64(Op, DAG);
13778 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13779 return LowerUINT_TO_FP_i32(Op, DAG);
13780 if (Subtarget.is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13783 // Make a 64-bit buffer, and use it to build an FILD.
13784 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13785 if (SrcVT == MVT::i32) {
13786 SDValue OffsetSlot = DAG.getMemBasePlusOffset(StackSlot, 4, dl);
13787 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13788 StackSlot, MachinePointerInfo());
13789 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
13790 OffsetSlot, MachinePointerInfo());
13791 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13795 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13796 SDValue ValueToStore = Op.getOperand(0);
13797 if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget.is64Bit())
13798 // Bitcasting to f64 here allows us to do a single 64-bit store from
13799 // an SSE register, avoiding the store forwarding penalty that would come
13800 // with two 32-bit stores.
13801 ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
13802 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, ValueToStore, StackSlot,
13803 MachinePointerInfo());
13804 // For i64 source, we need to add the appropriate power of 2 if the input
13805 // was negative. This is the same as the optimization in
13806 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13807 // we must be careful to do the computation in x87 extended precision, not
13808 // in SSE. (The generic code can't know it's OK to do this, or how to.)
13809 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13810 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
13811 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
13812 MachineMemOperand::MOLoad, 8, 8);
13814 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13815 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13816 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13819 APInt FF(32, 0x5F800000ULL);
13821 // Check whether the sign bit is set.
13822 SDValue SignSet = DAG.getSetCC(
13823 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
13824 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
13826 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13827 SDValue FudgePtr = DAG.getConstantPool(
13828 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
13830 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13831 SDValue Zero = DAG.getIntPtrConstant(0, dl);
13832 SDValue Four = DAG.getIntPtrConstant(4, dl);
13833 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13835 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
13837 // Load the value out, extending it from f32 to f80.
13838 // FIXME: Avoid the extend by constructing the right constant pool?
13839 SDValue Fudge = DAG.getExtLoad(
13840 ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
13841 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
13842 /* Alignment = */ 4);
13843 // Extend everything to 80 bits to force it to be done on x87.
13844 // TODO: Are there any fast-math-flags to propagate here?
13845 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
13846 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
13847 DAG.getIntPtrConstant(0, dl));
13850 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
13851 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
13852 // just return an <SDValue(), SDValue()> pair.
13853 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
13854 // to i16, i32 or i64, and we lower it to a legal sequence.
13855 // If lowered to the final integer result we return a <result, SDValue()> pair.
13856 // Otherwise we lower it to a sequence ending with a FIST, return a
13857 // <FIST, StackSlot> pair, and the caller is responsible for loading
13858 // the final integer result from StackSlot.
13859 std::pair<SDValue,SDValue>
13860 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
13861 bool IsSigned, bool IsReplace) const {
13864 EVT DstTy = Op.getValueType();
13865 EVT TheVT = Op.getOperand(0).getValueType();
13866 auto PtrVT = getPointerTy(DAG.getDataLayout());
13868 if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
13869 // f16 must be promoted before using the lowering in this routine.
13870 // fp128 does not use this lowering.
13871 return std::make_pair(SDValue(), SDValue());
13874 // If using FIST to compute an unsigned i64, we'll need some fixup
13875 // to handle values above the maximum signed i64. A FIST is always
13876 // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
13877 bool UnsignedFixup = !IsSigned &&
13878 DstTy == MVT::i64 &&
13879 (!Subtarget.is64Bit() ||
13880 !isScalarFPTypeInSSEReg(TheVT));
13882 if (!IsSigned && DstTy != MVT::i64 && !Subtarget.hasAVX512()) {
13883 // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
13884 // The low 32 bits of the fist result will have the correct uint32 result.
13885 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
13889 assert(DstTy.getSimpleVT() <= MVT::i64 &&
13890 DstTy.getSimpleVT() >= MVT::i16 &&
13891 "Unknown FP_TO_INT to lower!");
13893 // These are really Legal.
13894 if (DstTy == MVT::i32 &&
13895 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13896 return std::make_pair(SDValue(), SDValue());
13897 if (Subtarget.is64Bit() &&
13898 DstTy == MVT::i64 &&
13899 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13900 return std::make_pair(SDValue(), SDValue());
13902 // We lower FP->int64 into FISTP64 followed by a load from a temporary
13904 MachineFunction &MF = DAG.getMachineFunction();
13905 unsigned MemSize = DstTy.getSizeInBits()/8;
13906 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13907 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13910 switch (DstTy.getSimpleVT().SimpleTy) {
13911 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
13912 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
13913 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
13914 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
13917 SDValue Chain = DAG.getEntryNode();
13918 SDValue Value = Op.getOperand(0);
13919 SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
13921 if (UnsignedFixup) {
13923 // Conversion to unsigned i64 is implemented with a select,
13924 // depending on whether the source value fits in the range
13925 // of a signed i64. Let Thresh be the FP equivalent of
13926 // 0x8000000000000000ULL.
13928 // Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
13929 // FistSrc = (Value < Thresh) ? Value : (Value - Thresh);
13930 // Fist-to-mem64 FistSrc
13931 // Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
13932 // to XOR'ing the high 32 bits with Adjust.
13934 // Being a power of 2, Thresh is exactly representable in all FP formats.
13935 // For X87 we'd like to use the smallest FP type for this constant, but
13936 // for DAG type consistency we have to match the FP operand type.
13938 APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
13939 LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
13940 bool LosesInfo = false;
13941 if (TheVT == MVT::f64)
13942 // The rounding mode is irrelevant as the conversion should be exact.
13943 Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
13945 else if (TheVT == MVT::f80)
13946 Status = Thresh.convert(APFloat::x87DoubleExtended,
13947 APFloat::rmNearestTiesToEven, &LosesInfo);
13949 assert(Status == APFloat::opOK && !LosesInfo &&
13950 "FP conversion should have been exact");
13952 SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
13954 SDValue Cmp = DAG.getSetCC(DL,
13955 getSetCCResultType(DAG.getDataLayout(),
13956 *DAG.getContext(), TheVT),
13957 Value, ThreshVal, ISD::SETLT);
13958 Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
13959 DAG.getConstant(0, DL, MVT::i32),
13960 DAG.getConstant(0x80000000, DL, MVT::i32));
13961 SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
13962 Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
13963 *DAG.getContext(), TheVT),
13964 Value, ThreshVal, ISD::SETLT);
13965 Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
13968 // FIXME This causes a redundant load/store if the SSE-class value is already
13969 // in memory, such as if it is on the callstack.
13970 if (isScalarFPTypeInSSEReg(TheVT)) {
13971 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
13972 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
13973 MachinePointerInfo::getFixedStack(MF, SSFI));
13974 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
13976 Chain, StackSlot, DAG.getValueType(TheVT)
13979 MachineMemOperand *MMO =
13980 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13981 MachineMemOperand::MOLoad, MemSize, MemSize);
13982 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
13983 Chain = Value.getValue(1);
13984 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13985 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13988 MachineMemOperand *MMO =
13989 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13990 MachineMemOperand::MOStore, MemSize, MemSize);
13992 if (UnsignedFixup) {
13994 // Insert the FIST, load its result as two i32's,
13995 // and XOR the high i32 with Adjust.
13997 SDValue FistOps[] = { Chain, Value, StackSlot };
13998 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13999 FistOps, DstTy, MMO);
14002 DAG.getLoad(MVT::i32, DL, FIST, StackSlot, MachinePointerInfo());
14003 SDValue HighAddr = DAG.getMemBasePlusOffset(StackSlot, 4, DL);
14006 DAG.getLoad(MVT::i32, DL, FIST, HighAddr, MachinePointerInfo());
14007 High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
14009 if (Subtarget.is64Bit()) {
14010 // Join High32 and Low32 into a 64-bit result.
14011 // (High32 << 32) | Low32
14012 Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
14013 High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
14014 High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
14015 DAG.getConstant(32, DL, MVT::i8));
14016 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
14017 return std::make_pair(Result, SDValue());
14020 SDValue ResultOps[] = { Low32, High32 };
14022 SDValue pair = IsReplace
14023 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
14024 : DAG.getMergeValues(ResultOps, DL);
14025 return std::make_pair(pair, SDValue());
14027 // Build the FP_TO_INT*_IN_MEM
14028 SDValue Ops[] = { Chain, Value, StackSlot };
14029 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
14031 return std::make_pair(FIST, StackSlot);
14035 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
14036 const X86Subtarget &Subtarget) {
14037 MVT VT = Op->getSimpleValueType(0);
14038 SDValue In = Op->getOperand(0);
14039 MVT InVT = In.getSimpleValueType();
14042 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14043 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
14045 // Optimize vectors in AVX mode:
14048 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
14049 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
14050 // Concat upper and lower parts.
14053 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
14054 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
14055 // Concat upper and lower parts.
14058 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
14059 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
14060 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
14063 if (Subtarget.hasInt256())
14064 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
14066 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
14067 SDValue Undef = DAG.getUNDEF(InVT);
14068 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
14069 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
14070 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
14072 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
14073 VT.getVectorNumElements()/2);
14075 OpLo = DAG.getBitcast(HVT, OpLo);
14076 OpHi = DAG.getBitcast(HVT, OpHi);
14078 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14081 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
14082 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
14083 MVT VT = Op->getSimpleValueType(0);
14084 SDValue In = Op->getOperand(0);
14085 MVT InVT = In.getSimpleValueType();
14087 unsigned int NumElts = VT.getVectorNumElements();
14088 if (NumElts != 8 && NumElts != 16 && !Subtarget.hasBWI())
14091 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
14092 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
14094 assert(InVT.getVectorElementType() == MVT::i1);
14096 // Extend VT if the target is 256 or 128bit vector and VLX is not supported.
14098 if (!VT.is512BitVector() && !Subtarget.hasVLX())
14099 ExtVT = MVT::getVectorVT(MVT::getIntegerVT(512/NumElts), NumElts);
14102 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
14104 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
14106 SDValue SelectedVal = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
14108 return SelectedVal;
14109 return DAG.getNode(X86ISD::VTRUNC, DL, VT, SelectedVal);
14112 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
14113 SelectionDAG &DAG) {
14114 if (Subtarget.hasFp256())
14115 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
14121 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
14122 SelectionDAG &DAG) {
14124 MVT VT = Op.getSimpleValueType();
14125 SDValue In = Op.getOperand(0);
14126 MVT SVT = In.getSimpleValueType();
14128 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
14129 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
14131 if (Subtarget.hasFp256())
14132 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
14135 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
14136 VT.getVectorNumElements() != SVT.getVectorNumElements());
14140 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
14141 const X86Subtarget &Subtarget) {
14144 MVT VT = Op.getSimpleValueType();
14145 SDValue In = Op.getOperand(0);
14146 MVT InVT = In.getSimpleValueType();
14148 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type.");
14150 // Shift LSB to MSB and use VPMOVB/W2M or TESTD/Q.
14151 unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
14152 if (InVT.getScalarSizeInBits() <= 16) {
14153 if (Subtarget.hasBWI()) {
14154 // legal, will go to VPMOVB2M, VPMOVW2M
14155 // Shift packed bytes not supported natively, bitcast to word
14156 MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
14157 SDValue ShiftNode = DAG.getNode(ISD::SHL, DL, ExtVT,
14158 DAG.getBitcast(ExtVT, In),
14159 DAG.getConstant(ShiftInx, DL, ExtVT));
14160 ShiftNode = DAG.getBitcast(InVT, ShiftNode);
14161 return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
14163 // Use TESTD/Q, extended vector to packed dword/qword.
14164 assert((InVT.is256BitVector() || InVT.is128BitVector()) &&
14165 "Unexpected vector type.");
14166 unsigned NumElts = InVT.getVectorNumElements();
14167 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(512/NumElts), NumElts);
14168 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
14170 ShiftInx = InVT.getScalarSizeInBits() - 1;
14173 SDValue ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
14174 DAG.getConstant(ShiftInx, DL, InVT));
14175 return DAG.getNode(X86ISD::TESTM, DL, VT, ShiftNode, ShiftNode);
14178 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
14180 MVT VT = Op.getSimpleValueType();
14181 SDValue In = Op.getOperand(0);
14182 MVT InVT = In.getSimpleValueType();
14184 if (VT == MVT::i1) {
14185 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
14186 "Invalid scalar TRUNCATE operation");
14187 if (InVT.getSizeInBits() >= 32)
14189 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
14190 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
14192 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
14193 "Invalid TRUNCATE operation");
14195 if (VT.getVectorElementType() == MVT::i1)
14196 return LowerTruncateVecI1(Op, DAG, Subtarget);
14198 // vpmovqb/w/d, vpmovdb/w, vpmovwb
14199 if (Subtarget.hasAVX512()) {
14200 // word to byte only under BWI
14201 if (InVT == MVT::v16i16 && !Subtarget.hasBWI()) // v16i16 -> v16i8
14202 return DAG.getNode(X86ISD::VTRUNC, DL, VT,
14203 DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
14204 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
14206 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
14207 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
14208 if (Subtarget.hasInt256()) {
14209 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14210 In = DAG.getBitcast(MVT::v8i32, In);
14211 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
14213 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
14214 DAG.getIntPtrConstant(0, DL));
14217 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14218 DAG.getIntPtrConstant(0, DL));
14219 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14220 DAG.getIntPtrConstant(2, DL));
14221 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
14222 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
14223 static const int ShufMask[] = {0, 2, 4, 6};
14224 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
14227 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
14228 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
14229 if (Subtarget.hasInt256()) {
14230 In = DAG.getBitcast(MVT::v32i8, In);
14232 SmallVector<SDValue,32> pshufbMask;
14233 for (unsigned i = 0; i < 2; ++i) {
14234 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
14235 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
14236 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
14237 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
14238 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
14239 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
14240 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
14241 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
14242 for (unsigned j = 0; j < 8; ++j)
14243 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
14245 SDValue BV = DAG.getBuildVector(MVT::v32i8, DL, pshufbMask);
14246 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
14247 In = DAG.getBitcast(MVT::v4i64, In);
14249 static const int ShufMask[] = {0, 2, -1, -1};
14250 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
14252 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
14253 DAG.getIntPtrConstant(0, DL));
14254 return DAG.getBitcast(VT, In);
14257 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
14258 DAG.getIntPtrConstant(0, DL));
14260 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
14261 DAG.getIntPtrConstant(4, DL));
14263 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
14264 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
14266 // The PSHUFB mask:
14267 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
14268 -1, -1, -1, -1, -1, -1, -1, -1};
14270 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14271 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
14272 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
14274 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
14275 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
14277 // The MOVLHPS Mask:
14278 static const int ShufMask2[] = {0, 1, 4, 5};
14279 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
14280 return DAG.getBitcast(MVT::v8i16, res);
14283 // Handle truncation of V256 to V128 using shuffles.
14284 if (!VT.is128BitVector() || !InVT.is256BitVector())
14287 assert(Subtarget.hasFp256() && "256-bit vector without AVX!");
14289 unsigned NumElems = VT.getVectorNumElements();
14290 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
14292 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
14293 // Prepare truncation shuffle mask
14294 for (unsigned i = 0; i != NumElems; ++i)
14295 MaskVec[i] = i * 2;
14296 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
14297 DAG.getUNDEF(NVT), MaskVec);
14298 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
14299 DAG.getIntPtrConstant(0, DL));
14302 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
14303 SelectionDAG &DAG) const {
14304 assert(!Op.getSimpleValueType().isVector());
14306 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
14307 /*IsSigned=*/ true, /*IsReplace=*/ false);
14308 SDValue FIST = Vals.first, StackSlot = Vals.second;
14309 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
14310 if (!FIST.getNode())
14313 if (StackSlot.getNode())
14314 // Load the result.
14315 return DAG.getLoad(Op.getValueType(), SDLoc(Op), FIST, StackSlot,
14316 MachinePointerInfo());
14318 // The node is the result.
14322 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
14323 SelectionDAG &DAG) const {
14324 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
14325 /*IsSigned=*/ false, /*IsReplace=*/ false);
14326 SDValue FIST = Vals.first, StackSlot = Vals.second;
14327 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
14328 if (!FIST.getNode())
14331 if (StackSlot.getNode())
14332 // Load the result.
14333 return DAG.getLoad(Op.getValueType(), SDLoc(Op), FIST, StackSlot,
14334 MachinePointerInfo());
14336 // The node is the result.
14340 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
14342 MVT VT = Op.getSimpleValueType();
14343 SDValue In = Op.getOperand(0);
14344 MVT SVT = In.getSimpleValueType();
14346 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
14348 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
14349 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
14350 In, DAG.getUNDEF(SVT)));
14353 /// The only differences between FABS and FNEG are the mask and the logic op.
14354 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
14355 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
14356 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
14357 "Wrong opcode for lowering FABS or FNEG.");
14359 bool IsFABS = (Op.getOpcode() == ISD::FABS);
14361 // If this is a FABS and it has an FNEG user, bail out to fold the combination
14362 // into an FNABS. We'll lower the FABS after that if it is still in use.
14364 for (SDNode *User : Op->uses())
14365 if (User->getOpcode() == ISD::FNEG)
14369 MVT VT = Op.getSimpleValueType();
14371 bool IsF128 = (VT == MVT::f128);
14373 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
14374 // decide if we should generate a 16-byte constant mask when we only need 4 or
14375 // 8 bytes for the scalar case.
14381 if (VT.isVector()) {
14383 EltVT = VT.getVectorElementType();
14384 NumElts = VT.getVectorNumElements();
14385 } else if (IsF128) {
14386 // SSE instructions are used for optimized f128 logical operations.
14387 LogicVT = MVT::f128;
14391 // There are no scalar bitwise logical SSE/AVX instructions, so we
14392 // generate a 16-byte vector constant and logic op even for the scalar case.
14393 // Using a 16-byte mask allows folding the load of the mask with
14394 // the logic op, so it can save (~4 bytes) on code size.
14395 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
14397 NumElts = (VT == MVT::f64) ? 2 : 4;
14400 unsigned EltBits = EltVT.getSizeInBits();
14401 LLVMContext *Context = DAG.getContext();
14402 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
14404 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
14405 Constant *C = ConstantInt::get(*Context, MaskElt);
14406 C = ConstantVector::getSplat(NumElts, C);
14407 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14408 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
14409 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
14410 SDValue Mask = DAG.getLoad(
14411 LogicVT, dl, DAG.getEntryNode(), CPIdx,
14412 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Alignment);
14414 SDValue Op0 = Op.getOperand(0);
14415 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
14417 IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
14418 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
14420 if (VT.isVector() || IsF128)
14421 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
14423 // For the scalar case extend to a 128-bit vector, perform the logic op,
14424 // and extract the scalar result back out.
14425 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
14426 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
14427 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
14428 DAG.getIntPtrConstant(0, dl));
14431 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
14432 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14433 LLVMContext *Context = DAG.getContext();
14434 SDValue Op0 = Op.getOperand(0);
14435 SDValue Op1 = Op.getOperand(1);
14437 MVT VT = Op.getSimpleValueType();
14438 MVT SrcVT = Op1.getSimpleValueType();
14439 bool IsF128 = (VT == MVT::f128);
14441 // If second operand is smaller, extend it first.
14442 if (SrcVT.bitsLT(VT)) {
14443 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
14446 // And if it is bigger, shrink it first.
14447 if (SrcVT.bitsGT(VT)) {
14448 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
14452 // At this point the operands and the result should have the same
14453 // type, and that won't be f80 since that is not custom lowered.
14454 assert((VT == MVT::f64 || VT == MVT::f32 || IsF128) &&
14455 "Unexpected type in LowerFCOPYSIGN");
14457 const fltSemantics &Sem =
14458 VT == MVT::f64 ? APFloat::IEEEdouble :
14459 (IsF128 ? APFloat::IEEEquad : APFloat::IEEEsingle);
14460 const unsigned SizeInBits = VT.getSizeInBits();
14462 SmallVector<Constant *, 4> CV(
14463 VT == MVT::f64 ? 2 : (IsF128 ? 1 : 4),
14464 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
14466 // First, clear all bits but the sign bit from the second operand (sign).
14467 CV[0] = ConstantFP::get(*Context,
14468 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
14469 Constant *C = ConstantVector::get(CV);
14470 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
14471 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
14473 // Perform all logic operations as 16-byte vectors because there are no
14474 // scalar FP logic instructions in SSE. This allows load folding of the
14475 // constants into the logic instructions.
14476 MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : (IsF128 ? MVT::f128 : MVT::v4f32);
14478 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
14479 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14480 /* Alignment = */ 16);
14482 Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
14483 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
14485 // Next, clear the sign bit from the first operand (magnitude).
14486 // If it's a constant, we can clear it here.
14487 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
14488 APFloat APF = Op0CN->getValueAPF();
14489 // If the magnitude is a positive zero, the sign bit alone is enough.
14490 if (APF.isPosZero())
14491 return IsF128 ? SignBit :
14492 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
14493 DAG.getIntPtrConstant(0, dl));
14495 CV[0] = ConstantFP::get(*Context, APF);
14497 CV[0] = ConstantFP::get(
14499 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
14501 C = ConstantVector::get(CV);
14502 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
14504 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
14505 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
14506 /* Alignment = */ 16);
14507 // If the magnitude operand wasn't a constant, we need to AND out the sign.
14508 if (!isa<ConstantFPSDNode>(Op0)) {
14510 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
14511 Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
14513 // OR the magnitude value with the sign bit.
14514 Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
14515 return IsF128 ? Val :
14516 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
14517 DAG.getIntPtrConstant(0, dl));
14520 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
14521 SDValue N0 = Op.getOperand(0);
14523 MVT VT = Op.getSimpleValueType();
14525 MVT OpVT = N0.getSimpleValueType();
14526 assert((OpVT == MVT::f32 || OpVT == MVT::f64) &&
14527 "Unexpected type for FGETSIGN");
14529 // Lower ISD::FGETSIGN to (AND (X86ISD::MOVMSK ...) 1).
14530 MVT VecVT = (OpVT == MVT::f32 ? MVT::v4f32 : MVT::v2f64);
14531 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, N0);
14532 Res = DAG.getNode(X86ISD::MOVMSK, dl, MVT::i32, Res);
14533 Res = DAG.getZExtOrTrunc(Res, dl, VT);
14534 Res = DAG.getNode(ISD::AND, dl, VT, Res, DAG.getConstant(1, dl, VT));
14538 // Check whether an OR'd tree is PTEST-able.
14539 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget &Subtarget,
14540 SelectionDAG &DAG) {
14541 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
14543 if (!Subtarget.hasSSE41())
14546 if (!Op->hasOneUse())
14549 SDNode *N = Op.getNode();
14552 SmallVector<SDValue, 8> Opnds;
14553 DenseMap<SDValue, unsigned> VecInMap;
14554 SmallVector<SDValue, 8> VecIns;
14555 EVT VT = MVT::Other;
14557 // Recognize a special case where a vector is casted into wide integer to
14559 Opnds.push_back(N->getOperand(0));
14560 Opnds.push_back(N->getOperand(1));
14562 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14563 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
14564 // BFS traverse all OR'd operands.
14565 if (I->getOpcode() == ISD::OR) {
14566 Opnds.push_back(I->getOperand(0));
14567 Opnds.push_back(I->getOperand(1));
14568 // Re-evaluate the number of nodes to be traversed.
14569 e += 2; // 2 more nodes (LHS and RHS) are pushed.
14573 // Quit if a non-EXTRACT_VECTOR_ELT
14574 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14577 // Quit if without a constant index.
14578 SDValue Idx = I->getOperand(1);
14579 if (!isa<ConstantSDNode>(Idx))
14582 SDValue ExtractedFromVec = I->getOperand(0);
14583 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
14584 if (M == VecInMap.end()) {
14585 VT = ExtractedFromVec.getValueType();
14586 // Quit if not 128/256-bit vector.
14587 if (!VT.is128BitVector() && !VT.is256BitVector())
14589 // Quit if not the same type.
14590 if (VecInMap.begin() != VecInMap.end() &&
14591 VT != VecInMap.begin()->first.getValueType())
14593 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
14594 VecIns.push_back(ExtractedFromVec);
14596 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14599 assert((VT.is128BitVector() || VT.is256BitVector()) &&
14600 "Not extracted from 128-/256-bit vector.");
14602 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
14604 for (DenseMap<SDValue, unsigned>::const_iterator
14605 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
14606 // Quit if not all elements are used.
14607 if (I->second != FullMask)
14611 MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
14613 // Cast all vectors into TestVT for PTEST.
14614 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
14615 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
14617 // If more than one full vectors are evaluated, OR them first before PTEST.
14618 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
14619 // Each iteration will OR 2 nodes and append the result until there is only
14620 // 1 node left, i.e. the final OR'd value of all vectors.
14621 SDValue LHS = VecIns[Slot];
14622 SDValue RHS = VecIns[Slot + 1];
14623 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
14626 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
14627 VecIns.back(), VecIns.back());
14630 /// \brief return true if \c Op has a use that doesn't just read flags.
14631 static bool hasNonFlagsUse(SDValue Op) {
14632 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
14634 SDNode *User = *UI;
14635 unsigned UOpNo = UI.getOperandNo();
14636 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
14637 // Look pass truncate.
14638 UOpNo = User->use_begin().getOperandNo();
14639 User = *User->use_begin();
14642 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
14643 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
14649 // Emit KTEST instruction for bit vectors on AVX-512
14650 static SDValue EmitKTEST(SDValue Op, SelectionDAG &DAG,
14651 const X86Subtarget &Subtarget) {
14652 if (Op.getOpcode() == ISD::BITCAST) {
14653 auto hasKTEST = [&](MVT VT) {
14654 unsigned SizeInBits = VT.getSizeInBits();
14655 return (Subtarget.hasDQI() && (SizeInBits == 8 || SizeInBits == 16)) ||
14656 (Subtarget.hasBWI() && (SizeInBits == 32 || SizeInBits == 64));
14658 SDValue Op0 = Op.getOperand(0);
14659 MVT Op0VT = Op0.getValueType().getSimpleVT();
14660 if (Op0VT.isVector() && Op0VT.getVectorElementType() == MVT::i1 &&
14662 return DAG.getNode(X86ISD::KTEST, SDLoc(Op), Op0VT, Op0, Op0);
14667 /// Emit nodes that will be selected as "test Op0,Op0", or something
14669 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, const SDLoc &dl,
14670 SelectionDAG &DAG) const {
14671 if (Op.getValueType() == MVT::i1) {
14672 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
14673 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
14674 DAG.getConstant(0, dl, MVT::i8));
14676 // CF and OF aren't always set the way we want. Determine which
14677 // of these we need.
14678 bool NeedCF = false;
14679 bool NeedOF = false;
14682 case X86::COND_A: case X86::COND_AE:
14683 case X86::COND_B: case X86::COND_BE:
14686 case X86::COND_G: case X86::COND_GE:
14687 case X86::COND_L: case X86::COND_LE:
14688 case X86::COND_O: case X86::COND_NO: {
14689 // Check if we really need to set the
14690 // Overflow flag. If NoSignedWrap is present
14691 // that is not actually needed.
14692 switch (Op->getOpcode()) {
14697 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
14698 if (BinNode->Flags.hasNoSignedWrap())
14708 // See if we can use the EFLAGS value from the operand instead of
14709 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
14710 // we prove that the arithmetic won't overflow, we can't use OF or CF.
14711 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
14712 // Emit KTEST for bit vectors
14713 if (auto Node = EmitKTEST(Op, DAG, Subtarget))
14715 // Emit a CMP with 0, which is the TEST pattern.
14716 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14717 DAG.getConstant(0, dl, Op.getValueType()));
14719 unsigned Opcode = 0;
14720 unsigned NumOperands = 0;
14722 // Truncate operations may prevent the merge of the SETCC instruction
14723 // and the arithmetic instruction before it. Attempt to truncate the operands
14724 // of the arithmetic instruction and use a reduced bit-width instruction.
14725 bool NeedTruncation = false;
14726 SDValue ArithOp = Op;
14727 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
14728 SDValue Arith = Op->getOperand(0);
14729 // Both the trunc and the arithmetic op need to have one user each.
14730 if (Arith->hasOneUse())
14731 switch (Arith.getOpcode()) {
14738 NeedTruncation = true;
14744 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
14745 // which may be the result of a CAST. We use the variable 'Op', which is the
14746 // non-casted variable when we check for possible users.
14747 switch (ArithOp.getOpcode()) {
14749 // Due to an isel shortcoming, be conservative if this add is likely to be
14750 // selected as part of a load-modify-store instruction. When the root node
14751 // in a match is a store, isel doesn't know how to remap non-chain non-flag
14752 // uses of other nodes in the match, such as the ADD in this case. This
14753 // leads to the ADD being left around and reselected, with the result being
14754 // two adds in the output. Alas, even if none our users are stores, that
14755 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
14756 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
14757 // climbing the DAG back to the root, and it doesn't seem to be worth the
14759 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14760 UE = Op.getNode()->use_end(); UI != UE; ++UI)
14761 if (UI->getOpcode() != ISD::CopyToReg &&
14762 UI->getOpcode() != ISD::SETCC &&
14763 UI->getOpcode() != ISD::STORE)
14766 if (ConstantSDNode *C =
14767 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
14768 // An add of one will be selected as an INC.
14769 if (C->isOne() && !Subtarget.slowIncDec()) {
14770 Opcode = X86ISD::INC;
14775 // An add of negative one (subtract of one) will be selected as a DEC.
14776 if (C->isAllOnesValue() && !Subtarget.slowIncDec()) {
14777 Opcode = X86ISD::DEC;
14783 // Otherwise use a regular EFLAGS-setting add.
14784 Opcode = X86ISD::ADD;
14789 // If we have a constant logical shift that's only used in a comparison
14790 // against zero turn it into an equivalent AND. This allows turning it into
14791 // a TEST instruction later.
14792 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14793 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14794 EVT VT = Op.getValueType();
14795 unsigned BitWidth = VT.getSizeInBits();
14796 unsigned ShAmt = Op->getConstantOperandVal(1);
14797 if (ShAmt >= BitWidth) // Avoid undefined shifts.
14799 APInt Mask = ArithOp.getOpcode() == ISD::SRL
14800 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14801 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14802 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14804 Op = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14805 DAG.getConstant(Mask, dl, VT));
14810 // If the primary 'and' result isn't used, don't bother using X86ISD::AND,
14811 // because a TEST instruction will be better.
14812 if (!hasNonFlagsUse(Op)) {
14813 SDValue Op0 = ArithOp->getOperand(0);
14814 SDValue Op1 = ArithOp->getOperand(1);
14815 EVT VT = ArithOp.getValueType();
14816 bool isAndn = isBitwiseNot(Op0) || isBitwiseNot(Op1);
14817 bool isLegalAndnType = VT == MVT::i32 || VT == MVT::i64;
14819 // But if we can combine this into an ANDN operation, then create an AND
14820 // now and allow it to be pattern matched into an ANDN.
14821 if (!Subtarget.hasBMI() || !isAndn || !isLegalAndnType)
14828 // Due to the ISEL shortcoming noted above, be conservative if this op is
14829 // likely to be selected as part of a load-modify-store instruction.
14830 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14831 UE = Op.getNode()->use_end(); UI != UE; ++UI)
14832 if (UI->getOpcode() == ISD::STORE)
14835 // Otherwise use a regular EFLAGS-setting instruction.
14836 switch (ArithOp.getOpcode()) {
14837 default: llvm_unreachable("unexpected operator!");
14838 case ISD::SUB: Opcode = X86ISD::SUB; break;
14839 case ISD::XOR: Opcode = X86ISD::XOR; break;
14840 case ISD::AND: Opcode = X86ISD::AND; break;
14842 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14843 if (SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG))
14846 Opcode = X86ISD::OR;
14860 return SDValue(Op.getNode(), 1);
14866 // If we found that truncation is beneficial, perform the truncation and
14868 if (NeedTruncation) {
14869 EVT VT = Op.getValueType();
14870 SDValue WideVal = Op->getOperand(0);
14871 EVT WideVT = WideVal.getValueType();
14872 unsigned ConvertedOp = 0;
14873 // Use a target machine opcode to prevent further DAGCombine
14874 // optimizations that may separate the arithmetic operations
14875 // from the setcc node.
14876 switch (WideVal.getOpcode()) {
14878 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14879 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14880 case ISD::AND: ConvertedOp = X86ISD::AND; break;
14881 case ISD::OR: ConvertedOp = X86ISD::OR; break;
14882 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14886 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14887 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14888 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14889 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14890 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14896 // Emit KTEST for bit vectors
14897 if (auto Node = EmitKTEST(Op, DAG, Subtarget))
14900 // Emit a CMP with 0, which is the TEST pattern.
14901 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14902 DAG.getConstant(0, dl, Op.getValueType()));
14904 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14905 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
14907 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14908 DAG.ReplaceAllUsesWith(Op, New);
14909 return SDValue(New.getNode(), 1);
14912 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14914 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14915 const SDLoc &dl, SelectionDAG &DAG) const {
14916 if (isNullConstant(Op1))
14917 return EmitTest(Op0, X86CC, dl, DAG);
14919 assert(!(isa<ConstantSDNode>(Op1) && Op0.getValueType() == MVT::i1) &&
14920 "Unexpected comparison operation for MVT::i1 operands");
14922 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14923 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14924 // Only promote the compare up to I32 if it is a 16 bit operation
14925 // with an immediate. 16 bit immediates are to be avoided.
14926 if ((Op0.getValueType() == MVT::i16 &&
14927 (isa<ConstantSDNode>(Op0) || isa<ConstantSDNode>(Op1))) &&
14928 !DAG.getMachineFunction().getFunction()->optForMinSize() &&
14929 !Subtarget.isAtom()) {
14930 unsigned ExtendOp =
14931 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14932 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14933 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14935 // Use SUB instead of CMP to enable CSE between SUB and CMP.
14936 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14937 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14939 return SDValue(Sub.getNode(), 1);
14941 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14944 /// Convert a comparison if required by the subtarget.
14945 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14946 SelectionDAG &DAG) const {
14947 // If the subtarget does not support the FUCOMI instruction, floating-point
14948 // comparisons have to be converted.
14949 if (Subtarget.hasCMov() ||
14950 Cmp.getOpcode() != X86ISD::CMP ||
14951 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14952 !Cmp.getOperand(1).getValueType().isFloatingPoint())
14955 // The instruction selector will select an FUCOM instruction instead of
14956 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14957 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14958 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14960 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14961 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14962 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14963 DAG.getConstant(8, dl, MVT::i8));
14964 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14966 // Some 64-bit targets lack SAHF support, but they do support FCOMI.
14967 assert(Subtarget.hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?");
14968 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14971 /// The minimum architected relative accuracy is 2^-12. We need one
14972 /// Newton-Raphson step to have a good float result (24 bits of precision).
14973 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14974 DAGCombinerInfo &DCI,
14975 unsigned &RefinementSteps,
14976 bool &UseOneConstNR) const {
14977 EVT VT = Op.getValueType();
14978 const char *RecipOp;
14980 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
14981 // TODO: Add support for AVX512 (v16f32).
14982 // It is likely not profitable to do this for f64 because a double-precision
14983 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14984 // instructions: convert to single, rsqrtss, convert back to double, refine
14985 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14986 // along with FMA, this could be a throughput win.
14987 if (VT == MVT::f32 && Subtarget.hasSSE1())
14989 else if ((VT == MVT::v4f32 && Subtarget.hasSSE1()) ||
14990 (VT == MVT::v8f32 && Subtarget.hasAVX()))
14991 RecipOp = "vec-sqrtf";
14995 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14996 if (!Recips.isEnabled(RecipOp))
14999 RefinementSteps = Recips.getRefinementSteps(RecipOp);
15000 UseOneConstNR = false;
15001 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
15004 /// The minimum architected relative accuracy is 2^-12. We need one
15005 /// Newton-Raphson step to have a good float result (24 bits of precision).
15006 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
15007 DAGCombinerInfo &DCI,
15008 unsigned &RefinementSteps) const {
15009 EVT VT = Op.getValueType();
15010 const char *RecipOp;
15012 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
15013 // TODO: Add support for AVX512 (v16f32).
15014 // It is likely not profitable to do this for f64 because a double-precision
15015 // reciprocal estimate with refinement on x86 prior to FMA requires
15016 // 15 instructions: convert to single, rcpss, convert back to double, refine
15017 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
15018 // along with FMA, this could be a throughput win.
15019 if (VT == MVT::f32 && Subtarget.hasSSE1())
15021 else if ((VT == MVT::v4f32 && Subtarget.hasSSE1()) ||
15022 (VT == MVT::v8f32 && Subtarget.hasAVX()))
15023 RecipOp = "vec-divf";
15027 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
15028 if (!Recips.isEnabled(RecipOp))
15031 RefinementSteps = Recips.getRefinementSteps(RecipOp);
15032 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
15035 /// If we have at least two divisions that use the same divisor, convert to
15036 /// multplication by a reciprocal. This may need to be adjusted for a given
15037 /// CPU if a division's cost is not at least twice the cost of a multiplication.
15038 /// This is because we still need one division to calculate the reciprocal and
15039 /// then we need two multiplies by that reciprocal as replacements for the
15040 /// original divisions.
15041 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
15045 /// Result of 'and' is compared against zero. Change to a BT node if possible.
15046 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
15047 const SDLoc &dl, SelectionDAG &DAG) const {
15048 SDValue Op0 = And.getOperand(0);
15049 SDValue Op1 = And.getOperand(1);
15050 if (Op0.getOpcode() == ISD::TRUNCATE)
15051 Op0 = Op0.getOperand(0);
15052 if (Op1.getOpcode() == ISD::TRUNCATE)
15053 Op1 = Op1.getOperand(0);
15056 if (Op1.getOpcode() == ISD::SHL)
15057 std::swap(Op0, Op1);
15058 if (Op0.getOpcode() == ISD::SHL) {
15059 if (isOneConstant(Op0.getOperand(0))) {
15060 // If we looked past a truncate, check that it's only truncating away
15062 unsigned BitWidth = Op0.getValueSizeInBits();
15063 unsigned AndBitWidth = And.getValueSizeInBits();
15064 if (BitWidth > AndBitWidth) {
15066 DAG.computeKnownBits(Op0, Zeros, Ones);
15067 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
15071 RHS = Op0.getOperand(1);
15073 } else if (Op1.getOpcode() == ISD::Constant) {
15074 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
15075 uint64_t AndRHSVal = AndRHS->getZExtValue();
15076 SDValue AndLHS = Op0;
15078 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
15079 LHS = AndLHS.getOperand(0);
15080 RHS = AndLHS.getOperand(1);
15083 // Use BT if the immediate can't be encoded in a TEST instruction.
15084 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
15086 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
15090 if (LHS.getNode()) {
15091 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
15092 // instruction. Since the shift amount is in-range-or-undefined, we know
15093 // that doing a bittest on the i32 value is ok. We extend to i32 because
15094 // the encoding for the i16 version is larger than the i32 version.
15095 // Also promote i16 to i32 for performance / code size reason.
15096 if (LHS.getValueType() == MVT::i8 ||
15097 LHS.getValueType() == MVT::i16)
15098 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
15100 // If the operand types disagree, extend the shift amount to match. Since
15101 // BT ignores high bits (like shifts) we can use anyextend.
15102 if (LHS.getValueType() != RHS.getValueType())
15103 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
15105 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
15106 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
15107 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15108 DAG.getConstant(Cond, dl, MVT::i8), BT);
15114 /// Turns an ISD::CondCode into a value suitable for SSE floating-point mask
15116 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
15121 // SSE Condition code mapping:
15130 switch (SetCCOpcode) {
15131 default: llvm_unreachable("Unexpected SETCC condition");
15133 case ISD::SETEQ: SSECC = 0; break;
15135 case ISD::SETGT: Swap = true; // Fallthrough
15137 case ISD::SETOLT: SSECC = 1; break;
15139 case ISD::SETGE: Swap = true; // Fallthrough
15141 case ISD::SETOLE: SSECC = 2; break;
15142 case ISD::SETUO: SSECC = 3; break;
15144 case ISD::SETNE: SSECC = 4; break;
15145 case ISD::SETULE: Swap = true; // Fallthrough
15146 case ISD::SETUGE: SSECC = 5; break;
15147 case ISD::SETULT: Swap = true; // Fallthrough
15148 case ISD::SETUGT: SSECC = 6; break;
15149 case ISD::SETO: SSECC = 7; break;
15151 case ISD::SETONE: SSECC = 8; break;
15154 std::swap(Op0, Op1);
15159 /// Break a VSETCC 256-bit integer VSETCC into two new 128 ones and then
15160 /// concatenate the result back.
15161 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
15162 MVT VT = Op.getSimpleValueType();
15164 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
15165 "Unsupported value type for operation");
15167 unsigned NumElems = VT.getVectorNumElements();
15169 SDValue CC = Op.getOperand(2);
15171 // Extract the LHS vectors
15172 SDValue LHS = Op.getOperand(0);
15173 SDValue LHS1 = extract128BitVector(LHS, 0, DAG, dl);
15174 SDValue LHS2 = extract128BitVector(LHS, NumElems / 2, DAG, dl);
15176 // Extract the RHS vectors
15177 SDValue RHS = Op.getOperand(1);
15178 SDValue RHS1 = extract128BitVector(RHS, 0, DAG, dl);
15179 SDValue RHS2 = extract128BitVector(RHS, NumElems / 2, DAG, dl);
15181 // Issue the operation on the smaller types and concatenate the result back
15182 MVT EltVT = VT.getVectorElementType();
15183 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15184 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15185 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
15186 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
15189 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
15190 SDValue Op0 = Op.getOperand(0);
15191 SDValue Op1 = Op.getOperand(1);
15192 SDValue CC = Op.getOperand(2);
15193 MVT VT = Op.getSimpleValueType();
15196 assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
15197 "Unexpected type for boolean compare operation");
15198 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
15199 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
15200 DAG.getConstant(-1, dl, VT));
15201 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
15202 DAG.getConstant(-1, dl, VT));
15203 switch (SetCCOpcode) {
15204 default: llvm_unreachable("Unexpected SETCC condition");
15206 // (x == y) -> ~(x ^ y)
15207 return DAG.getNode(ISD::XOR, dl, VT,
15208 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
15209 DAG.getConstant(-1, dl, VT));
15211 // (x != y) -> (x ^ y)
15212 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
15215 // (x > y) -> (x & ~y)
15216 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
15219 // (x < y) -> (~x & y)
15220 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
15223 // (x <= y) -> (~x | y)
15224 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
15227 // (x >=y) -> (x | ~y)
15228 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
15232 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
15234 SDValue Op0 = Op.getOperand(0);
15235 SDValue Op1 = Op.getOperand(1);
15236 SDValue CC = Op.getOperand(2);
15237 MVT VT = Op.getSimpleValueType();
15240 assert(VT.getVectorElementType() == MVT::i1 &&
15241 "Cannot set masked compare for this operation");
15243 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
15245 bool Unsigned = false;
15248 switch (SetCCOpcode) {
15249 default: llvm_unreachable("Unexpected SETCC condition");
15250 case ISD::SETNE: SSECC = 4; break;
15251 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
15252 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
15253 case ISD::SETLT: Swap = true; //fall-through
15254 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
15255 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
15256 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
15257 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
15258 case ISD::SETULE: Unsigned = true; //fall-through
15259 case ISD::SETLE: SSECC = 2; break;
15263 std::swap(Op0, Op1);
15265 return DAG.getNode(Opc, dl, VT, Op0, Op1);
15266 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
15267 return DAG.getNode(Opc, dl, VT, Op0, Op1,
15268 DAG.getConstant(SSECC, dl, MVT::i8));
15271 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
15272 /// operand \p Op1. If non-trivial (for example because it's not constant)
15273 /// return an empty value.
15274 static SDValue ChangeVSETULTtoVSETULE(const SDLoc &dl, SDValue Op1,
15275 SelectionDAG &DAG) {
15276 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
15280 MVT VT = Op1.getSimpleValueType();
15281 MVT EVT = VT.getVectorElementType();
15282 unsigned n = VT.getVectorNumElements();
15283 SmallVector<SDValue, 8> ULTOp1;
15285 for (unsigned i = 0; i < n; ++i) {
15286 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
15287 if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
15290 // Avoid underflow.
15291 APInt Val = Elt->getAPIntValue();
15295 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
15298 return DAG.getBuildVector(VT, dl, ULTOp1);
15301 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget &Subtarget,
15302 SelectionDAG &DAG) {
15303 SDValue Op0 = Op.getOperand(0);
15304 SDValue Op1 = Op.getOperand(1);
15305 SDValue CC = Op.getOperand(2);
15306 MVT VT = Op.getSimpleValueType();
15307 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
15308 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
15313 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
15314 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
15318 if (Subtarget.hasAVX512() && VT.getVectorElementType() == MVT::i1) {
15319 assert(VT.getVectorNumElements() <= 16);
15320 Opc = X86ISD::CMPM;
15322 Opc = X86ISD::CMPP;
15323 // The SSE/AVX packed FP comparison nodes are defined with a
15324 // floating-point vector result that matches the operand type. This allows
15325 // them to work with an SSE1 target (integer vector types are not legal).
15326 VT = Op0.getSimpleValueType();
15329 // In the two cases not handled by SSE compare predicates (SETUEQ/SETONE),
15330 // emit two comparisons and a logic op to tie them together.
15331 // TODO: This can be avoided if Intel (and only Intel as of 2016) AVX is
15334 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
15336 // LLVM predicate is SETUEQ or SETONE.
15338 unsigned CombineOpc;
15339 if (SetCCOpcode == ISD::SETUEQ) {
15342 CombineOpc = Opc == X86ISD::CMPP ? static_cast<unsigned>(X86ISD::FOR) :
15343 static_cast<unsigned>(ISD::OR);
15345 assert(SetCCOpcode == ISD::SETONE);
15348 CombineOpc = Opc == X86ISD::CMPP ? static_cast<unsigned>(X86ISD::FAND) :
15349 static_cast<unsigned>(ISD::AND);
15352 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
15353 DAG.getConstant(CC0, dl, MVT::i8));
15354 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
15355 DAG.getConstant(CC1, dl, MVT::i8));
15356 Cmp = DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
15358 // Handle all other FP comparisons here.
15359 Cmp = DAG.getNode(Opc, dl, VT, Op0, Op1,
15360 DAG.getConstant(SSECC, dl, MVT::i8));
15363 // If this is SSE/AVX CMPP, bitcast the result back to integer to match the
15364 // result type of SETCC. The bitcast is expected to be optimized away
15365 // during combining/isel.
15366 if (Opc == X86ISD::CMPP)
15367 Cmp = DAG.getBitcast(Op.getSimpleValueType(), Cmp);
15372 MVT VTOp0 = Op0.getSimpleValueType();
15373 assert(VTOp0 == Op1.getSimpleValueType() &&
15374 "Expected operands with same type!");
15375 assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
15376 "Invalid number of packed elements for source and destination!");
15378 if (VT.is128BitVector() && VTOp0.is256BitVector()) {
15379 // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
15380 // legalizer to a wider vector type. In the case of 'vsetcc' nodes, the
15381 // legalizer firstly checks if the first operand in input to the setcc has
15382 // a legal type. If so, then it promotes the return type to that same type.
15383 // Otherwise, the return type is promoted to the 'next legal type' which,
15384 // for a vector of MVT::i1 is always a 128-bit integer vector type.
15386 // We reach this code only if the following two conditions are met:
15387 // 1. Both return type and operand type have been promoted to wider types
15388 // by the type legalizer.
15389 // 2. The original operand type has been promoted to a 256-bit vector.
15391 // Note that condition 2. only applies for AVX targets.
15392 SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
15393 return DAG.getZExtOrTrunc(NewOp, dl, VT);
15396 // The non-AVX512 code below works under the assumption that source and
15397 // destination types are the same.
15398 assert((Subtarget.hasAVX512() || (VT == VTOp0)) &&
15399 "Value types for source and destination must be the same!");
15401 // Break 256-bit integer vector compare into smaller ones.
15402 if (VT.is256BitVector() && !Subtarget.hasInt256())
15403 return Lower256IntVSETCC(Op, DAG);
15405 // Operands are boolean (vectors of i1)
15406 MVT OpVT = Op1.getSimpleValueType();
15407 if (OpVT.getVectorElementType() == MVT::i1)
15408 return LowerBoolVSETCC_AVX512(Op, DAG);
15410 // The result is boolean, but operands are int/float
15411 if (VT.getVectorElementType() == MVT::i1) {
15412 // In AVX-512 architecture setcc returns mask with i1 elements,
15413 // But there is no compare instruction for i8 and i16 elements in KNL.
15414 // In this case use SSE compare
15415 bool UseAVX512Inst =
15416 (OpVT.is512BitVector() ||
15417 OpVT.getVectorElementType().getSizeInBits() >= 32 ||
15418 (Subtarget.hasBWI() && Subtarget.hasVLX()));
15421 return LowerIntVSETCC_AVX512(Op, DAG);
15423 return DAG.getNode(ISD::TRUNCATE, dl, VT,
15424 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
15427 // Lower using XOP integer comparisons.
15428 if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
15429 VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget.hasXOP()) {
15430 // Translate compare code to XOP PCOM compare mode.
15431 unsigned CmpMode = 0;
15432 switch (SetCCOpcode) {
15433 default: llvm_unreachable("Unexpected SETCC condition");
15435 case ISD::SETLT: CmpMode = 0x00; break;
15437 case ISD::SETLE: CmpMode = 0x01; break;
15439 case ISD::SETGT: CmpMode = 0x02; break;
15441 case ISD::SETGE: CmpMode = 0x03; break;
15442 case ISD::SETEQ: CmpMode = 0x04; break;
15443 case ISD::SETNE: CmpMode = 0x05; break;
15446 // Are we comparing unsigned or signed integers?
15447 unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
15448 ? X86ISD::VPCOMU : X86ISD::VPCOM;
15450 return DAG.getNode(Opc, dl, VT, Op0, Op1,
15451 DAG.getConstant(CmpMode, dl, MVT::i8));
15454 // We are handling one of the integer comparisons here. Since SSE only has
15455 // GT and EQ comparisons for integer, swapping operands and multiple
15456 // operations may be required for some comparisons.
15458 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
15459 bool Subus = false;
15461 switch (SetCCOpcode) {
15462 default: llvm_unreachable("Unexpected SETCC condition");
15463 case ISD::SETNE: Invert = true;
15464 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
15465 case ISD::SETLT: Swap = true;
15466 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
15467 case ISD::SETGE: Swap = true;
15468 case ISD::SETLE: Opc = X86ISD::PCMPGT;
15469 Invert = true; break;
15470 case ISD::SETULT: Swap = true;
15471 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
15472 FlipSigns = true; break;
15473 case ISD::SETUGE: Swap = true;
15474 case ISD::SETULE: Opc = X86ISD::PCMPGT;
15475 FlipSigns = true; Invert = true; break;
15478 // Special case: Use min/max operations for SETULE/SETUGE
15479 MVT VET = VT.getVectorElementType();
15481 (Subtarget.hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
15482 || (Subtarget.hasSSE2() && (VET == MVT::i8));
15485 switch (SetCCOpcode) {
15487 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
15488 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
15491 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
15494 bool hasSubus = Subtarget.hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
15495 if (!MinMax && hasSubus) {
15496 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
15498 // t = psubus Op0, Op1
15499 // pcmpeq t, <0..0>
15500 switch (SetCCOpcode) {
15502 case ISD::SETULT: {
15503 // If the comparison is against a constant we can turn this into a
15504 // setule. With psubus, setule does not require a swap. This is
15505 // beneficial because the constant in the register is no longer
15506 // destructed as the destination so it can be hoisted out of a loop.
15507 // Only do this pre-AVX since vpcmp* is no longer destructive.
15508 if (Subtarget.hasAVX())
15510 if (SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG)) {
15512 Subus = true; Invert = false; Swap = false;
15516 // Psubus is better than flip-sign because it requires no inversion.
15517 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
15518 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
15522 Opc = X86ISD::SUBUS;
15528 std::swap(Op0, Op1);
15530 // Check that the operation in question is available (most are plain SSE2,
15531 // but PCMPGTQ and PCMPEQQ have different requirements).
15532 if (VT == MVT::v2i64) {
15533 if (Opc == X86ISD::PCMPGT && !Subtarget.hasSSE42()) {
15534 assert(Subtarget.hasSSE2() && "Don't know how to lower!");
15536 // First cast everything to the right type.
15537 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
15538 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
15540 // Since SSE has no unsigned integer comparisons, we need to flip the sign
15541 // bits of the inputs before performing those operations. The lower
15542 // compare is always unsigned.
15545 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
15547 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
15548 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
15549 SB = DAG.getBuildVector(MVT::v4i32, dl, {Sign, Zero, Sign, Zero});
15551 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
15552 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
15554 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
15555 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
15556 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
15558 // Create masks for only the low parts/high parts of the 64 bit integers.
15559 static const int MaskHi[] = { 1, 1, 3, 3 };
15560 static const int MaskLo[] = { 0, 0, 2, 2 };
15561 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
15562 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
15563 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
15565 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
15566 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
15569 Result = DAG.getNOT(dl, Result, MVT::v4i32);
15571 return DAG.getBitcast(VT, Result);
15574 if (Opc == X86ISD::PCMPEQ && !Subtarget.hasSSE41()) {
15575 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
15576 // pcmpeqd + pshufd + pand.
15577 assert(Subtarget.hasSSE2() && !FlipSigns && "Don't know how to lower!");
15579 // First cast everything to the right type.
15580 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
15581 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
15584 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
15586 // Make sure the lower and upper halves are both all-ones.
15587 static const int Mask[] = { 1, 0, 3, 2 };
15588 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
15589 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
15592 Result = DAG.getNOT(dl, Result, MVT::v4i32);
15594 return DAG.getBitcast(VT, Result);
15598 // Since SSE has no unsigned integer comparisons, we need to flip the sign
15599 // bits of the inputs before performing those operations.
15601 MVT EltVT = VT.getVectorElementType();
15602 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
15604 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
15605 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
15608 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
15610 // If the logical-not of the result is required, perform that now.
15612 Result = DAG.getNOT(dl, Result, VT);
15615 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
15618 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
15619 getZeroVector(VT, Subtarget, DAG, dl));
15624 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
15626 MVT VT = Op.getSimpleValueType();
15628 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
15630 assert(((!Subtarget.hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
15631 && "SetCC type must be 8-bit or 1-bit integer");
15632 SDValue Op0 = Op.getOperand(0);
15633 SDValue Op1 = Op.getOperand(1);
15635 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
15637 // Optimize to BT if possible.
15638 // Lower (X & (1 << N)) == 0 to BT(X, N).
15639 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
15640 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
15641 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
15642 isNullConstant(Op1) &&
15643 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15644 if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
15645 if (VT == MVT::i1) {
15646 NewSetCC = DAG.getNode(ISD::AssertZext, dl, MVT::i8, NewSetCC,
15647 DAG.getValueType(MVT::i1));
15648 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
15654 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
15656 if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
15657 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15659 // If the input is a setcc, then reuse the input setcc or use a new one with
15660 // the inverted condition.
15661 if (Op0.getOpcode() == X86ISD::SETCC) {
15662 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
15663 bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
15667 CCode = X86::GetOppositeBranchCondition(CCode);
15668 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15669 DAG.getConstant(CCode, dl, MVT::i8),
15670 Op0.getOperand(1));
15671 if (VT == MVT::i1) {
15672 SetCC = DAG.getNode(ISD::AssertZext, dl, MVT::i8, SetCC,
15673 DAG.getValueType(MVT::i1));
15674 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
15679 if (Op0.getValueType() == MVT::i1 && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
15680 if (isOneConstant(Op1)) {
15681 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
15682 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
15684 if (!isNullConstant(Op1)) {
15685 SDValue Xor = DAG.getNode(ISD::XOR, dl, MVT::i1, Op0, Op1);
15686 return DAG.getSetCC(dl, VT, Xor, DAG.getConstant(0, dl, MVT::i1), CC);
15690 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
15691 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
15692 if (X86CC == X86::COND_INVALID)
15695 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
15696 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
15697 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15698 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
15699 if (VT == MVT::i1) {
15700 SetCC = DAG.getNode(ISD::AssertZext, dl, MVT::i8, SetCC,
15701 DAG.getValueType(MVT::i1));
15702 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
15707 SDValue X86TargetLowering::LowerSETCCE(SDValue Op, SelectionDAG &DAG) const {
15708 SDValue LHS = Op.getOperand(0);
15709 SDValue RHS = Op.getOperand(1);
15710 SDValue Carry = Op.getOperand(2);
15711 SDValue Cond = Op.getOperand(3);
15714 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
15715 X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
15717 assert(Carry.getOpcode() != ISD::CARRY_FALSE);
15718 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15719 SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry);
15720 SDValue SetCC = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15721 DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
15722 if (Op.getSimpleValueType() == MVT::i1) {
15723 SetCC = DAG.getNode(ISD::AssertZext, DL, MVT::i8, SetCC,
15724 DAG.getValueType(MVT::i1));
15725 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
15730 /// Return true if opcode is a X86 logical comparison.
15731 static bool isX86LogicalCmp(SDValue Op) {
15732 unsigned Opc = Op.getNode()->getOpcode();
15733 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
15734 Opc == X86ISD::SAHF)
15736 if (Op.getResNo() == 1 &&
15737 (Opc == X86ISD::ADD ||
15738 Opc == X86ISD::SUB ||
15739 Opc == X86ISD::ADC ||
15740 Opc == X86ISD::SBB ||
15741 Opc == X86ISD::SMUL ||
15742 Opc == X86ISD::UMUL ||
15743 Opc == X86ISD::INC ||
15744 Opc == X86ISD::DEC ||
15745 Opc == X86ISD::OR ||
15746 Opc == X86ISD::XOR ||
15747 Opc == X86ISD::AND))
15750 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
15756 /// Returns the "condition" node, that may be wrapped with "truncate".
15757 /// Like this: (i1 (trunc (i8 X86ISD::SETCC))).
15758 static SDValue getCondAfterTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
15759 if (V.getOpcode() != ISD::TRUNCATE)
15762 SDValue VOp0 = V.getOperand(0);
15763 if (VOp0.getOpcode() == ISD::AssertZext &&
15764 V.getValueSizeInBits() ==
15765 cast<VTSDNode>(VOp0.getOperand(1))->getVT().getSizeInBits())
15766 return VOp0.getOperand(0);
15768 unsigned InBits = VOp0.getValueSizeInBits();
15769 unsigned Bits = V.getValueSizeInBits();
15770 if (DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits)))
15771 return V.getOperand(0);
15775 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
15776 bool addTest = true;
15777 SDValue Cond = Op.getOperand(0);
15778 SDValue Op1 = Op.getOperand(1);
15779 SDValue Op2 = Op.getOperand(2);
15781 MVT VT = Op1.getSimpleValueType();
15784 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
15785 // are available or VBLENDV if AVX is available.
15786 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
15787 if (Cond.getOpcode() == ISD::SETCC &&
15788 ((Subtarget.hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
15789 (Subtarget.hasSSE1() && VT == MVT::f32)) &&
15790 VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
15791 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
15792 int SSECC = translateX86FSETCC(
15793 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
15796 if (Subtarget.hasAVX512()) {
15797 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
15798 DAG.getConstant(SSECC, DL, MVT::i8));
15799 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
15802 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
15803 DAG.getConstant(SSECC, DL, MVT::i8));
15805 // If we have AVX, we can use a variable vector select (VBLENDV) instead
15806 // of 3 logic instructions for size savings and potentially speed.
15807 // Unfortunately, there is no scalar form of VBLENDV.
15809 // If either operand is a constant, don't try this. We can expect to
15810 // optimize away at least one of the logic instructions later in that
15811 // case, so that sequence would be faster than a variable blend.
15813 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
15814 // uses XMM0 as the selection register. That may need just as many
15815 // instructions as the AND/ANDN/OR sequence due to register moves, so
15818 if (Subtarget.hasAVX() &&
15819 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
15821 // Convert to vectors, do a VSELECT, and convert back to scalar.
15822 // All of the conversions should be optimized away.
15824 MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
15825 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
15826 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
15827 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
15829 MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
15830 VCmp = DAG.getBitcast(VCmpVT, VCmp);
15832 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
15834 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
15835 VSel, DAG.getIntPtrConstant(0, DL));
15837 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15838 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15839 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15843 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
15845 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
15846 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
15847 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
15848 Op1Scalar = Op1.getOperand(0);
15850 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
15851 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
15852 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
15853 Op2Scalar = Op2.getOperand(0);
15854 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
15855 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
15856 Op1Scalar.getValueType(),
15857 Cond, Op1Scalar, Op2Scalar);
15858 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
15859 return DAG.getBitcast(VT, newSelect);
15860 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
15861 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
15862 DAG.getIntPtrConstant(0, DL));
15866 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
15867 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
15868 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15869 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
15870 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15871 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
15872 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
15874 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
15877 if (Cond.getOpcode() == ISD::SETCC) {
15878 if (SDValue NewCond = LowerSETCC(Cond, DAG))
15882 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15883 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15884 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15885 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15886 if (Cond.getOpcode() == X86ISD::SETCC &&
15887 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15888 isNullConstant(Cond.getOperand(1).getOperand(1))) {
15889 SDValue Cmp = Cond.getOperand(1);
15891 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15893 if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15894 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15895 SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
15897 SDValue CmpOp0 = Cmp.getOperand(0);
15898 // Apply further optimizations for special cases
15899 // (select (x != 0), -1, 0) -> neg & sbb
15900 // (select (x == 0), 0, -1) -> neg & sbb
15901 if (isNullConstant(Y) &&
15902 (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
15903 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15904 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15905 DAG.getConstant(0, DL,
15906 CmpOp0.getValueType()),
15908 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15909 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15910 SDValue(Neg.getNode(), 1));
15914 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15915 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
15916 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15918 SDValue Res = // Res = 0 or -1.
15919 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15920 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
15922 if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
15923 Res = DAG.getNOT(DL, Res, Res.getValueType());
15925 if (!isNullConstant(Op2))
15926 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15931 // Look past (and (setcc_carry (cmp ...)), 1).
15932 if (Cond.getOpcode() == ISD::AND &&
15933 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15934 isOneConstant(Cond.getOperand(1)))
15935 Cond = Cond.getOperand(0);
15937 // If condition flag is set by a X86ISD::CMP, then use it as the condition
15938 // setting operand in place of the X86ISD::SETCC.
15939 unsigned CondOpcode = Cond.getOpcode();
15940 if (CondOpcode == X86ISD::SETCC ||
15941 CondOpcode == X86ISD::SETCC_CARRY) {
15942 CC = Cond.getOperand(0);
15944 SDValue Cmp = Cond.getOperand(1);
15945 unsigned Opc = Cmp.getOpcode();
15946 MVT VT = Op.getSimpleValueType();
15948 bool IllegalFPCMov = false;
15949 if (VT.isFloatingPoint() && !VT.isVector() &&
15950 !isScalarFPTypeInSSEReg(VT)) // FPStack?
15951 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15953 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15954 Opc == X86ISD::BT) { // FIXME
15958 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15959 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15960 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15961 Cond.getOperand(0).getValueType() != MVT::i8)) {
15962 SDValue LHS = Cond.getOperand(0);
15963 SDValue RHS = Cond.getOperand(1);
15964 unsigned X86Opcode;
15967 switch (CondOpcode) {
15968 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15969 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15970 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15971 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15972 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15973 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15974 default: llvm_unreachable("unexpected overflowing operator");
15976 if (CondOpcode == ISD::UMULO)
15977 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15980 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15982 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15984 if (CondOpcode == ISD::UMULO)
15985 Cond = X86Op.getValue(2);
15987 Cond = X86Op.getValue(1);
15989 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
15994 // Look past the truncate if the high bits are known zero.
15995 Cond = getCondAfterTruncWithZeroHighBitsInput(Cond, DAG);
15997 // We know the result of AND is compared against zero. Try to match
15999 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
16000 if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
16001 CC = NewSetCC.getOperand(0);
16002 Cond = NewSetCC.getOperand(1);
16009 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
16010 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
16013 // a < b ? -1 : 0 -> RES = ~setcc_carry
16014 // a < b ? 0 : -1 -> RES = setcc_carry
16015 // a >= b ? -1 : 0 -> RES = setcc_carry
16016 // a >= b ? 0 : -1 -> RES = ~setcc_carry
16017 if (Cond.getOpcode() == X86ISD::SUB) {
16018 Cond = ConvertCmpIfNecessary(Cond, DAG);
16019 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
16021 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
16022 (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
16023 (isNullConstant(Op1) || isNullConstant(Op2))) {
16024 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
16025 DAG.getConstant(X86::COND_B, DL, MVT::i8),
16027 if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
16028 return DAG.getNOT(DL, Res, Res.getValueType());
16033 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
16034 // widen the cmov and push the truncate through. This avoids introducing a new
16035 // branch during isel and doesn't add any extensions.
16036 if (Op.getValueType() == MVT::i8 &&
16037 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
16038 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
16039 if (T1.getValueType() == T2.getValueType() &&
16040 // Blacklist CopyFromReg to avoid partial register stalls.
16041 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
16042 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
16043 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
16044 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
16048 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
16049 // condition is true.
16050 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
16051 SDValue Ops[] = { Op2, Op1, CC, Cond };
16052 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
16055 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
16056 const X86Subtarget &Subtarget,
16057 SelectionDAG &DAG) {
16058 MVT VT = Op->getSimpleValueType(0);
16059 SDValue In = Op->getOperand(0);
16060 MVT InVT = In.getSimpleValueType();
16061 MVT VTElt = VT.getVectorElementType();
16062 MVT InVTElt = InVT.getVectorElementType();
16066 if ((InVTElt == MVT::i1) &&
16067 (((Subtarget.hasBWI() && Subtarget.hasVLX() &&
16068 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
16070 ((Subtarget.hasBWI() && VT.is512BitVector() &&
16071 VTElt.getSizeInBits() <= 16)) ||
16073 ((Subtarget.hasDQI() && Subtarget.hasVLX() &&
16074 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
16076 ((Subtarget.hasDQI() && VT.is512BitVector() &&
16077 VTElt.getSizeInBits() >= 32))))
16078 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
16080 unsigned int NumElts = VT.getVectorNumElements();
16082 if (NumElts != 8 && NumElts != 16 && !Subtarget.hasBWI())
16085 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
16086 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
16087 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
16088 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
16091 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
16092 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
16094 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
16097 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
16099 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
16100 if (VT.is512BitVector())
16102 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
16105 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
16106 const X86Subtarget &Subtarget,
16107 SelectionDAG &DAG) {
16108 SDValue In = Op->getOperand(0);
16109 MVT VT = Op->getSimpleValueType(0);
16110 MVT InVT = In.getSimpleValueType();
16111 assert(VT.getSizeInBits() == InVT.getSizeInBits());
16113 MVT SVT = VT.getVectorElementType();
16114 MVT InSVT = InVT.getVectorElementType();
16115 assert(SVT.getSizeInBits() > InSVT.getSizeInBits());
16117 if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16)
16119 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
16121 if (!(VT.is128BitVector() && Subtarget.hasSSE2()) &&
16122 !(VT.is256BitVector() && Subtarget.hasInt256()))
16127 // For 256-bit vectors, we only need the lower (128-bit) half of the input.
16128 if (VT.is256BitVector())
16129 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
16130 MVT::getVectorVT(InSVT, InVT.getVectorNumElements() / 2),
16131 In, DAG.getIntPtrConstant(0, dl));
16133 // SSE41 targets can use the pmovsx* instructions directly.
16134 if (Subtarget.hasSSE41())
16135 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
16137 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
16141 // As SRAI is only available on i16/i32 types, we expand only up to i32
16142 // and handle i64 separately.
16143 while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
16144 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
16145 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
16146 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
16147 Curr = DAG.getBitcast(CurrVT, Curr);
16150 SDValue SignExt = Curr;
16151 if (CurrVT != InVT) {
16152 unsigned SignExtShift =
16153 CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
16154 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
16155 DAG.getConstant(SignExtShift, dl, MVT::i8));
16161 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
16162 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
16163 DAG.getConstant(31, dl, MVT::i8));
16164 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
16165 return DAG.getBitcast(VT, Ext);
16171 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
16172 SelectionDAG &DAG) {
16173 MVT VT = Op->getSimpleValueType(0);
16174 SDValue In = Op->getOperand(0);
16175 MVT InVT = In.getSimpleValueType();
16178 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
16179 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
16181 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
16182 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
16183 (VT != MVT::v16i16 || InVT != MVT::v16i8))
16186 if (Subtarget.hasInt256())
16187 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
16189 // Optimize vectors in AVX mode
16190 // Sign extend v8i16 to v8i32 and
16193 // Divide input vector into two parts
16194 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16195 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16196 // concat the vectors to original VT
16198 unsigned NumElems = InVT.getVectorNumElements();
16199 SDValue Undef = DAG.getUNDEF(InVT);
16201 SmallVector<int,8> ShufMask1(NumElems, -1);
16202 for (unsigned i = 0; i != NumElems/2; ++i)
16205 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, ShufMask1);
16207 SmallVector<int,8> ShufMask2(NumElems, -1);
16208 for (unsigned i = 0; i != NumElems/2; ++i)
16209 ShufMask2[i] = i + NumElems/2;
16211 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, ShufMask2);
16213 MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
16214 VT.getVectorNumElements()/2);
16216 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
16217 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
16219 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16222 // Lower truncating store. We need a special lowering to vXi1 vectors
16223 static SDValue LowerTruncatingStore(SDValue StOp, const X86Subtarget &Subtarget,
16224 SelectionDAG &DAG) {
16225 StoreSDNode *St = cast<StoreSDNode>(StOp.getNode());
16227 EVT MemVT = St->getMemoryVT();
16228 assert(St->isTruncatingStore() && "We only custom truncating store.");
16229 assert(MemVT.isVector() && MemVT.getVectorElementType() == MVT::i1 &&
16230 "Expected truncstore of i1 vector");
16232 SDValue Op = St->getValue();
16233 MVT OpVT = Op.getValueType().getSimpleVT();
16234 unsigned NumElts = OpVT.getVectorNumElements();
16235 if ((Subtarget.hasVLX() && Subtarget.hasBWI() && Subtarget.hasDQI()) ||
16237 // Truncate and store - everything is legal
16238 Op = DAG.getNode(ISD::TRUNCATE, dl, MemVT, Op);
16239 if (MemVT.getSizeInBits() < 8)
16240 Op = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
16241 DAG.getUNDEF(MVT::v8i1), Op,
16242 DAG.getIntPtrConstant(0, dl));
16243 return DAG.getStore(St->getChain(), dl, Op, St->getBasePtr(),
16244 St->getMemOperand());
16247 // A subset, assume that we have only AVX-512F
16248 if (NumElts <= 8) {
16250 // Extend to 8-elts vector
16251 MVT ExtVT = MVT::getVectorVT(OpVT.getScalarType(), 8);
16252 Op = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ExtVT,
16253 DAG.getUNDEF(ExtVT), Op, DAG.getIntPtrConstant(0, dl));
16255 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i1, Op);
16256 return DAG.getStore(St->getChain(), dl, Op, St->getBasePtr(),
16257 St->getMemOperand());
16260 assert(OpVT == MVT::v32i8 && "Unexpected operand type");
16261 // Divide the vector into 2 parts and store each part separately
16262 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v16i8, Op,
16263 DAG.getIntPtrConstant(0, dl));
16264 Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::v16i1, Lo);
16265 SDValue BasePtr = St->getBasePtr();
16266 SDValue StLo = DAG.getStore(St->getChain(), dl, Lo, BasePtr,
16267 St->getMemOperand());
16268 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v16i8, Op,
16269 DAG.getIntPtrConstant(16, dl));
16270 Hi = DAG.getNode(ISD::TRUNCATE, dl, MVT::v16i1, Hi);
16272 SDValue BasePtrHi =
16273 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
16274 DAG.getConstant(2, dl, BasePtr.getValueType()));
16276 SDValue StHi = DAG.getStore(St->getChain(), dl, Hi,
16277 BasePtrHi, St->getMemOperand());
16278 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, StLo, StHi);
16281 static SDValue LowerExtended1BitVectorLoad(SDValue Op,
16282 const X86Subtarget &Subtarget,
16283 SelectionDAG &DAG) {
16285 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
16287 EVT MemVT = Ld->getMemoryVT();
16288 assert(MemVT.isVector() && MemVT.getScalarType() == MVT::i1 &&
16289 "Expected i1 vector load");
16290 unsigned ExtOpcode = Ld->getExtensionType() == ISD::ZEXTLOAD ?
16291 ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
16292 MVT VT = Op.getValueType().getSimpleVT();
16293 unsigned NumElts = VT.getVectorNumElements();
16295 if ((Subtarget.hasVLX() && Subtarget.hasBWI() && Subtarget.hasDQI()) ||
16297 // Load and extend - everything is legal
16299 SDValue Load = DAG.getLoad(MVT::v8i1, dl, Ld->getChain(),
16301 Ld->getMemOperand());
16302 // Replace chain users with the new chain.
16303 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
16304 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
16305 MVT ExtVT = MVT::getVectorVT(VT.getScalarType(), 8);
16306 SDValue ExtVec = DAG.getNode(ExtOpcode, dl, ExtVT, Load);
16308 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
16309 DAG.getIntPtrConstant(0, dl));
16311 SDValue Load = DAG.getLoad(MemVT, dl, Ld->getChain(),
16313 Ld->getMemOperand());
16314 // Replace chain users with the new chain.
16315 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
16316 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
16318 // Finally, do a normal sign-extend to the desired register.
16319 return DAG.getNode(ExtOpcode, dl, Op.getValueType(), Load);
16322 if (NumElts <= 8) {
16323 // A subset, assume that we have only AVX-512F
16324 unsigned NumBitsToLoad = NumElts < 8 ? 8 : NumElts;
16325 MVT TypeToLoad = MVT::getIntegerVT(NumBitsToLoad);
16326 SDValue Load = DAG.getLoad(TypeToLoad, dl, Ld->getChain(),
16328 Ld->getMemOperand());
16329 // Replace chain users with the new chain.
16330 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
16331 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
16333 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumBitsToLoad);
16334 SDValue BitVec = DAG.getBitcast(MaskVT, Load);
16337 return DAG.getNode(ExtOpcode, dl, VT, BitVec);
16339 // we should take care to v4i1 and v2i1
16341 MVT ExtVT = MVT::getVectorVT(VT.getScalarType(), 8);
16342 SDValue ExtVec = DAG.getNode(ExtOpcode, dl, ExtVT, BitVec);
16343 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
16344 DAG.getIntPtrConstant(0, dl));
16347 assert(VT == MVT::v32i8 && "Unexpected extload type");
16349 SmallVector<SDValue, 2> Chains;
16351 SDValue BasePtr = Ld->getBasePtr();
16352 SDValue LoadLo = DAG.getLoad(MVT::v16i1, dl, Ld->getChain(),
16354 Ld->getMemOperand());
16355 Chains.push_back(LoadLo.getValue(1));
16357 SDValue BasePtrHi =
16358 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
16359 DAG.getConstant(2, dl, BasePtr.getValueType()));
16361 SDValue LoadHi = DAG.getLoad(MVT::v16i1, dl, Ld->getChain(),
16363 Ld->getMemOperand());
16364 Chains.push_back(LoadHi.getValue(1));
16365 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
16366 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
16368 SDValue Lo = DAG.getNode(ExtOpcode, dl, MVT::v16i8, LoadLo);
16369 SDValue Hi = DAG.getNode(ExtOpcode, dl, MVT::v16i8, LoadHi);
16370 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v32i8, Lo, Hi);
16373 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
16374 // may emit an illegal shuffle but the expansion is still better than scalar
16375 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
16376 // we'll emit a shuffle and a arithmetic shift.
16377 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
16378 // TODO: It is possible to support ZExt by zeroing the undef values during
16379 // the shuffle phase or after the shuffle.
16380 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget &Subtarget,
16381 SelectionDAG &DAG) {
16382 MVT RegVT = Op.getSimpleValueType();
16383 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
16384 assert(RegVT.isInteger() &&
16385 "We only custom lower integer vector sext loads.");
16387 // Nothing useful we can do without SSE2 shuffles.
16388 assert(Subtarget.hasSSE2() && "We only custom lower sext loads with SSE2.");
16390 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
16392 EVT MemVT = Ld->getMemoryVT();
16393 if (MemVT.getScalarType() == MVT::i1)
16394 return LowerExtended1BitVectorLoad(Op, Subtarget, DAG);
16396 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16397 unsigned RegSz = RegVT.getSizeInBits();
16399 ISD::LoadExtType Ext = Ld->getExtensionType();
16401 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
16402 && "Only anyext and sext are currently implemented.");
16403 assert(MemVT != RegVT && "Cannot extend to the same type");
16404 assert(MemVT.isVector() && "Must load a vector from memory");
16406 unsigned NumElems = RegVT.getVectorNumElements();
16407 unsigned MemSz = MemVT.getSizeInBits();
16408 assert(RegSz > MemSz && "Register size must be greater than the mem size");
16410 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget.hasInt256()) {
16411 // The only way in which we have a legal 256-bit vector result but not the
16412 // integer 256-bit operations needed to directly lower a sextload is if we
16413 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
16414 // a 128-bit vector and a normal sign_extend to 256-bits that should get
16415 // correctly legalized. We do this late to allow the canonical form of
16416 // sextload to persist throughout the rest of the DAG combiner -- it wants
16417 // to fold together any extensions it can, and so will fuse a sign_extend
16418 // of an sextload into a sextload targeting a wider value.
16420 if (MemSz == 128) {
16421 // Just switch this to a normal load.
16422 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
16423 "it must be a legal 128-bit vector "
16425 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
16426 Ld->getPointerInfo(), Ld->getAlignment(),
16427 Ld->getMemOperand()->getFlags());
16429 assert(MemSz < 128 &&
16430 "Can't extend a type wider than 128 bits to a 256 bit vector!");
16431 // Do an sext load to a 128-bit vector type. We want to use the same
16432 // number of elements, but elements half as wide. This will end up being
16433 // recursively lowered by this routine, but will succeed as we definitely
16434 // have all the necessary features if we're using AVX1.
16436 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
16437 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
16439 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
16440 Ld->getPointerInfo(), MemVT, Ld->getAlignment(),
16441 Ld->getMemOperand()->getFlags());
16444 // Replace chain users with the new chain.
16445 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
16446 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
16448 // Finally, do a normal sign-extend to the desired register.
16449 return DAG.getSExtOrTrunc(Load, dl, RegVT);
16452 // All sizes must be a power of two.
16453 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
16454 "Non-power-of-two elements are not custom lowered!");
16456 // Attempt to load the original value using scalar loads.
16457 // Find the largest scalar type that divides the total loaded size.
16458 MVT SclrLoadTy = MVT::i8;
16459 for (MVT Tp : MVT::integer_valuetypes()) {
16460 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16465 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16466 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16468 SclrLoadTy = MVT::f64;
16470 // Calculate the number of scalar loads that we need to perform
16471 // in order to load our vector from memory.
16472 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16474 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
16475 "Can only lower sext loads with a single scalar load!");
16477 unsigned loadRegZize = RegSz;
16478 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
16481 // Represent our vector as a sequence of elements which are the
16482 // largest scalar that we can load.
16483 EVT LoadUnitVecVT = EVT::getVectorVT(
16484 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
16486 // Represent the data using the same element type that is stored in
16487 // memory. In practice, we ''widen'' MemVT.
16489 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16490 loadRegZize / MemVT.getScalarSizeInBits());
16492 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16493 "Invalid vector type");
16495 // We can't shuffle using an illegal type.
16496 assert(TLI.isTypeLegal(WideVecVT) &&
16497 "We only lower types that form legal widened vector types");
16499 SmallVector<SDValue, 8> Chains;
16500 SDValue Ptr = Ld->getBasePtr();
16501 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
16502 TLI.getPointerTy(DAG.getDataLayout()));
16503 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16505 for (unsigned i = 0; i < NumLoads; ++i) {
16506 // Perform a single load.
16507 SDValue ScalarLoad =
16508 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
16509 Ld->getAlignment(), Ld->getMemOperand()->getFlags());
16510 Chains.push_back(ScalarLoad.getValue(1));
16511 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16512 // another round of DAGCombining.
16514 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16516 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16517 ScalarLoad, DAG.getIntPtrConstant(i, dl));
16519 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16522 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
16524 // Bitcast the loaded value to a vector of the original element type, in
16525 // the size of the target vector type.
16526 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
16527 unsigned SizeRatio = RegSz / MemSz;
16529 if (Ext == ISD::SEXTLOAD) {
16530 // If we have SSE4.1, we can directly emit a VSEXT node.
16531 if (Subtarget.hasSSE41()) {
16532 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16533 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16537 // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
16539 assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
16540 "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
16542 SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
16543 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16547 // Redistribute the loaded elements into the different locations.
16548 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
16549 for (unsigned i = 0; i != NumElems; ++i)
16550 ShuffleVec[i * SizeRatio] = i;
16552 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16553 DAG.getUNDEF(WideVecVT), ShuffleVec);
16555 // Bitcast to the requested type.
16556 Shuff = DAG.getBitcast(RegVT, Shuff);
16557 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
16561 /// Return true if node is an ISD::AND or ISD::OR of two X86ISD::SETCC nodes
16562 /// each of which has no other use apart from the AND / OR.
16563 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
16564 Opc = Op.getOpcode();
16565 if (Opc != ISD::OR && Opc != ISD::AND)
16567 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
16568 Op.getOperand(0).hasOneUse() &&
16569 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
16570 Op.getOperand(1).hasOneUse());
16573 /// Return true if node is an ISD::XOR of a X86ISD::SETCC and 1 and that the
16574 /// SETCC node has a single use.
16575 static bool isXor1OfSetCC(SDValue Op) {
16576 if (Op.getOpcode() != ISD::XOR)
16578 if (isOneConstant(Op.getOperand(1)))
16579 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
16580 Op.getOperand(0).hasOneUse();
16584 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
16585 bool addTest = true;
16586 SDValue Chain = Op.getOperand(0);
16587 SDValue Cond = Op.getOperand(1);
16588 SDValue Dest = Op.getOperand(2);
16591 bool Inverted = false;
16593 if (Cond.getOpcode() == ISD::SETCC) {
16594 // Check for setcc([su]{add,sub,mul}o == 0).
16595 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
16596 isNullConstant(Cond.getOperand(1)) &&
16597 Cond.getOperand(0).getResNo() == 1 &&
16598 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
16599 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
16600 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
16601 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
16602 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
16603 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
16605 Cond = Cond.getOperand(0);
16607 if (SDValue NewCond = LowerSETCC(Cond, DAG))
16612 // FIXME: LowerXALUO doesn't handle these!!
16613 else if (Cond.getOpcode() == X86ISD::ADD ||
16614 Cond.getOpcode() == X86ISD::SUB ||
16615 Cond.getOpcode() == X86ISD::SMUL ||
16616 Cond.getOpcode() == X86ISD::UMUL)
16617 Cond = LowerXALUO(Cond, DAG);
16620 // Look pass (and (setcc_carry (cmp ...)), 1).
16621 if (Cond.getOpcode() == ISD::AND &&
16622 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
16623 isOneConstant(Cond.getOperand(1)))
16624 Cond = Cond.getOperand(0);
16626 // If condition flag is set by a X86ISD::CMP, then use it as the condition
16627 // setting operand in place of the X86ISD::SETCC.
16628 unsigned CondOpcode = Cond.getOpcode();
16629 if (CondOpcode == X86ISD::SETCC ||
16630 CondOpcode == X86ISD::SETCC_CARRY) {
16631 CC = Cond.getOperand(0);
16633 SDValue Cmp = Cond.getOperand(1);
16634 unsigned Opc = Cmp.getOpcode();
16635 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
16636 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
16640 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
16644 // These can only come from an arithmetic instruction with overflow,
16645 // e.g. SADDO, UADDO.
16646 Cond = Cond.getNode()->getOperand(1);
16652 CondOpcode = Cond.getOpcode();
16653 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
16654 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
16655 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
16656 Cond.getOperand(0).getValueType() != MVT::i8)) {
16657 SDValue LHS = Cond.getOperand(0);
16658 SDValue RHS = Cond.getOperand(1);
16659 unsigned X86Opcode;
16662 // Keep this in sync with LowerXALUO, otherwise we might create redundant
16663 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
16665 switch (CondOpcode) {
16666 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
16668 if (isOneConstant(RHS)) {
16669 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
16672 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
16673 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
16675 if (isOneConstant(RHS)) {
16676 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
16679 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
16680 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
16681 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
16682 default: llvm_unreachable("unexpected overflowing operator");
16685 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
16686 if (CondOpcode == ISD::UMULO)
16687 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
16690 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
16692 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
16694 if (CondOpcode == ISD::UMULO)
16695 Cond = X86Op.getValue(2);
16697 Cond = X86Op.getValue(1);
16699 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
16703 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
16704 SDValue Cmp = Cond.getOperand(0).getOperand(1);
16705 if (CondOpc == ISD::OR) {
16706 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
16707 // two branches instead of an explicit OR instruction with a
16709 if (Cmp == Cond.getOperand(1).getOperand(1) &&
16710 isX86LogicalCmp(Cmp)) {
16711 CC = Cond.getOperand(0).getOperand(0);
16712 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16713 Chain, Dest, CC, Cmp);
16714 CC = Cond.getOperand(1).getOperand(0);
16718 } else { // ISD::AND
16719 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
16720 // two branches instead of an explicit AND instruction with a
16721 // separate test. However, we only do this if this block doesn't
16722 // have a fall-through edge, because this requires an explicit
16723 // jmp when the condition is false.
16724 if (Cmp == Cond.getOperand(1).getOperand(1) &&
16725 isX86LogicalCmp(Cmp) &&
16726 Op.getNode()->hasOneUse()) {
16727 X86::CondCode CCode =
16728 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
16729 CCode = X86::GetOppositeBranchCondition(CCode);
16730 CC = DAG.getConstant(CCode, dl, MVT::i8);
16731 SDNode *User = *Op.getNode()->use_begin();
16732 // Look for an unconditional branch following this conditional branch.
16733 // We need this because we need to reverse the successors in order
16734 // to implement FCMP_OEQ.
16735 if (User->getOpcode() == ISD::BR) {
16736 SDValue FalseBB = User->getOperand(1);
16738 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16739 assert(NewBR == User);
16743 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16744 Chain, Dest, CC, Cmp);
16745 X86::CondCode CCode =
16746 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
16747 CCode = X86::GetOppositeBranchCondition(CCode);
16748 CC = DAG.getConstant(CCode, dl, MVT::i8);
16754 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
16755 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
16756 // It should be transformed during dag combiner except when the condition
16757 // is set by a arithmetics with overflow node.
16758 X86::CondCode CCode =
16759 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
16760 CCode = X86::GetOppositeBranchCondition(CCode);
16761 CC = DAG.getConstant(CCode, dl, MVT::i8);
16762 Cond = Cond.getOperand(0).getOperand(1);
16764 } else if (Cond.getOpcode() == ISD::SETCC &&
16765 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
16766 // For FCMP_OEQ, we can emit
16767 // two branches instead of an explicit AND instruction with a
16768 // separate test. However, we only do this if this block doesn't
16769 // have a fall-through edge, because this requires an explicit
16770 // jmp when the condition is false.
16771 if (Op.getNode()->hasOneUse()) {
16772 SDNode *User = *Op.getNode()->use_begin();
16773 // Look for an unconditional branch following this conditional branch.
16774 // We need this because we need to reverse the successors in order
16775 // to implement FCMP_OEQ.
16776 if (User->getOpcode() == ISD::BR) {
16777 SDValue FalseBB = User->getOperand(1);
16779 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16780 assert(NewBR == User);
16784 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
16785 Cond.getOperand(0), Cond.getOperand(1));
16786 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
16787 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
16788 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16789 Chain, Dest, CC, Cmp);
16790 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
16795 } else if (Cond.getOpcode() == ISD::SETCC &&
16796 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
16797 // For FCMP_UNE, we can emit
16798 // two branches instead of an explicit AND instruction with a
16799 // separate test. However, we only do this if this block doesn't
16800 // have a fall-through edge, because this requires an explicit
16801 // jmp when the condition is false.
16802 if (Op.getNode()->hasOneUse()) {
16803 SDNode *User = *Op.getNode()->use_begin();
16804 // Look for an unconditional branch following this conditional branch.
16805 // We need this because we need to reverse the successors in order
16806 // to implement FCMP_UNE.
16807 if (User->getOpcode() == ISD::BR) {
16808 SDValue FalseBB = User->getOperand(1);
16810 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
16811 assert(NewBR == User);
16814 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
16815 Cond.getOperand(0), Cond.getOperand(1));
16816 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
16817 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
16818 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16819 Chain, Dest, CC, Cmp);
16820 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
16830 // Look pass the truncate if the high bits are known zero.
16831 Cond = getCondAfterTruncWithZeroHighBitsInput(Cond, DAG);
16833 // We know the result of AND is compared against zero. Try to match
16835 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
16836 if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
16837 CC = NewSetCC.getOperand(0);
16838 Cond = NewSetCC.getOperand(1);
16845 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
16846 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
16847 Cond = EmitTest(Cond, X86Cond, dl, DAG);
16849 Cond = ConvertCmpIfNecessary(Cond, DAG);
16850 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
16851 Chain, Dest, CC, Cond);
16854 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
16855 // Calls to _alloca are needed to probe the stack when allocating more than 4k
16856 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
16857 // that the guard pages used by the OS virtual memory manager are allocated in
16858 // correct sequence.
16860 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
16861 SelectionDAG &DAG) const {
16862 MachineFunction &MF = DAG.getMachineFunction();
16863 bool SplitStack = MF.shouldSplitStack();
16864 bool Lower = (Subtarget.isOSWindows() && !Subtarget.isTargetMachO()) ||
16869 SDNode *Node = Op.getNode();
16870 SDValue Chain = Op.getOperand(0);
16871 SDValue Size = Op.getOperand(1);
16872 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
16873 EVT VT = Node->getValueType(0);
16875 // Chain the dynamic stack allocation so that it doesn't modify the stack
16876 // pointer when other instructions are using the stack.
16877 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl);
16879 bool Is64Bit = Subtarget.is64Bit();
16880 MVT SPTy = getPointerTy(DAG.getDataLayout());
16884 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16885 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
16886 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
16887 " not tell us which reg is the stack pointer!");
16889 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
16890 Chain = SP.getValue(1);
16891 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
16892 unsigned StackAlign = TFI.getStackAlignment();
16893 Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
16894 if (Align > StackAlign)
16895 Result = DAG.getNode(ISD::AND, dl, VT, Result,
16896 DAG.getConstant(-(uint64_t)Align, dl, VT));
16897 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
16898 } else if (SplitStack) {
16899 MachineRegisterInfo &MRI = MF.getRegInfo();
16902 // The 64 bit implementation of segmented stacks needs to clobber both r10
16903 // r11. This makes it impossible to use it along with nested parameters.
16904 const Function *F = MF.getFunction();
16905 for (const auto &A : F->args()) {
16906 if (A.hasNestAttr())
16907 report_fatal_error("Cannot use segmented stacks with functions that "
16908 "have nested arguments.");
16912 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
16913 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
16914 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
16915 Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
16916 DAG.getRegister(Vreg, SPTy));
16918 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
16919 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Size);
16920 MF.getInfo<X86MachineFunctionInfo>()->setHasWinAlloca(true);
16922 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
16923 unsigned SPReg = RegInfo->getStackRegister();
16924 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
16925 Chain = SP.getValue(1);
16928 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
16929 DAG.getConstant(-(uint64_t)Align, dl, VT));
16930 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
16936 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
16937 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
16939 SDValue Ops[2] = {Result, Chain};
16940 return DAG.getMergeValues(Ops, dl);
16943 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
16944 MachineFunction &MF = DAG.getMachineFunction();
16945 auto PtrVT = getPointerTy(MF.getDataLayout());
16946 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16948 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16951 if (!Subtarget.is64Bit() ||
16952 Subtarget.isCallingConvWin64(MF.getFunction()->getCallingConv())) {
16953 // vastart just stores the address of the VarArgsFrameIndex slot into the
16954 // memory location argument.
16955 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16956 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
16957 MachinePointerInfo(SV));
16961 // gp_offset (0 - 6 * 8)
16962 // fp_offset (48 - 48 + 8 * 16)
16963 // overflow_arg_area (point to parameters coming in memory).
16965 SmallVector<SDValue, 8> MemOps;
16966 SDValue FIN = Op.getOperand(1);
16968 SDValue Store = DAG.getStore(
16969 Op.getOperand(0), DL,
16970 DAG.getConstant(FuncInfo->getVarArgsGPOffset(), DL, MVT::i32), FIN,
16971 MachinePointerInfo(SV));
16972 MemOps.push_back(Store);
16975 FIN = DAG.getMemBasePlusOffset(FIN, 4, DL);
16976 Store = DAG.getStore(
16977 Op.getOperand(0), DL,
16978 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL, MVT::i32), FIN,
16979 MachinePointerInfo(SV, 4));
16980 MemOps.push_back(Store);
16982 // Store ptr to overflow_arg_area
16983 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16984 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16986 DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, MachinePointerInfo(SV, 8));
16987 MemOps.push_back(Store);
16989 // Store ptr to reg_save_area.
16990 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
16991 Subtarget.isTarget64BitLP64() ? 8 : 4, DL));
16992 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
16993 Store = DAG.getStore(
16994 Op.getOperand(0), DL, RSFIN, FIN,
16995 MachinePointerInfo(SV, Subtarget.isTarget64BitLP64() ? 16 : 12));
16996 MemOps.push_back(Store);
16997 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
17000 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
17001 assert(Subtarget.is64Bit() &&
17002 "LowerVAARG only handles 64-bit va_arg!");
17003 assert(Op.getNode()->getNumOperands() == 4);
17005 MachineFunction &MF = DAG.getMachineFunction();
17006 if (Subtarget.isCallingConvWin64(MF.getFunction()->getCallingConv()))
17007 // The Win64 ABI uses char* instead of a structure.
17008 return DAG.expandVAArg(Op.getNode());
17010 SDValue Chain = Op.getOperand(0);
17011 SDValue SrcPtr = Op.getOperand(1);
17012 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
17013 unsigned Align = Op.getConstantOperandVal(3);
17016 EVT ArgVT = Op.getNode()->getValueType(0);
17017 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17018 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
17021 // Decide which area this value should be read from.
17022 // TODO: Implement the AMD64 ABI in its entirety. This simple
17023 // selection mechanism works only for the basic types.
17024 if (ArgVT == MVT::f80) {
17025 llvm_unreachable("va_arg for f80 not yet implemented");
17026 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
17027 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
17028 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
17029 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
17031 llvm_unreachable("Unhandled argument type in LowerVAARG");
17034 if (ArgMode == 2) {
17035 // Sanity Check: Make sure using fp_offset makes sense.
17036 assert(!Subtarget.useSoftFloat() &&
17037 !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
17038 Subtarget.hasSSE1());
17041 // Insert VAARG_64 node into the DAG
17042 // VAARG_64 returns two values: Variable Argument Address, Chain
17043 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
17044 DAG.getConstant(ArgMode, dl, MVT::i8),
17045 DAG.getConstant(Align, dl, MVT::i32)};
17046 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
17047 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
17048 VTs, InstOps, MVT::i64,
17049 MachinePointerInfo(SV),
17051 /*Volatile=*/false,
17053 /*WriteMem=*/true);
17054 Chain = VAARG.getValue(1);
17056 // Load the next argument and return it
17057 return DAG.getLoad(ArgVT, dl, Chain, VAARG, MachinePointerInfo());
17060 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget &Subtarget,
17061 SelectionDAG &DAG) {
17062 // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
17063 // where a va_list is still an i8*.
17064 assert(Subtarget.is64Bit() && "This code only handles 64-bit va_copy!");
17065 if (Subtarget.isCallingConvWin64(
17066 DAG.getMachineFunction().getFunction()->getCallingConv()))
17067 // Probably a Win64 va_copy.
17068 return DAG.expandVACopy(Op.getNode());
17070 SDValue Chain = Op.getOperand(0);
17071 SDValue DstPtr = Op.getOperand(1);
17072 SDValue SrcPtr = Op.getOperand(2);
17073 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
17074 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17077 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
17078 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
17080 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
17083 /// Handle vector element shifts where the shift amount is a constant.
17084 /// Takes immediate version of shift as input.
17085 static SDValue getTargetVShiftByConstNode(unsigned Opc, const SDLoc &dl, MVT VT,
17086 SDValue SrcOp, uint64_t ShiftAmt,
17087 SelectionDAG &DAG) {
17088 MVT ElementType = VT.getVectorElementType();
17090 // Fold this packed shift into its first operand if ShiftAmt is 0.
17094 // Check for ShiftAmt >= element width
17095 if (ShiftAmt >= ElementType.getSizeInBits()) {
17096 if (Opc == X86ISD::VSRAI)
17097 ShiftAmt = ElementType.getSizeInBits() - 1;
17099 return DAG.getConstant(0, dl, VT);
17102 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
17103 && "Unknown target vector shift-by-constant node");
17105 // Fold this packed vector shift into a build vector if SrcOp is a
17106 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
17107 if (VT == SrcOp.getSimpleValueType() &&
17108 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
17109 SmallVector<SDValue, 8> Elts;
17110 unsigned NumElts = SrcOp->getNumOperands();
17111 ConstantSDNode *ND;
17114 default: llvm_unreachable("Unknown opcode!");
17115 case X86ISD::VSHLI:
17116 for (unsigned i=0; i!=NumElts; ++i) {
17117 SDValue CurrentOp = SrcOp->getOperand(i);
17118 if (CurrentOp->isUndef()) {
17119 Elts.push_back(CurrentOp);
17122 ND = cast<ConstantSDNode>(CurrentOp);
17123 const APInt &C = ND->getAPIntValue();
17124 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
17127 case X86ISD::VSRLI:
17128 for (unsigned i=0; i!=NumElts; ++i) {
17129 SDValue CurrentOp = SrcOp->getOperand(i);
17130 if (CurrentOp->isUndef()) {
17131 Elts.push_back(CurrentOp);
17134 ND = cast<ConstantSDNode>(CurrentOp);
17135 const APInt &C = ND->getAPIntValue();
17136 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
17139 case X86ISD::VSRAI:
17140 for (unsigned i=0; i!=NumElts; ++i) {
17141 SDValue CurrentOp = SrcOp->getOperand(i);
17142 if (CurrentOp->isUndef()) {
17143 Elts.push_back(CurrentOp);
17146 ND = cast<ConstantSDNode>(CurrentOp);
17147 const APInt &C = ND->getAPIntValue();
17148 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
17153 return DAG.getBuildVector(VT, dl, Elts);
17156 return DAG.getNode(Opc, dl, VT, SrcOp,
17157 DAG.getConstant(ShiftAmt, dl, MVT::i8));
17160 /// Handle vector element shifts where the shift amount may or may not be a
17161 /// constant. Takes immediate version of shift as input.
17162 static SDValue getTargetVShiftNode(unsigned Opc, const SDLoc &dl, MVT VT,
17163 SDValue SrcOp, SDValue ShAmt,
17164 SelectionDAG &DAG) {
17165 MVT SVT = ShAmt.getSimpleValueType();
17166 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
17168 // Catch shift-by-constant.
17169 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
17170 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
17171 CShAmt->getZExtValue(), DAG);
17173 // Change opcode to non-immediate version
17175 default: llvm_unreachable("Unknown target vector shift node");
17176 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
17177 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
17178 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
17181 const X86Subtarget &Subtarget =
17182 static_cast<const X86Subtarget &>(DAG.getSubtarget());
17183 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
17184 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
17185 // Let the shuffle legalizer expand this shift amount node.
17186 SDValue Op0 = ShAmt.getOperand(0);
17187 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
17188 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, Subtarget, DAG);
17190 // Need to build a vector containing shift amount.
17191 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
17192 SmallVector<SDValue, 4> ShOps;
17193 ShOps.push_back(ShAmt);
17194 if (SVT == MVT::i32) {
17195 ShOps.push_back(DAG.getConstant(0, dl, SVT));
17196 ShOps.push_back(DAG.getUNDEF(SVT));
17198 ShOps.push_back(DAG.getUNDEF(SVT));
17200 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
17201 ShAmt = DAG.getBuildVector(BVT, dl, ShOps);
17204 // The return type has to be a 128-bit type with the same element
17205 // type as the input type.
17206 MVT EltVT = VT.getVectorElementType();
17207 MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
17209 ShAmt = DAG.getBitcast(ShVT, ShAmt);
17210 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
17213 /// \brief Return Mask with the necessary casting or extending
17214 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
17215 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
17216 const X86Subtarget &Subtarget, SelectionDAG &DAG,
17219 if (isAllOnesConstant(Mask))
17220 return DAG.getTargetConstant(1, dl, MaskVT);
17221 if (X86::isZeroNode(Mask))
17222 return DAG.getTargetConstant(0, dl, MaskVT);
17224 if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
17225 // Mask should be extended
17226 Mask = DAG.getNode(ISD::ANY_EXTEND, dl,
17227 MVT::getIntegerVT(MaskVT.getSizeInBits()), Mask);
17230 if (Mask.getSimpleValueType() == MVT::i64 && Subtarget.is32Bit()) {
17231 if (MaskVT == MVT::v64i1) {
17232 assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
17233 // In case 32bit mode, bitcast i64 is illegal, extend/split it.
17235 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
17236 DAG.getConstant(0, dl, MVT::i32));
17237 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
17238 DAG.getConstant(1, dl, MVT::i32));
17240 Lo = DAG.getBitcast(MVT::v32i1, Lo);
17241 Hi = DAG.getBitcast(MVT::v32i1, Hi);
17243 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
17245 // MaskVT require < 64bit. Truncate mask (should succeed in any case),
17247 MVT TruncVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
17248 return DAG.getBitcast(MaskVT,
17249 DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Mask));
17253 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17254 Mask.getSimpleValueType().getSizeInBits());
17255 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17256 // are extracted by EXTRACT_SUBVECTOR.
17257 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17258 DAG.getBitcast(BitcastVT, Mask),
17259 DAG.getIntPtrConstant(0, dl));
17263 /// \brief Return (and \p Op, \p Mask) for compare instructions or
17264 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
17265 /// necessary casting or extending for \p Mask when lowering masking intrinsics
17266 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
17267 SDValue PreservedSrc,
17268 const X86Subtarget &Subtarget,
17269 SelectionDAG &DAG) {
17270 MVT VT = Op.getSimpleValueType();
17271 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17272 unsigned OpcodeSelect = ISD::VSELECT;
17275 if (isAllOnesConstant(Mask))
17278 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
17280 switch (Op.getOpcode()) {
17282 case X86ISD::PCMPEQM:
17283 case X86ISD::PCMPGTM:
17285 case X86ISD::CMPMU:
17286 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
17287 case X86ISD::VFPCLASS:
17288 case X86ISD::VFPCLASSS:
17289 return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
17290 case X86ISD::VTRUNC:
17291 case X86ISD::VTRUNCS:
17292 case X86ISD::VTRUNCUS:
17293 case ISD::FP_TO_FP16:
17294 // We can't use ISD::VSELECT here because it is not always "Legal"
17295 // for the destination type. For example vpmovqb require only AVX512
17296 // and vselect that can operate on byte element type require BWI
17297 OpcodeSelect = X86ISD::SELECT;
17300 if (PreservedSrc.isUndef())
17301 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
17302 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
17305 /// \brief Creates an SDNode for a predicated scalar operation.
17306 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
17307 /// The mask is coming as MVT::i8 and it should be truncated
17308 /// to MVT::i1 while lowering masking intrinsics.
17309 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
17310 /// "X86select" instead of "vselect". We just can't create the "vselect" node
17311 /// for a scalar instruction.
17312 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
17313 SDValue PreservedSrc,
17314 const X86Subtarget &Subtarget,
17315 SelectionDAG &DAG) {
17316 if (isAllOnesConstant(Mask))
17319 MVT VT = Op.getSimpleValueType();
17321 // The mask should be of type MVT::i1
17322 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
17324 if (Op.getOpcode() == X86ISD::FSETCC)
17325 return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
17326 if (Op.getOpcode() == X86ISD::VFPCLASS ||
17327 Op.getOpcode() == X86ISD::VFPCLASSS)
17328 return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
17330 if (PreservedSrc.isUndef())
17331 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
17332 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
17335 static int getSEHRegistrationNodeSize(const Function *Fn) {
17336 if (!Fn->hasPersonalityFn())
17337 report_fatal_error(
17338 "querying registration node size for function without personality");
17339 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
17340 // WinEHStatePass for the full struct definition.
17341 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
17342 case EHPersonality::MSVC_X86SEH: return 24;
17343 case EHPersonality::MSVC_CXX: return 16;
17346 report_fatal_error(
17347 "can only recover FP for 32-bit MSVC EH personality functions");
17350 /// When the MSVC runtime transfers control to us, either to an outlined
17351 /// function or when returning to a parent frame after catching an exception, we
17352 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
17353 /// Here's the math:
17354 /// RegNodeBase = EntryEBP - RegNodeSize
17355 /// ParentFP = RegNodeBase - ParentFrameOffset
17356 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
17357 /// subtracting the offset (negative on x86) takes us back to the parent FP.
17358 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
17359 SDValue EntryEBP) {
17360 MachineFunction &MF = DAG.getMachineFunction();
17363 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17364 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
17366 // It's possible that the parent function no longer has a personality function
17367 // if the exceptional code was optimized away, in which case we just return
17368 // the incoming EBP.
17369 if (!Fn->hasPersonalityFn())
17372 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
17373 // registration, or the .set_setframe offset.
17374 MCSymbol *OffsetSym =
17375 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
17376 GlobalValue::getRealLinkageName(Fn->getName()));
17377 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
17378 SDValue ParentFrameOffset =
17379 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
17381 // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
17382 // prologue to RBP in the parent function.
17383 const X86Subtarget &Subtarget =
17384 static_cast<const X86Subtarget &>(DAG.getSubtarget());
17385 if (Subtarget.is64Bit())
17386 return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
17388 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
17389 // RegNodeBase = EntryEBP - RegNodeSize
17390 // ParentFP = RegNodeBase - ParentFrameOffset
17391 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
17392 DAG.getConstant(RegNodeSize, dl, PtrVT));
17393 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
17396 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget &Subtarget,
17397 SelectionDAG &DAG) {
17399 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17400 MVT VT = Op.getSimpleValueType();
17401 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
17403 switch(IntrData->Type) {
17404 case INTR_TYPE_1OP:
17405 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
17406 case INTR_TYPE_2OP:
17407 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
17409 case INTR_TYPE_2OP_IMM8:
17410 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
17411 DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
17412 case INTR_TYPE_3OP:
17413 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
17414 Op.getOperand(2), Op.getOperand(3));
17415 case INTR_TYPE_4OP:
17416 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
17417 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
17418 case INTR_TYPE_1OP_MASK_RM: {
17419 SDValue Src = Op.getOperand(1);
17420 SDValue PassThru = Op.getOperand(2);
17421 SDValue Mask = Op.getOperand(3);
17422 SDValue RoundingMode;
17423 // We allways add rounding mode to the Node.
17424 // If the rounding mode is not specified, we add the
17425 // "current direction" mode.
17426 if (Op.getNumOperands() == 4)
17428 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
17430 RoundingMode = Op.getOperand(4);
17431 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
17432 if (IntrWithRoundingModeOpcode != 0)
17433 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
17434 X86::STATIC_ROUNDING::CUR_DIRECTION)
17435 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
17436 dl, Op.getValueType(), Src, RoundingMode),
17437 Mask, PassThru, Subtarget, DAG);
17438 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
17440 Mask, PassThru, Subtarget, DAG);
17442 case INTR_TYPE_1OP_MASK: {
17443 SDValue Src = Op.getOperand(1);
17444 SDValue PassThru = Op.getOperand(2);
17445 SDValue Mask = Op.getOperand(3);
17446 // We add rounding mode to the Node when
17447 // - RM Opcode is specified and
17448 // - RM is not "current direction".
17449 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
17450 if (IntrWithRoundingModeOpcode != 0) {
17451 SDValue Rnd = Op.getOperand(4);
17452 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
17453 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
17454 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
17455 dl, Op.getValueType(),
17457 Mask, PassThru, Subtarget, DAG);
17460 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
17461 Mask, PassThru, Subtarget, DAG);
17463 case INTR_TYPE_SCALAR_MASK: {
17464 SDValue Src1 = Op.getOperand(1);
17465 SDValue Src2 = Op.getOperand(2);
17466 SDValue passThru = Op.getOperand(3);
17467 SDValue Mask = Op.getOperand(4);
17468 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
17469 Mask, passThru, Subtarget, DAG);
17471 case INTR_TYPE_SCALAR_MASK_RM: {
17472 SDValue Src1 = Op.getOperand(1);
17473 SDValue Src2 = Op.getOperand(2);
17474 SDValue Src0 = Op.getOperand(3);
17475 SDValue Mask = Op.getOperand(4);
17476 // There are 2 kinds of intrinsics in this group:
17477 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
17478 // (2) With rounding mode and sae - 7 operands.
17479 if (Op.getNumOperands() == 6) {
17480 SDValue Sae = Op.getOperand(5);
17481 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
17482 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
17484 Mask, Src0, Subtarget, DAG);
17486 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
17487 SDValue RoundingMode = Op.getOperand(5);
17488 SDValue Sae = Op.getOperand(6);
17489 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
17490 RoundingMode, Sae),
17491 Mask, Src0, Subtarget, DAG);
17493 case INTR_TYPE_2OP_MASK:
17494 case INTR_TYPE_2OP_IMM8_MASK: {
17495 SDValue Src1 = Op.getOperand(1);
17496 SDValue Src2 = Op.getOperand(2);
17497 SDValue PassThru = Op.getOperand(3);
17498 SDValue Mask = Op.getOperand(4);
17500 if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
17501 Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
17503 // We specify 2 possible opcodes for intrinsics with rounding modes.
17504 // First, we check if the intrinsic may have non-default rounding mode,
17505 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
17506 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
17507 if (IntrWithRoundingModeOpcode != 0) {
17508 SDValue Rnd = Op.getOperand(5);
17509 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
17510 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
17511 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
17512 dl, Op.getValueType(),
17514 Mask, PassThru, Subtarget, DAG);
17517 // TODO: Intrinsics should have fast-math-flags to propagate.
17518 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
17519 Mask, PassThru, Subtarget, DAG);
17521 case INTR_TYPE_2OP_MASK_RM: {
17522 SDValue Src1 = Op.getOperand(1);
17523 SDValue Src2 = Op.getOperand(2);
17524 SDValue PassThru = Op.getOperand(3);
17525 SDValue Mask = Op.getOperand(4);
17526 // We specify 2 possible modes for intrinsics, with/without rounding
17528 // First, we check if the intrinsic have rounding mode (6 operands),
17529 // if not, we set rounding mode to "current".
17531 if (Op.getNumOperands() == 6)
17532 Rnd = Op.getOperand(5);
17534 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
17535 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
17537 Mask, PassThru, Subtarget, DAG);
17539 case INTR_TYPE_3OP_SCALAR_MASK_RM: {
17540 SDValue Src1 = Op.getOperand(1);
17541 SDValue Src2 = Op.getOperand(2);
17542 SDValue Src3 = Op.getOperand(3);
17543 SDValue PassThru = Op.getOperand(4);
17544 SDValue Mask = Op.getOperand(5);
17545 SDValue Sae = Op.getOperand(6);
17547 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
17549 Mask, PassThru, Subtarget, DAG);
17551 case INTR_TYPE_3OP_MASK_RM: {
17552 SDValue Src1 = Op.getOperand(1);
17553 SDValue Src2 = Op.getOperand(2);
17554 SDValue Imm = Op.getOperand(3);
17555 SDValue PassThru = Op.getOperand(4);
17556 SDValue Mask = Op.getOperand(5);
17557 // We specify 2 possible modes for intrinsics, with/without rounding
17559 // First, we check if the intrinsic have rounding mode (7 operands),
17560 // if not, we set rounding mode to "current".
17562 if (Op.getNumOperands() == 7)
17563 Rnd = Op.getOperand(6);
17565 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
17566 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
17567 Src1, Src2, Imm, Rnd),
17568 Mask, PassThru, Subtarget, DAG);
17570 case INTR_TYPE_3OP_IMM8_MASK:
17571 case INTR_TYPE_3OP_MASK:
17572 case INSERT_SUBVEC: {
17573 SDValue Src1 = Op.getOperand(1);
17574 SDValue Src2 = Op.getOperand(2);
17575 SDValue Src3 = Op.getOperand(3);
17576 SDValue PassThru = Op.getOperand(4);
17577 SDValue Mask = Op.getOperand(5);
17579 if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
17580 Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
17581 else if (IntrData->Type == INSERT_SUBVEC) {
17582 // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
17583 assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
17584 unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
17585 Imm *= Src2.getSimpleValueType().getVectorNumElements();
17586 Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
17589 // We specify 2 possible opcodes for intrinsics with rounding modes.
17590 // First, we check if the intrinsic may have non-default rounding mode,
17591 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
17592 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
17593 if (IntrWithRoundingModeOpcode != 0) {
17594 SDValue Rnd = Op.getOperand(6);
17595 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
17596 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
17597 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
17598 dl, Op.getValueType(),
17599 Src1, Src2, Src3, Rnd),
17600 Mask, PassThru, Subtarget, DAG);
17603 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
17605 Mask, PassThru, Subtarget, DAG);
17607 case VPERM_2OP_MASK : {
17608 SDValue Src1 = Op.getOperand(1);
17609 SDValue Src2 = Op.getOperand(2);
17610 SDValue PassThru = Op.getOperand(3);
17611 SDValue Mask = Op.getOperand(4);
17613 // Swap Src1 and Src2 in the node creation
17614 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src2, Src1),
17615 Mask, PassThru, Subtarget, DAG);
17617 case VPERM_3OP_MASKZ:
17618 case VPERM_3OP_MASK:{
17619 // Src2 is the PassThru
17620 SDValue Src1 = Op.getOperand(1);
17621 SDValue Src2 = Op.getOperand(2);
17622 SDValue Src3 = Op.getOperand(3);
17623 SDValue Mask = Op.getOperand(4);
17624 MVT VT = Op.getSimpleValueType();
17625 SDValue PassThru = SDValue();
17627 // set PassThru element
17628 if (IntrData->Type == VPERM_3OP_MASKZ)
17629 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
17631 PassThru = DAG.getBitcast(VT, Src2);
17633 // Swap Src1 and Src2 in the node creation
17634 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
17635 dl, Op.getValueType(),
17637 Mask, PassThru, Subtarget, DAG);
17641 case FMA_OP_MASK: {
17642 SDValue Src1 = Op.getOperand(1);
17643 SDValue Src2 = Op.getOperand(2);
17644 SDValue Src3 = Op.getOperand(3);
17645 SDValue Mask = Op.getOperand(4);
17646 MVT VT = Op.getSimpleValueType();
17647 SDValue PassThru = SDValue();
17649 // set PassThru element
17650 if (IntrData->Type == FMA_OP_MASKZ)
17651 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
17652 else if (IntrData->Type == FMA_OP_MASK3)
17657 // We specify 2 possible opcodes for intrinsics with rounding modes.
17658 // First, we check if the intrinsic may have non-default rounding mode,
17659 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
17660 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
17661 if (IntrWithRoundingModeOpcode != 0) {
17662 SDValue Rnd = Op.getOperand(5);
17663 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
17664 X86::STATIC_ROUNDING::CUR_DIRECTION)
17665 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
17666 dl, Op.getValueType(),
17667 Src1, Src2, Src3, Rnd),
17668 Mask, PassThru, Subtarget, DAG);
17670 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
17671 dl, Op.getValueType(),
17673 Mask, PassThru, Subtarget, DAG);
17675 case FMA_OP_SCALAR_MASK:
17676 case FMA_OP_SCALAR_MASK3:
17677 case FMA_OP_SCALAR_MASKZ: {
17678 SDValue Src1 = Op.getOperand(1);
17679 SDValue Src2 = Op.getOperand(2);
17680 SDValue Src3 = Op.getOperand(3);
17681 SDValue Mask = Op.getOperand(4);
17682 MVT VT = Op.getSimpleValueType();
17683 SDValue PassThru = SDValue();
17685 // set PassThru element
17686 if (IntrData->Type == FMA_OP_SCALAR_MASKZ)
17687 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
17688 else if (IntrData->Type == FMA_OP_SCALAR_MASK3)
17693 SDValue Rnd = Op.getOperand(5);
17694 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl,
17695 Op.getValueType(), Src1, Src2,
17697 Mask, PassThru, Subtarget, DAG);
17699 case TERLOG_OP_MASK:
17700 case TERLOG_OP_MASKZ: {
17701 SDValue Src1 = Op.getOperand(1);
17702 SDValue Src2 = Op.getOperand(2);
17703 SDValue Src3 = Op.getOperand(3);
17704 SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
17705 SDValue Mask = Op.getOperand(5);
17706 MVT VT = Op.getSimpleValueType();
17707 SDValue PassThru = Src1;
17708 // Set PassThru element.
17709 if (IntrData->Type == TERLOG_OP_MASKZ)
17710 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
17712 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
17713 Src1, Src2, Src3, Src4),
17714 Mask, PassThru, Subtarget, DAG);
17717 // FPclass intrinsics with mask
17718 SDValue Src1 = Op.getOperand(1);
17719 MVT VT = Src1.getSimpleValueType();
17720 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17721 SDValue Imm = Op.getOperand(2);
17722 SDValue Mask = Op.getOperand(3);
17723 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17724 Mask.getSimpleValueType().getSizeInBits());
17725 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
17726 SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
17727 DAG.getTargetConstant(0, dl, MaskVT),
17729 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
17730 DAG.getUNDEF(BitcastVT), FPclassMask,
17731 DAG.getIntPtrConstant(0, dl));
17732 return DAG.getBitcast(Op.getValueType(), Res);
17735 SDValue Src1 = Op.getOperand(1);
17736 SDValue Imm = Op.getOperand(2);
17737 SDValue Mask = Op.getOperand(3);
17738 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
17739 SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
17740 DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
17741 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
17744 case CMP_MASK_CC: {
17745 // Comparison intrinsics with masks.
17746 // Example of transformation:
17747 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
17748 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
17750 // (v8i1 (insert_subvector undef,
17751 // (v2i1 (and (PCMPEQM %a, %b),
17752 // (extract_subvector
17753 // (v8i1 (bitcast %mask)), 0))), 0))))
17754 MVT VT = Op.getOperand(1).getSimpleValueType();
17755 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17756 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
17757 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17758 Mask.getSimpleValueType().getSizeInBits());
17760 if (IntrData->Type == CMP_MASK_CC) {
17761 SDValue CC = Op.getOperand(3);
17762 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
17763 // We specify 2 possible opcodes for intrinsics with rounding modes.
17764 // First, we check if the intrinsic may have non-default rounding mode,
17765 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
17766 if (IntrData->Opc1 != 0) {
17767 SDValue Rnd = Op.getOperand(5);
17768 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
17769 X86::STATIC_ROUNDING::CUR_DIRECTION)
17770 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
17771 Op.getOperand(2), CC, Rnd);
17773 //default rounding mode
17775 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
17776 Op.getOperand(2), CC);
17779 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
17780 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
17783 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
17784 DAG.getTargetConstant(0, dl,
17787 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
17788 DAG.getUNDEF(BitcastVT), CmpMask,
17789 DAG.getIntPtrConstant(0, dl));
17790 return DAG.getBitcast(Op.getValueType(), Res);
17792 case CMP_MASK_SCALAR_CC: {
17793 SDValue Src1 = Op.getOperand(1);
17794 SDValue Src2 = Op.getOperand(2);
17795 SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
17796 SDValue Mask = Op.getOperand(4);
17799 if (IntrData->Opc1 != 0) {
17800 SDValue Rnd = Op.getOperand(5);
17801 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
17802 X86::STATIC_ROUNDING::CUR_DIRECTION)
17803 Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
17805 //default rounding mode
17807 Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
17809 SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
17810 DAG.getTargetConstant(0, dl,
17814 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, CmpMask);
17816 case COMI: { // Comparison intrinsics
17817 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
17818 SDValue LHS = Op.getOperand(1);
17819 SDValue RHS = Op.getOperand(2);
17820 SDValue Comi = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
17821 SDValue InvComi = DAG.getNode(IntrData->Opc0, dl, MVT::i32, RHS, LHS);
17824 case ISD::SETEQ: { // (ZF = 0 and PF = 0)
17825 SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17826 DAG.getConstant(X86::COND_E, dl, MVT::i8), Comi);
17827 SDValue SetNP = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17828 DAG.getConstant(X86::COND_NP, dl, MVT::i8),
17830 SetCC = DAG.getNode(ISD::AND, dl, MVT::i8, SetCC, SetNP);
17833 case ISD::SETNE: { // (ZF = 1 or PF = 1)
17834 SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17835 DAG.getConstant(X86::COND_NE, dl, MVT::i8), Comi);
17836 SDValue SetP = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17837 DAG.getConstant(X86::COND_P, dl, MVT::i8),
17839 SetCC = DAG.getNode(ISD::OR, dl, MVT::i8, SetCC, SetP);
17842 case ISD::SETGT: // (CF = 0 and ZF = 0)
17843 SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17844 DAG.getConstant(X86::COND_A, dl, MVT::i8), Comi);
17846 case ISD::SETLT: { // The condition is opposite to GT. Swap the operands.
17847 SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17848 DAG.getConstant(X86::COND_A, dl, MVT::i8), InvComi);
17851 case ISD::SETGE: // CF = 0
17852 SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17853 DAG.getConstant(X86::COND_AE, dl, MVT::i8), Comi);
17855 case ISD::SETLE: // The condition is opposite to GE. Swap the operands.
17856 SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17857 DAG.getConstant(X86::COND_AE, dl, MVT::i8), InvComi);
17860 llvm_unreachable("Unexpected illegal condition!");
17862 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17864 case COMI_RM: { // Comparison intrinsics with Sae
17865 SDValue LHS = Op.getOperand(1);
17866 SDValue RHS = Op.getOperand(2);
17867 unsigned CondVal = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
17868 SDValue Sae = Op.getOperand(4);
17871 if (cast<ConstantSDNode>(Sae)->getZExtValue() ==
17872 X86::STATIC_ROUNDING::CUR_DIRECTION)
17873 FCmp = DAG.getNode(X86ISD::FSETCC, dl, MVT::i1, LHS, RHS,
17874 DAG.getConstant(CondVal, dl, MVT::i8));
17876 FCmp = DAG.getNode(X86ISD::FSETCC, dl, MVT::i1, LHS, RHS,
17877 DAG.getConstant(CondVal, dl, MVT::i8), Sae);
17878 // AnyExt just uses KMOVW %kreg, %r32; ZeroExt emits "and $1, %reg"
17879 return DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, FCmp);
17882 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
17883 Op.getOperand(1), Op.getOperand(2), DAG);
17884 case COMPRESS_EXPAND_IN_REG: {
17885 SDValue Mask = Op.getOperand(3);
17886 SDValue DataToCompress = Op.getOperand(1);
17887 SDValue PassThru = Op.getOperand(2);
17888 if (isAllOnesConstant(Mask)) // return data as is
17889 return Op.getOperand(1);
17891 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
17893 Mask, PassThru, Subtarget, DAG);
17896 SDValue Mask = Op.getOperand(1);
17897 MVT MaskVT = MVT::getVectorVT(MVT::i1,
17898 Mask.getSimpleValueType().getSizeInBits());
17899 Mask = DAG.getBitcast(MaskVT, Mask);
17900 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Mask);
17903 MVT VT = Op.getSimpleValueType();
17904 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits()/2);
17906 SDValue Src1 = getMaskNode(Op.getOperand(1), MaskVT, Subtarget, DAG, dl);
17907 SDValue Src2 = getMaskNode(Op.getOperand(2), MaskVT, Subtarget, DAG, dl);
17908 // Arguments should be swapped.
17909 SDValue Res = DAG.getNode(IntrData->Opc0, dl,
17910 MVT::getVectorVT(MVT::i1, VT.getSizeInBits()),
17912 return DAG.getBitcast(VT, Res);
17915 case FIXUPIMMS_MASKZ:
17917 case FIXUPIMM_MASKZ:{
17918 SDValue Src1 = Op.getOperand(1);
17919 SDValue Src2 = Op.getOperand(2);
17920 SDValue Src3 = Op.getOperand(3);
17921 SDValue Imm = Op.getOperand(4);
17922 SDValue Mask = Op.getOperand(5);
17923 SDValue Passthru = (IntrData->Type == FIXUPIMM || IntrData->Type == FIXUPIMMS ) ?
17924 Src1 : getZeroVector(VT, Subtarget, DAG, dl);
17925 // We specify 2 possible modes for intrinsics, with/without rounding
17927 // First, we check if the intrinsic have rounding mode (7 operands),
17928 // if not, we set rounding mode to "current".
17930 if (Op.getNumOperands() == 7)
17931 Rnd = Op.getOperand(6);
17933 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
17934 if (IntrData->Type == FIXUPIMM || IntrData->Type == FIXUPIMM_MASKZ)
17935 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
17936 Src1, Src2, Src3, Imm, Rnd),
17937 Mask, Passthru, Subtarget, DAG);
17938 else // Scalar - FIXUPIMMS, FIXUPIMMS_MASKZ
17939 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
17940 Src1, Src2, Src3, Imm, Rnd),
17941 Mask, Passthru, Subtarget, DAG);
17943 case CONVERT_TO_MASK: {
17944 MVT SrcVT = Op.getOperand(1).getSimpleValueType();
17945 MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
17946 MVT BitcastVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits());
17948 SDValue CvtMask = DAG.getNode(IntrData->Opc0, dl, MaskVT,
17950 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
17951 DAG.getUNDEF(BitcastVT), CvtMask,
17952 DAG.getIntPtrConstant(0, dl));
17953 return DAG.getBitcast(Op.getValueType(), Res);
17955 case CONVERT_MASK_TO_VEC: {
17956 SDValue Mask = Op.getOperand(1);
17957 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17958 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
17959 return DAG.getNode(IntrData->Opc0, dl, VT, VMask);
17961 case BRCST_SUBVEC_TO_VEC: {
17962 SDValue Src = Op.getOperand(1);
17963 SDValue Passthru = Op.getOperand(2);
17964 SDValue Mask = Op.getOperand(3);
17965 EVT resVT = Passthru.getValueType();
17966 SDValue subVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, resVT,
17967 DAG.getUNDEF(resVT), Src,
17968 DAG.getIntPtrConstant(0, dl));
17970 if (Src.getSimpleValueType().is256BitVector() && resVT.is512BitVector())
17971 immVal = DAG.getConstant(0x44, dl, MVT::i8);
17973 immVal = DAG.getConstant(0, dl, MVT::i8);
17974 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
17975 subVec, subVec, immVal),
17976 Mask, Passthru, Subtarget, DAG);
17978 case BRCST32x2_TO_VEC: {
17979 SDValue Src = Op.getOperand(1);
17980 SDValue PassThru = Op.getOperand(2);
17981 SDValue Mask = Op.getOperand(3);
17983 assert((VT.getScalarType() == MVT::i32 ||
17984 VT.getScalarType() == MVT::f32) && "Unexpected type!");
17985 //bitcast Src to packed 64
17986 MVT ScalarVT = VT.getScalarType() == MVT::i32 ? MVT::i64 : MVT::f64;
17987 MVT BitcastVT = MVT::getVectorVT(ScalarVT, Src.getValueSizeInBits()/64);
17988 Src = DAG.getBitcast(BitcastVT, Src);
17990 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
17991 Mask, PassThru, Subtarget, DAG);
17999 default: return SDValue(); // Don't custom lower most intrinsics.
18001 case Intrinsic::x86_avx2_permd:
18002 case Intrinsic::x86_avx2_permps:
18003 // Operands intentionally swapped. Mask is last operand to intrinsic,
18004 // but second operand for node/instruction.
18005 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
18006 Op.getOperand(2), Op.getOperand(1));
18008 // ptest and testp intrinsics. The intrinsic these come from are designed to
18009 // return an integer value, not just an instruction so lower it to the ptest
18010 // or testp pattern and a setcc for the result.
18011 case Intrinsic::x86_sse41_ptestz:
18012 case Intrinsic::x86_sse41_ptestc:
18013 case Intrinsic::x86_sse41_ptestnzc:
18014 case Intrinsic::x86_avx_ptestz_256:
18015 case Intrinsic::x86_avx_ptestc_256:
18016 case Intrinsic::x86_avx_ptestnzc_256:
18017 case Intrinsic::x86_avx_vtestz_ps:
18018 case Intrinsic::x86_avx_vtestc_ps:
18019 case Intrinsic::x86_avx_vtestnzc_ps:
18020 case Intrinsic::x86_avx_vtestz_pd:
18021 case Intrinsic::x86_avx_vtestc_pd:
18022 case Intrinsic::x86_avx_vtestnzc_pd:
18023 case Intrinsic::x86_avx_vtestz_ps_256:
18024 case Intrinsic::x86_avx_vtestc_ps_256:
18025 case Intrinsic::x86_avx_vtestnzc_ps_256:
18026 case Intrinsic::x86_avx_vtestz_pd_256:
18027 case Intrinsic::x86_avx_vtestc_pd_256:
18028 case Intrinsic::x86_avx_vtestnzc_pd_256: {
18029 bool IsTestPacked = false;
18032 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
18033 case Intrinsic::x86_avx_vtestz_ps:
18034 case Intrinsic::x86_avx_vtestz_pd:
18035 case Intrinsic::x86_avx_vtestz_ps_256:
18036 case Intrinsic::x86_avx_vtestz_pd_256:
18037 IsTestPacked = true; // Fallthrough
18038 case Intrinsic::x86_sse41_ptestz:
18039 case Intrinsic::x86_avx_ptestz_256:
18041 X86CC = X86::COND_E;
18043 case Intrinsic::x86_avx_vtestc_ps:
18044 case Intrinsic::x86_avx_vtestc_pd:
18045 case Intrinsic::x86_avx_vtestc_ps_256:
18046 case Intrinsic::x86_avx_vtestc_pd_256:
18047 IsTestPacked = true; // Fallthrough
18048 case Intrinsic::x86_sse41_ptestc:
18049 case Intrinsic::x86_avx_ptestc_256:
18051 X86CC = X86::COND_B;
18053 case Intrinsic::x86_avx_vtestnzc_ps:
18054 case Intrinsic::x86_avx_vtestnzc_pd:
18055 case Intrinsic::x86_avx_vtestnzc_ps_256:
18056 case Intrinsic::x86_avx_vtestnzc_pd_256:
18057 IsTestPacked = true; // Fallthrough
18058 case Intrinsic::x86_sse41_ptestnzc:
18059 case Intrinsic::x86_avx_ptestnzc_256:
18061 X86CC = X86::COND_A;
18065 SDValue LHS = Op.getOperand(1);
18066 SDValue RHS = Op.getOperand(2);
18067 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
18068 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
18069 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
18070 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
18071 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
18073 case Intrinsic::x86_avx512_kortestz_w:
18074 case Intrinsic::x86_avx512_kortestc_w: {
18075 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
18076 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
18077 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
18078 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
18079 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
18080 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
18081 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
18084 case Intrinsic::x86_sse42_pcmpistria128:
18085 case Intrinsic::x86_sse42_pcmpestria128:
18086 case Intrinsic::x86_sse42_pcmpistric128:
18087 case Intrinsic::x86_sse42_pcmpestric128:
18088 case Intrinsic::x86_sse42_pcmpistrio128:
18089 case Intrinsic::x86_sse42_pcmpestrio128:
18090 case Intrinsic::x86_sse42_pcmpistris128:
18091 case Intrinsic::x86_sse42_pcmpestris128:
18092 case Intrinsic::x86_sse42_pcmpistriz128:
18093 case Intrinsic::x86_sse42_pcmpestriz128: {
18097 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
18098 case Intrinsic::x86_sse42_pcmpistria128:
18099 Opcode = X86ISD::PCMPISTRI;
18100 X86CC = X86::COND_A;
18102 case Intrinsic::x86_sse42_pcmpestria128:
18103 Opcode = X86ISD::PCMPESTRI;
18104 X86CC = X86::COND_A;
18106 case Intrinsic::x86_sse42_pcmpistric128:
18107 Opcode = X86ISD::PCMPISTRI;
18108 X86CC = X86::COND_B;
18110 case Intrinsic::x86_sse42_pcmpestric128:
18111 Opcode = X86ISD::PCMPESTRI;
18112 X86CC = X86::COND_B;
18114 case Intrinsic::x86_sse42_pcmpistrio128:
18115 Opcode = X86ISD::PCMPISTRI;
18116 X86CC = X86::COND_O;
18118 case Intrinsic::x86_sse42_pcmpestrio128:
18119 Opcode = X86ISD::PCMPESTRI;
18120 X86CC = X86::COND_O;
18122 case Intrinsic::x86_sse42_pcmpistris128:
18123 Opcode = X86ISD::PCMPISTRI;
18124 X86CC = X86::COND_S;
18126 case Intrinsic::x86_sse42_pcmpestris128:
18127 Opcode = X86ISD::PCMPESTRI;
18128 X86CC = X86::COND_S;
18130 case Intrinsic::x86_sse42_pcmpistriz128:
18131 Opcode = X86ISD::PCMPISTRI;
18132 X86CC = X86::COND_E;
18134 case Intrinsic::x86_sse42_pcmpestriz128:
18135 Opcode = X86ISD::PCMPESTRI;
18136 X86CC = X86::COND_E;
18139 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
18140 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
18141 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
18142 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18143 DAG.getConstant(X86CC, dl, MVT::i8),
18144 SDValue(PCMP.getNode(), 1));
18145 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
18148 case Intrinsic::x86_sse42_pcmpistri128:
18149 case Intrinsic::x86_sse42_pcmpestri128: {
18151 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
18152 Opcode = X86ISD::PCMPISTRI;
18154 Opcode = X86ISD::PCMPESTRI;
18156 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
18157 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
18158 return DAG.getNode(Opcode, dl, VTs, NewOps);
18161 case Intrinsic::eh_sjlj_lsda: {
18162 MachineFunction &MF = DAG.getMachineFunction();
18163 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18164 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
18165 auto &Context = MF.getMMI().getContext();
18166 MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
18167 Twine(MF.getFunctionNumber()));
18168 return DAG.getNode(X86ISD::Wrapper, dl, VT, DAG.getMCSymbol(S, PtrVT));
18171 case Intrinsic::x86_seh_lsda: {
18172 // Compute the symbol for the LSDA. We know it'll get emitted later.
18173 MachineFunction &MF = DAG.getMachineFunction();
18174 SDValue Op1 = Op.getOperand(1);
18175 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
18176 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
18177 GlobalValue::getRealLinkageName(Fn->getName()));
18179 // Generate a simple absolute symbol reference. This intrinsic is only
18180 // supported on 32-bit Windows, which isn't PIC.
18181 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
18182 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
18185 case Intrinsic::x86_seh_recoverfp: {
18186 SDValue FnOp = Op.getOperand(1);
18187 SDValue IncomingFPOp = Op.getOperand(2);
18188 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
18189 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
18191 report_fatal_error(
18192 "llvm.x86.seh.recoverfp must take a function as the first argument");
18193 return recoverFramePointer(DAG, Fn, IncomingFPOp);
18196 case Intrinsic::localaddress: {
18197 // Returns one of the stack, base, or frame pointer registers, depending on
18198 // which is used to reference local variables.
18199 MachineFunction &MF = DAG.getMachineFunction();
18200 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
18202 if (RegInfo->hasBasePointer(MF))
18203 Reg = RegInfo->getBaseRegister();
18204 else // This function handles the SP or FP case.
18205 Reg = RegInfo->getPtrSizedFrameRegister(MF);
18206 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
18211 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
18212 SDValue Src, SDValue Mask, SDValue Base,
18213 SDValue Index, SDValue ScaleOp, SDValue Chain,
18214 const X86Subtarget &Subtarget) {
18216 auto *C = cast<ConstantSDNode>(ScaleOp);
18217 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
18218 MVT MaskVT = MVT::getVectorVT(MVT::i1,
18219 Index.getSimpleValueType().getVectorNumElements());
18221 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
18222 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
18223 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
18224 SDValue Segment = DAG.getRegister(0, MVT::i32);
18226 Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
18227 SDValue Ops[] = {Src, VMask, Base, Scale, Index, Disp, Segment, Chain};
18228 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
18229 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
18230 return DAG.getMergeValues(RetOps, dl);
18233 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
18234 SDValue Src, SDValue Mask, SDValue Base,
18235 SDValue Index, SDValue ScaleOp, SDValue Chain,
18236 const X86Subtarget &Subtarget) {
18238 auto *C = cast<ConstantSDNode>(ScaleOp);
18239 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
18240 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
18241 SDValue Segment = DAG.getRegister(0, MVT::i32);
18242 MVT MaskVT = MVT::getVectorVT(MVT::i1,
18243 Index.getSimpleValueType().getVectorNumElements());
18245 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
18246 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
18247 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, VMask, Src, Chain};
18248 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
18249 return SDValue(Res, 1);
18252 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
18253 SDValue Mask, SDValue Base, SDValue Index,
18254 SDValue ScaleOp, SDValue Chain,
18255 const X86Subtarget &Subtarget) {
18257 auto *C = cast<ConstantSDNode>(ScaleOp);
18258 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
18259 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
18260 SDValue Segment = DAG.getRegister(0, MVT::i32);
18262 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
18263 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
18264 //SDVTList VTs = DAG.getVTList(MVT::Other);
18265 SDValue Ops[] = {VMask, Base, Scale, Index, Disp, Segment, Chain};
18266 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
18267 return SDValue(Res, 0);
18270 /// Handles the lowering of builtin intrinsics that read performance monitor
18271 /// counters (x86_rdpmc).
18272 static void getReadPerformanceCounter(SDNode *N, const SDLoc &DL,
18274 const X86Subtarget &Subtarget,
18275 SmallVectorImpl<SDValue> &Results) {
18276 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
18277 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18280 // The ECX register is used to select the index of the performance counter
18282 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
18284 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
18286 // Reads the content of a 64-bit performance counter and returns it in the
18287 // registers EDX:EAX.
18288 if (Subtarget.is64Bit()) {
18289 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
18290 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
18293 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
18294 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
18297 Chain = HI.getValue(1);
18299 if (Subtarget.is64Bit()) {
18300 // The EAX register is loaded with the low-order 32 bits. The EDX register
18301 // is loaded with the supported high-order bits of the counter.
18302 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
18303 DAG.getConstant(32, DL, MVT::i8));
18304 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
18305 Results.push_back(Chain);
18309 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
18310 SDValue Ops[] = { LO, HI };
18311 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
18312 Results.push_back(Pair);
18313 Results.push_back(Chain);
18316 /// Handles the lowering of builtin intrinsics that read the time stamp counter
18317 /// (x86_rdtsc and x86_rdtscp). This function is also used to custom lower
18318 /// READCYCLECOUNTER nodes.
18319 static void getReadTimeStampCounter(SDNode *N, const SDLoc &DL, unsigned Opcode,
18321 const X86Subtarget &Subtarget,
18322 SmallVectorImpl<SDValue> &Results) {
18323 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18324 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
18327 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
18328 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
18329 // and the EAX register is loaded with the low-order 32 bits.
18330 if (Subtarget.is64Bit()) {
18331 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
18332 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
18335 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
18336 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
18339 SDValue Chain = HI.getValue(1);
18341 if (Opcode == X86ISD::RDTSCP_DAG) {
18342 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
18344 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
18345 // the ECX register. Add 'ecx' explicitly to the chain.
18346 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
18348 // Explicitly store the content of ECX at the location passed in input
18349 // to the 'rdtscp' intrinsic.
18350 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
18351 MachinePointerInfo());
18354 if (Subtarget.is64Bit()) {
18355 // The EDX register is loaded with the high-order 32 bits of the MSR, and
18356 // the EAX register is loaded with the low-order 32 bits.
18357 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
18358 DAG.getConstant(32, DL, MVT::i8));
18359 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
18360 Results.push_back(Chain);
18364 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
18365 SDValue Ops[] = { LO, HI };
18366 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
18367 Results.push_back(Pair);
18368 Results.push_back(Chain);
18371 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget &Subtarget,
18372 SelectionDAG &DAG) {
18373 SmallVector<SDValue, 2> Results;
18375 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
18377 return DAG.getMergeValues(Results, DL);
18380 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
18381 MachineFunction &MF = DAG.getMachineFunction();
18382 SDValue Chain = Op.getOperand(0);
18383 SDValue RegNode = Op.getOperand(2);
18384 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
18386 report_fatal_error("EH registrations only live in functions using WinEH");
18388 // Cast the operand to an alloca, and remember the frame index.
18389 auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
18391 report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
18392 EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
18394 // Return the chain operand without making any DAG nodes.
18398 static SDValue MarkEHGuard(SDValue Op, SelectionDAG &DAG) {
18399 MachineFunction &MF = DAG.getMachineFunction();
18400 SDValue Chain = Op.getOperand(0);
18401 SDValue EHGuard = Op.getOperand(2);
18402 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
18404 report_fatal_error("EHGuard only live in functions using WinEH");
18406 // Cast the operand to an alloca, and remember the frame index.
18407 auto *FINode = dyn_cast<FrameIndexSDNode>(EHGuard);
18409 report_fatal_error("llvm.x86.seh.ehguard expects a static alloca");
18410 EHInfo->EHGuardFrameIndex = FINode->getIndex();
18412 // Return the chain operand without making any DAG nodes.
18416 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget &Subtarget,
18417 SelectionDAG &DAG) {
18418 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
18420 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
18422 if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
18423 return MarkEHRegistrationNode(Op, DAG);
18424 if (IntNo == llvm::Intrinsic::x86_seh_ehguard)
18425 return MarkEHGuard(Op, DAG);
18426 if (IntNo == llvm::Intrinsic::x86_flags_read_u32 ||
18427 IntNo == llvm::Intrinsic::x86_flags_read_u64 ||
18428 IntNo == llvm::Intrinsic::x86_flags_write_u32 ||
18429 IntNo == llvm::Intrinsic::x86_flags_write_u64) {
18430 // We need a frame pointer because this will get lowered to a PUSH/POP
18432 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
18433 MFI->setHasCopyImplyingStackAdjustment(true);
18434 // Don't do anything here, we will expand these intrinsics out later
18435 // during ExpandISelPseudos in EmitInstrWithCustomInserter.
18442 switch(IntrData->Type) {
18443 default: llvm_unreachable("Unknown Intrinsic Type");
18446 // Emit the node with the right value type.
18447 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
18448 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
18450 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
18451 // Otherwise return the value from Rand, which is always 0, casted to i32.
18452 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
18453 DAG.getConstant(1, dl, Op->getValueType(1)),
18454 DAG.getConstant(X86::COND_B, dl, MVT::i32),
18455 SDValue(Result.getNode(), 1) };
18456 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
18457 DAG.getVTList(Op->getValueType(1), MVT::Glue),
18460 // Return { result, isValid, chain }.
18461 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
18462 SDValue(Result.getNode(), 2));
18465 //gather(v1, mask, index, base, scale);
18466 SDValue Chain = Op.getOperand(0);
18467 SDValue Src = Op.getOperand(2);
18468 SDValue Base = Op.getOperand(3);
18469 SDValue Index = Op.getOperand(4);
18470 SDValue Mask = Op.getOperand(5);
18471 SDValue Scale = Op.getOperand(6);
18472 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
18476 //scatter(base, mask, index, v1, scale);
18477 SDValue Chain = Op.getOperand(0);
18478 SDValue Base = Op.getOperand(2);
18479 SDValue Mask = Op.getOperand(3);
18480 SDValue Index = Op.getOperand(4);
18481 SDValue Src = Op.getOperand(5);
18482 SDValue Scale = Op.getOperand(6);
18483 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
18484 Scale, Chain, Subtarget);
18487 SDValue Hint = Op.getOperand(6);
18488 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
18489 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
18490 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
18491 SDValue Chain = Op.getOperand(0);
18492 SDValue Mask = Op.getOperand(2);
18493 SDValue Index = Op.getOperand(3);
18494 SDValue Base = Op.getOperand(4);
18495 SDValue Scale = Op.getOperand(5);
18496 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain,
18499 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
18501 SmallVector<SDValue, 2> Results;
18502 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
18504 return DAG.getMergeValues(Results, dl);
18506 // Read Performance Monitoring Counters.
18508 SmallVector<SDValue, 2> Results;
18509 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
18510 return DAG.getMergeValues(Results, dl);
18512 // XTEST intrinsics.
18514 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
18515 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
18516 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18517 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
18519 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
18520 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
18521 Ret, SDValue(InTrans.getNode(), 1));
18525 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
18526 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
18527 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
18528 DAG.getConstant(-1, dl, MVT::i8));
18529 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
18530 Op.getOperand(4), GenCF.getValue(1));
18531 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
18532 Op.getOperand(5), MachinePointerInfo());
18533 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18534 DAG.getConstant(X86::COND_B, dl, MVT::i8),
18536 SDValue Results[] = { SetCC, Store };
18537 return DAG.getMergeValues(Results, dl);
18539 case COMPRESS_TO_MEM: {
18540 SDValue Mask = Op.getOperand(4);
18541 SDValue DataToCompress = Op.getOperand(3);
18542 SDValue Addr = Op.getOperand(2);
18543 SDValue Chain = Op.getOperand(0);
18544 MVT VT = DataToCompress.getSimpleValueType();
18546 MemIntrinsicSDNode *MemIntr = dyn_cast<MemIntrinsicSDNode>(Op);
18547 assert(MemIntr && "Expected MemIntrinsicSDNode!");
18549 if (isAllOnesConstant(Mask)) // return just a store
18550 return DAG.getStore(Chain, dl, DataToCompress, Addr,
18551 MemIntr->getMemOperand());
18553 SDValue Compressed =
18554 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
18555 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
18556 return DAG.getStore(Chain, dl, Compressed, Addr,
18557 MemIntr->getMemOperand());
18559 case TRUNCATE_TO_MEM_VI8:
18560 case TRUNCATE_TO_MEM_VI16:
18561 case TRUNCATE_TO_MEM_VI32: {
18562 SDValue Mask = Op.getOperand(4);
18563 SDValue DataToTruncate = Op.getOperand(3);
18564 SDValue Addr = Op.getOperand(2);
18565 SDValue Chain = Op.getOperand(0);
18567 MemIntrinsicSDNode *MemIntr = dyn_cast<MemIntrinsicSDNode>(Op);
18568 assert(MemIntr && "Expected MemIntrinsicSDNode!");
18570 EVT VT = MemIntr->getMemoryVT();
18572 if (isAllOnesConstant(Mask)) // return just a truncate store
18573 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr, VT,
18574 MemIntr->getMemOperand());
18576 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
18577 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
18579 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr, VMask, VT,
18580 MemIntr->getMemOperand(), true);
18582 case EXPAND_FROM_MEM: {
18583 SDValue Mask = Op.getOperand(4);
18584 SDValue PassThru = Op.getOperand(3);
18585 SDValue Addr = Op.getOperand(2);
18586 SDValue Chain = Op.getOperand(0);
18587 MVT VT = Op.getSimpleValueType();
18589 MemIntrinsicSDNode *MemIntr = dyn_cast<MemIntrinsicSDNode>(Op);
18590 assert(MemIntr && "Expected MemIntrinsicSDNode!");
18592 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr,
18593 MemIntr->getMemOperand());
18595 if (isAllOnesConstant(Mask)) // return just a load
18596 return DataToExpand;
18598 SDValue Results[] = {
18599 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
18600 Mask, PassThru, Subtarget, DAG), Chain};
18601 return DAG.getMergeValues(Results, dl);
18606 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
18607 SelectionDAG &DAG) const {
18608 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
18609 MFI->setReturnAddressIsTaken(true);
18611 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
18614 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18616 EVT PtrVT = getPointerTy(DAG.getDataLayout());
18619 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
18620 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
18621 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
18622 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
18623 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
18624 MachinePointerInfo());
18627 // Just load the return address.
18628 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
18629 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
18630 MachinePointerInfo());
18633 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
18634 MachineFunction &MF = DAG.getMachineFunction();
18635 MachineFrameInfo *MFI = MF.getFrameInfo();
18636 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
18637 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
18638 EVT VT = Op.getValueType();
18640 MFI->setFrameAddressIsTaken(true);
18642 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
18643 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
18644 // is not possible to crawl up the stack without looking at the unwind codes
18646 int FrameAddrIndex = FuncInfo->getFAIndex();
18647 if (!FrameAddrIndex) {
18648 // Set up a frame object for the return address.
18649 unsigned SlotSize = RegInfo->getSlotSize();
18650 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
18651 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
18652 FuncInfo->setFAIndex(FrameAddrIndex);
18654 return DAG.getFrameIndex(FrameAddrIndex, VT);
18657 unsigned FrameReg =
18658 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
18659 SDLoc dl(Op); // FIXME probably not meaningful
18660 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18661 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
18662 (FrameReg == X86::EBP && VT == MVT::i32)) &&
18663 "Invalid Frame Register!");
18664 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
18666 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
18667 MachinePointerInfo());
18671 // FIXME? Maybe this could be a TableGen attribute on some registers and
18672 // this table could be generated automatically from RegInfo.
18673 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
18674 SelectionDAG &DAG) const {
18675 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
18676 const MachineFunction &MF = DAG.getMachineFunction();
18678 unsigned Reg = StringSwitch<unsigned>(RegName)
18679 .Case("esp", X86::ESP)
18680 .Case("rsp", X86::RSP)
18681 .Case("ebp", X86::EBP)
18682 .Case("rbp", X86::RBP)
18685 if (Reg == X86::EBP || Reg == X86::RBP) {
18686 if (!TFI.hasFP(MF))
18687 report_fatal_error("register " + StringRef(RegName) +
18688 " is allocatable: function has no frame pointer");
18691 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
18692 unsigned FrameReg =
18693 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
18694 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
18695 "Invalid Frame Register!");
18703 report_fatal_error("Invalid register name global variable");
18706 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
18707 SelectionDAG &DAG) const {
18708 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
18709 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
18712 unsigned X86TargetLowering::getExceptionPointerRegister(
18713 const Constant *PersonalityFn) const {
18714 if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
18715 return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
18717 return Subtarget.isTarget64BitLP64() ? X86::RAX : X86::EAX;
18720 unsigned X86TargetLowering::getExceptionSelectorRegister(
18721 const Constant *PersonalityFn) const {
18722 // Funclet personalities don't use selectors (the runtime does the selection).
18723 assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
18724 return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
18727 bool X86TargetLowering::needsFixedCatchObjects() const {
18728 return Subtarget.isTargetWin64();
18731 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
18732 SDValue Chain = Op.getOperand(0);
18733 SDValue Offset = Op.getOperand(1);
18734 SDValue Handler = Op.getOperand(2);
18737 EVT PtrVT = getPointerTy(DAG.getDataLayout());
18738 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
18739 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
18740 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
18741 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
18742 "Invalid Frame Register!");
18743 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
18744 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
18746 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
18747 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
18749 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
18750 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo());
18751 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
18753 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
18754 DAG.getRegister(StoreAddrReg, PtrVT));
18757 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
18758 SelectionDAG &DAG) const {
18760 // If the subtarget is not 64bit, we may need the global base reg
18761 // after isel expand pseudo, i.e., after CGBR pass ran.
18762 // Therefore, ask for the GlobalBaseReg now, so that the pass
18763 // inserts the code for us in case we need it.
18764 // Otherwise, we will end up in a situation where we will
18765 // reference a virtual register that is not defined!
18766 if (!Subtarget.is64Bit()) {
18767 const X86InstrInfo *TII = Subtarget.getInstrInfo();
18768 (void)TII->getGlobalBaseReg(&DAG.getMachineFunction());
18770 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
18771 DAG.getVTList(MVT::i32, MVT::Other),
18772 Op.getOperand(0), Op.getOperand(1));
18775 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
18776 SelectionDAG &DAG) const {
18778 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
18779 Op.getOperand(0), Op.getOperand(1));
18782 SDValue X86TargetLowering::lowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
18783 SelectionDAG &DAG) const {
18785 return DAG.getNode(X86ISD::EH_SJLJ_SETUP_DISPATCH, DL, MVT::Other,
18789 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
18790 return Op.getOperand(0);
18793 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
18794 SelectionDAG &DAG) const {
18795 SDValue Root = Op.getOperand(0);
18796 SDValue Trmp = Op.getOperand(1); // trampoline
18797 SDValue FPtr = Op.getOperand(2); // nested function
18798 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
18801 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
18802 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
18804 if (Subtarget.is64Bit()) {
18805 SDValue OutChains[6];
18807 // Large code-model.
18808 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
18809 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
18811 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
18812 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
18814 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
18816 // Load the pointer to the nested function into R11.
18817 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
18818 SDValue Addr = Trmp;
18819 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
18820 Addr, MachinePointerInfo(TrmpAddr));
18822 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
18823 DAG.getConstant(2, dl, MVT::i64));
18825 DAG.getStore(Root, dl, FPtr, Addr, MachinePointerInfo(TrmpAddr, 2),
18826 /* Alignment = */ 2);
18828 // Load the 'nest' parameter value into R10.
18829 // R10 is specified in X86CallingConv.td
18830 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
18831 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
18832 DAG.getConstant(10, dl, MVT::i64));
18833 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
18834 Addr, MachinePointerInfo(TrmpAddr, 10));
18836 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
18837 DAG.getConstant(12, dl, MVT::i64));
18839 DAG.getStore(Root, dl, Nest, Addr, MachinePointerInfo(TrmpAddr, 12),
18840 /* Alignment = */ 2);
18842 // Jump to the nested function.
18843 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
18844 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
18845 DAG.getConstant(20, dl, MVT::i64));
18846 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
18847 Addr, MachinePointerInfo(TrmpAddr, 20));
18849 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
18850 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
18851 DAG.getConstant(22, dl, MVT::i64));
18852 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
18853 Addr, MachinePointerInfo(TrmpAddr, 22));
18855 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
18857 const Function *Func =
18858 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
18859 CallingConv::ID CC = Func->getCallingConv();
18864 llvm_unreachable("Unsupported calling convention");
18865 case CallingConv::C:
18866 case CallingConv::X86_StdCall: {
18867 // Pass 'nest' parameter in ECX.
18868 // Must be kept in sync with X86CallingConv.td
18869 NestReg = X86::ECX;
18871 // Check that ECX wasn't needed by an 'inreg' parameter.
18872 FunctionType *FTy = Func->getFunctionType();
18873 const AttributeSet &Attrs = Func->getAttributes();
18875 if (!Attrs.isEmpty() && !Func->isVarArg()) {
18876 unsigned InRegCount = 0;
18879 for (FunctionType::param_iterator I = FTy->param_begin(),
18880 E = FTy->param_end(); I != E; ++I, ++Idx)
18881 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
18882 auto &DL = DAG.getDataLayout();
18883 // FIXME: should only count parameters that are lowered to integers.
18884 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
18887 if (InRegCount > 2) {
18888 report_fatal_error("Nest register in use - reduce number of inreg"
18894 case CallingConv::X86_FastCall:
18895 case CallingConv::X86_ThisCall:
18896 case CallingConv::Fast:
18897 // Pass 'nest' parameter in EAX.
18898 // Must be kept in sync with X86CallingConv.td
18899 NestReg = X86::EAX;
18903 SDValue OutChains[4];
18904 SDValue Addr, Disp;
18906 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
18907 DAG.getConstant(10, dl, MVT::i32));
18908 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
18910 // This is storing the opcode for MOV32ri.
18911 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
18912 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
18914 DAG.getStore(Root, dl, DAG.getConstant(MOV32ri | N86Reg, dl, MVT::i8),
18915 Trmp, MachinePointerInfo(TrmpAddr));
18917 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
18918 DAG.getConstant(1, dl, MVT::i32));
18920 DAG.getStore(Root, dl, Nest, Addr, MachinePointerInfo(TrmpAddr, 1),
18921 /* Alignment = */ 1);
18923 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
18924 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
18925 DAG.getConstant(5, dl, MVT::i32));
18926 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
18927 Addr, MachinePointerInfo(TrmpAddr, 5),
18928 /* Alignment = */ 1);
18930 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
18931 DAG.getConstant(6, dl, MVT::i32));
18933 DAG.getStore(Root, dl, Disp, Addr, MachinePointerInfo(TrmpAddr, 6),
18934 /* Alignment = */ 1);
18936 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
18940 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
18941 SelectionDAG &DAG) const {
18943 The rounding mode is in bits 11:10 of FPSR, and has the following
18945 00 Round to nearest
18950 FLT_ROUNDS, on the other hand, expects the following:
18957 To perform the conversion, we do:
18958 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
18961 MachineFunction &MF = DAG.getMachineFunction();
18962 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
18963 unsigned StackAlignment = TFI.getStackAlignment();
18964 MVT VT = Op.getSimpleValueType();
18967 // Save FP Control Word to stack slot
18968 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
18969 SDValue StackSlot =
18970 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
18972 MachineMemOperand *MMO =
18973 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
18974 MachineMemOperand::MOStore, 2, 2);
18976 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
18977 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
18978 DAG.getVTList(MVT::Other),
18979 Ops, MVT::i16, MMO);
18981 // Load FP Control Word from stack slot
18983 DAG.getLoad(MVT::i16, DL, Chain, StackSlot, MachinePointerInfo());
18985 // Transform as necessary
18987 DAG.getNode(ISD::SRL, DL, MVT::i16,
18988 DAG.getNode(ISD::AND, DL, MVT::i16,
18989 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
18990 DAG.getConstant(11, DL, MVT::i8));
18992 DAG.getNode(ISD::SRL, DL, MVT::i16,
18993 DAG.getNode(ISD::AND, DL, MVT::i16,
18994 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
18995 DAG.getConstant(9, DL, MVT::i8));
18998 DAG.getNode(ISD::AND, DL, MVT::i16,
18999 DAG.getNode(ISD::ADD, DL, MVT::i16,
19000 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
19001 DAG.getConstant(1, DL, MVT::i16)),
19002 DAG.getConstant(3, DL, MVT::i16));
19004 return DAG.getNode((VT.getSizeInBits() < 16 ?
19005 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
19008 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
19010 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
19011 // to 512-bit vector.
19012 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
19013 // ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
19014 // split the vector, perform operation on it's Lo a Hi part and
19015 // concatenate the results.
19016 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
19017 assert(Op.getOpcode() == ISD::CTLZ);
19019 MVT VT = Op.getSimpleValueType();
19020 MVT EltVT = VT.getVectorElementType();
19021 unsigned NumElems = VT.getVectorNumElements();
19023 if (EltVT == MVT::i64 || EltVT == MVT::i32) {
19024 // Extend to 512 bit vector.
19025 assert((VT.is256BitVector() || VT.is128BitVector()) &&
19026 "Unsupported value type for operation");
19028 MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
19029 SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
19030 DAG.getUNDEF(NewVT),
19032 DAG.getIntPtrConstant(0, dl));
19033 SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
19035 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
19036 DAG.getIntPtrConstant(0, dl));
19039 assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
19040 "Unsupported element type");
19042 if (16 < NumElems) {
19043 // Split vector, it's Lo and Hi parts will be handled in next iteration.
19045 std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
19046 MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
19048 Lo = DAG.getNode(ISD::CTLZ, dl, OutVT, Lo);
19049 Hi = DAG.getNode(ISD::CTLZ, dl, OutVT, Hi);
19051 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
19054 MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
19056 assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
19057 "Unsupported value type for operation");
19059 // Use native supported vector instruction vplzcntd.
19060 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
19061 SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
19062 SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
19063 SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
19065 return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
19068 // Lower CTLZ using a PSHUFB lookup table implementation.
19069 static SDValue LowerVectorCTLZInRegLUT(SDValue Op, const SDLoc &DL,
19070 const X86Subtarget &Subtarget,
19071 SelectionDAG &DAG) {
19072 MVT VT = Op.getSimpleValueType();
19073 int NumElts = VT.getVectorNumElements();
19074 int NumBytes = NumElts * (VT.getScalarSizeInBits() / 8);
19075 MVT CurrVT = MVT::getVectorVT(MVT::i8, NumBytes);
19077 // Per-nibble leading zero PSHUFB lookup table.
19078 const int LUT[16] = {/* 0 */ 4, /* 1 */ 3, /* 2 */ 2, /* 3 */ 2,
19079 /* 4 */ 1, /* 5 */ 1, /* 6 */ 1, /* 7 */ 1,
19080 /* 8 */ 0, /* 9 */ 0, /* a */ 0, /* b */ 0,
19081 /* c */ 0, /* d */ 0, /* e */ 0, /* f */ 0};
19083 SmallVector<SDValue, 64> LUTVec;
19084 for (int i = 0; i < NumBytes; ++i)
19085 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19086 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, CurrVT, LUTVec);
19088 // Begin by bitcasting the input to byte vector, then split those bytes
19089 // into lo/hi nibbles and use the PSHUFB LUT to perform CLTZ on each of them.
19090 // If the hi input nibble is zero then we add both results together, otherwise
19091 // we just take the hi result (by masking the lo result to zero before the
19093 SDValue Op0 = DAG.getBitcast(CurrVT, Op.getOperand(0));
19094 SDValue Zero = getZeroVector(CurrVT, Subtarget, DAG, DL);
19096 SDValue NibbleMask = DAG.getConstant(0xF, DL, CurrVT);
19097 SDValue NibbleShift = DAG.getConstant(0x4, DL, CurrVT);
19098 SDValue Lo = DAG.getNode(ISD::AND, DL, CurrVT, Op0, NibbleMask);
19099 SDValue Hi = DAG.getNode(ISD::SRL, DL, CurrVT, Op0, NibbleShift);
19100 SDValue HiZ = DAG.getSetCC(DL, CurrVT, Hi, Zero, ISD::SETEQ);
19102 Lo = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Lo);
19103 Hi = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Hi);
19104 Lo = DAG.getNode(ISD::AND, DL, CurrVT, Lo, HiZ);
19105 SDValue Res = DAG.getNode(ISD::ADD, DL, CurrVT, Lo, Hi);
19107 // Merge result back from vXi8 back to VT, working on the lo/hi halves
19108 // of the current vector width in the same way we did for the nibbles.
19109 // If the upper half of the input element is zero then add the halves'
19110 // leading zero counts together, otherwise just use the upper half's.
19111 // Double the width of the result until we are at target width.
19112 while (CurrVT != VT) {
19113 int CurrScalarSizeInBits = CurrVT.getScalarSizeInBits();
19114 int CurrNumElts = CurrVT.getVectorNumElements();
19115 MVT NextSVT = MVT::getIntegerVT(CurrScalarSizeInBits * 2);
19116 MVT NextVT = MVT::getVectorVT(NextSVT, CurrNumElts / 2);
19117 SDValue Shift = DAG.getConstant(CurrScalarSizeInBits, DL, NextVT);
19119 // Check if the upper half of the input element is zero.
19120 SDValue HiZ = DAG.getSetCC(DL, CurrVT, DAG.getBitcast(CurrVT, Op0),
19121 DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
19122 HiZ = DAG.getBitcast(NextVT, HiZ);
19124 // Move the upper/lower halves to the lower bits as we'll be extending to
19125 // NextVT. Mask the lower result to zero if HiZ is true and add the results
19127 SDValue ResNext = Res = DAG.getBitcast(NextVT, Res);
19128 SDValue R0 = DAG.getNode(ISD::SRL, DL, NextVT, ResNext, Shift);
19129 SDValue R1 = DAG.getNode(ISD::SRL, DL, NextVT, HiZ, Shift);
19130 R1 = DAG.getNode(ISD::AND, DL, NextVT, ResNext, R1);
19131 Res = DAG.getNode(ISD::ADD, DL, NextVT, R0, R1);
19138 static SDValue LowerVectorCTLZ(SDValue Op, const SDLoc &DL,
19139 const X86Subtarget &Subtarget,
19140 SelectionDAG &DAG) {
19141 MVT VT = Op.getSimpleValueType();
19142 SDValue Op0 = Op.getOperand(0);
19144 if (Subtarget.hasAVX512())
19145 return LowerVectorCTLZ_AVX512(Op, DAG);
19147 // Decompose 256-bit ops into smaller 128-bit ops.
19148 if (VT.is256BitVector() && !Subtarget.hasInt256()) {
19149 unsigned NumElems = VT.getVectorNumElements();
19151 // Extract each 128-bit vector, perform ctlz and concat the result.
19152 SDValue LHS = extract128BitVector(Op0, 0, DAG, DL);
19153 SDValue RHS = extract128BitVector(Op0, NumElems / 2, DAG, DL);
19155 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19156 DAG.getNode(ISD::CTLZ, DL, LHS.getValueType(), LHS),
19157 DAG.getNode(ISD::CTLZ, DL, RHS.getValueType(), RHS));
19160 assert(Subtarget.hasSSSE3() && "Expected SSSE3 support for PSHUFB");
19161 return LowerVectorCTLZInRegLUT(Op, DL, Subtarget, DAG);
19164 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget &Subtarget,
19165 SelectionDAG &DAG) {
19166 MVT VT = Op.getSimpleValueType();
19168 unsigned NumBits = VT.getSizeInBits();
19170 unsigned Opc = Op.getOpcode();
19173 return LowerVectorCTLZ(Op, dl, Subtarget, DAG);
19175 Op = Op.getOperand(0);
19176 if (VT == MVT::i8) {
19177 // Zero extend to i32 since there is not an i8 bsr.
19179 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
19182 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
19183 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
19184 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
19186 if (Opc == ISD::CTLZ) {
19187 // If src is zero (i.e. bsr sets ZF), returns NumBits.
19190 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
19191 DAG.getConstant(X86::COND_E, dl, MVT::i8),
19194 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
19197 // Finally xor with NumBits-1.
19198 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
19199 DAG.getConstant(NumBits - 1, dl, OpVT));
19202 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
19206 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
19207 MVT VT = Op.getSimpleValueType();
19208 unsigned NumBits = VT.getScalarSizeInBits();
19211 if (VT.isVector()) {
19212 SDValue N0 = Op.getOperand(0);
19213 SDValue Zero = DAG.getConstant(0, dl, VT);
19215 // lsb(x) = (x & -x)
19216 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
19217 DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
19219 // cttz_undef(x) = (width - 1) - ctlz(lsb)
19220 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
19221 SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
19222 return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
19223 DAG.getNode(ISD::CTLZ, dl, VT, LSB));
19226 // cttz(x) = ctpop(lsb - 1)
19227 SDValue One = DAG.getConstant(1, dl, VT);
19228 return DAG.getNode(ISD::CTPOP, dl, VT,
19229 DAG.getNode(ISD::SUB, dl, VT, LSB, One));
19232 assert(Op.getOpcode() == ISD::CTTZ &&
19233 "Only scalar CTTZ requires custom lowering");
19235 // Issue a bsf (scan bits forward) which also sets EFLAGS.
19236 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19237 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
19239 // If src is zero (i.e. bsf sets ZF), returns NumBits.
19242 DAG.getConstant(NumBits, dl, VT),
19243 DAG.getConstant(X86::COND_E, dl, MVT::i8),
19246 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
19249 /// Break a 256-bit integer operation into two new 128-bit ones and then
19250 /// concatenate the result back.
19251 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
19252 MVT VT = Op.getSimpleValueType();
19254 assert(VT.is256BitVector() && VT.isInteger() &&
19255 "Unsupported value type for operation");
19257 unsigned NumElems = VT.getVectorNumElements();
19260 // Extract the LHS vectors
19261 SDValue LHS = Op.getOperand(0);
19262 SDValue LHS1 = extract128BitVector(LHS, 0, DAG, dl);
19263 SDValue LHS2 = extract128BitVector(LHS, NumElems / 2, DAG, dl);
19265 // Extract the RHS vectors
19266 SDValue RHS = Op.getOperand(1);
19267 SDValue RHS1 = extract128BitVector(RHS, 0, DAG, dl);
19268 SDValue RHS2 = extract128BitVector(RHS, NumElems / 2, DAG, dl);
19270 MVT EltVT = VT.getVectorElementType();
19271 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
19273 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
19274 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
19275 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
19278 /// Break a 512-bit integer operation into two new 256-bit ones and then
19279 /// concatenate the result back.
19280 static SDValue Lower512IntArith(SDValue Op, SelectionDAG &DAG) {
19281 MVT VT = Op.getSimpleValueType();
19283 assert(VT.is512BitVector() && VT.isInteger() &&
19284 "Unsupported value type for operation");
19286 unsigned NumElems = VT.getVectorNumElements();
19289 // Extract the LHS vectors
19290 SDValue LHS = Op.getOperand(0);
19291 SDValue LHS1 = extract256BitVector(LHS, 0, DAG, dl);
19292 SDValue LHS2 = extract256BitVector(LHS, NumElems / 2, DAG, dl);
19294 // Extract the RHS vectors
19295 SDValue RHS = Op.getOperand(1);
19296 SDValue RHS1 = extract256BitVector(RHS, 0, DAG, dl);
19297 SDValue RHS2 = extract256BitVector(RHS, NumElems / 2, DAG, dl);
19299 MVT EltVT = VT.getVectorElementType();
19300 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
19302 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
19303 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
19304 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
19307 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
19308 if (Op.getValueType() == MVT::i1)
19309 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
19310 Op.getOperand(0), Op.getOperand(1));
19311 assert(Op.getSimpleValueType().is256BitVector() &&
19312 Op.getSimpleValueType().isInteger() &&
19313 "Only handle AVX 256-bit vector integer operation");
19314 return Lower256IntArith(Op, DAG);
19317 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
19318 if (Op.getValueType() == MVT::i1)
19319 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
19320 Op.getOperand(0), Op.getOperand(1));
19321 assert(Op.getSimpleValueType().is256BitVector() &&
19322 Op.getSimpleValueType().isInteger() &&
19323 "Only handle AVX 256-bit vector integer operation");
19324 return Lower256IntArith(Op, DAG);
19327 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
19328 assert(Op.getSimpleValueType().is256BitVector() &&
19329 Op.getSimpleValueType().isInteger() &&
19330 "Only handle AVX 256-bit vector integer operation");
19331 return Lower256IntArith(Op, DAG);
19334 static SDValue LowerMUL(SDValue Op, const X86Subtarget &Subtarget,
19335 SelectionDAG &DAG) {
19337 MVT VT = Op.getSimpleValueType();
19340 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
19342 // Decompose 256-bit ops into smaller 128-bit ops.
19343 if (VT.is256BitVector() && !Subtarget.hasInt256())
19344 return Lower256IntArith(Op, DAG);
19346 SDValue A = Op.getOperand(0);
19347 SDValue B = Op.getOperand(1);
19349 // Lower v16i8/v32i8/v64i8 mul as sign-extension to v8i16/v16i16/v32i16
19350 // vector pairs, multiply and truncate.
19351 if (VT == MVT::v16i8 || VT == MVT::v32i8 || VT == MVT::v64i8) {
19352 if (Subtarget.hasInt256()) {
19353 // For 512-bit vectors, split into 256-bit vectors to allow the
19354 // sign-extension to occur.
19355 if (VT == MVT::v64i8)
19356 return Lower512IntArith(Op, DAG);
19358 // For 256-bit vectors, split into 128-bit vectors to allow the
19359 // sign-extension to occur. We don't need this on AVX512BW as we can
19360 // safely sign-extend to v32i16.
19361 if (VT == MVT::v32i8 && !Subtarget.hasBWI())
19362 return Lower256IntArith(Op, DAG);
19364 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
19365 return DAG.getNode(
19366 ISD::TRUNCATE, dl, VT,
19367 DAG.getNode(ISD::MUL, dl, ExVT,
19368 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
19369 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
19372 assert(VT == MVT::v16i8 &&
19373 "Pre-AVX2 support only supports v16i8 multiplication");
19374 MVT ExVT = MVT::v8i16;
19376 // Extract the lo parts and sign extend to i16
19378 if (Subtarget.hasSSE41()) {
19379 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
19380 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
19382 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
19383 -1, 4, -1, 5, -1, 6, -1, 7};
19384 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
19385 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
19386 ALo = DAG.getBitcast(ExVT, ALo);
19387 BLo = DAG.getBitcast(ExVT, BLo);
19388 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
19389 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
19392 // Extract the hi parts and sign extend to i16
19394 if (Subtarget.hasSSE41()) {
19395 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
19396 -1, -1, -1, -1, -1, -1, -1, -1};
19397 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
19398 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
19399 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
19400 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
19402 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
19403 -1, 12, -1, 13, -1, 14, -1, 15};
19404 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
19405 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
19406 AHi = DAG.getBitcast(ExVT, AHi);
19407 BHi = DAG.getBitcast(ExVT, BHi);
19408 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
19409 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
19412 // Multiply, mask the lower 8bits of the lo/hi results and pack
19413 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
19414 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
19415 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
19416 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
19417 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
19420 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
19421 if (VT == MVT::v4i32) {
19422 assert(Subtarget.hasSSE2() && !Subtarget.hasSSE41() &&
19423 "Should not custom lower when pmuldq is available!");
19425 // Extract the odd parts.
19426 static const int UnpackMask[] = { 1, -1, 3, -1 };
19427 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
19428 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
19430 // Multiply the even parts.
19431 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
19432 // Now multiply odd parts.
19433 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
19435 Evens = DAG.getBitcast(VT, Evens);
19436 Odds = DAG.getBitcast(VT, Odds);
19438 // Merge the two vectors back together with a shuffle. This expands into 2
19440 static const int ShufMask[] = { 0, 4, 2, 6 };
19441 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
19444 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
19445 "Only know how to lower V2I64/V4I64/V8I64 multiply");
19447 // Ahi = psrlqi(a, 32);
19448 // Bhi = psrlqi(b, 32);
19450 // AloBlo = pmuludq(a, b);
19451 // AloBhi = pmuludq(a, Bhi);
19452 // AhiBlo = pmuludq(Ahi, b);
19454 // AloBhi = psllqi(AloBhi, 32);
19455 // AhiBlo = psllqi(AhiBlo, 32);
19456 // return AloBlo + AloBhi + AhiBlo;
19458 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
19459 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
19461 SDValue AhiBlo = Ahi;
19462 SDValue AloBhi = Bhi;
19463 // Bit cast to 32-bit vectors for MULUDQ
19464 MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
19465 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
19466 A = DAG.getBitcast(MulVT, A);
19467 B = DAG.getBitcast(MulVT, B);
19468 Ahi = DAG.getBitcast(MulVT, Ahi);
19469 Bhi = DAG.getBitcast(MulVT, Bhi);
19471 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
19472 // After shifting right const values the result may be all-zero.
19473 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
19474 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
19475 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
19477 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
19478 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
19479 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
19482 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
19483 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
19486 static SDValue LowerMULH(SDValue Op, const X86Subtarget &Subtarget,
19487 SelectionDAG &DAG) {
19489 MVT VT = Op.getSimpleValueType();
19491 // Decompose 256-bit ops into smaller 128-bit ops.
19492 if (VT.is256BitVector() && !Subtarget.hasInt256())
19493 return Lower256IntArith(Op, DAG);
19495 // Only i8 vectors should need custom lowering after this.
19496 assert((VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256())) &&
19497 "Unsupported vector type");
19499 // Lower v16i8/v32i8 as extension to v8i16/v16i16 vector pairs, multiply,
19500 // logical shift down the upper half and pack back to i8.
19501 SDValue A = Op.getOperand(0);
19502 SDValue B = Op.getOperand(1);
19504 // With SSE41 we can use sign/zero extend, but for pre-SSE41 we unpack
19505 // and then ashr/lshr the upper bits down to the lower bits before multiply.
19506 unsigned Opcode = Op.getOpcode();
19507 unsigned ExShift = (ISD::MULHU == Opcode ? ISD::SRL : ISD::SRA);
19508 unsigned ExSSE41 = (ISD::MULHU == Opcode ? X86ISD::VZEXT : X86ISD::VSEXT);
19510 // AVX2 implementations - extend xmm subvectors to ymm.
19511 if (Subtarget.hasInt256()) {
19512 SDValue Lo = DAG.getIntPtrConstant(0, dl);
19513 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
19515 if (VT == MVT::v32i8) {
19516 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v16i8, A, Lo);
19517 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v16i8, B, Lo);
19518 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v16i8, A, Hi);
19519 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v16i8, B, Hi);
19520 ALo = DAG.getNode(ExSSE41, dl, MVT::v16i16, ALo);
19521 BLo = DAG.getNode(ExSSE41, dl, MVT::v16i16, BLo);
19522 AHi = DAG.getNode(ExSSE41, dl, MVT::v16i16, AHi);
19523 BHi = DAG.getNode(ExSSE41, dl, MVT::v16i16, BHi);
19524 Lo = DAG.getNode(ISD::SRL, dl, MVT::v16i16,
19525 DAG.getNode(ISD::MUL, dl, MVT::v16i16, ALo, BLo),
19526 DAG.getConstant(8, dl, MVT::v16i16));
19527 Hi = DAG.getNode(ISD::SRL, dl, MVT::v16i16,
19528 DAG.getNode(ISD::MUL, dl, MVT::v16i16, AHi, BHi),
19529 DAG.getConstant(8, dl, MVT::v16i16));
19530 // The ymm variant of PACKUS treats the 128-bit lanes separately, so before
19531 // using PACKUS we need to permute the inputs to the correct lo/hi xmm lane.
19532 const int LoMask[] = {0, 1, 2, 3, 4, 5, 6, 7,
19533 16, 17, 18, 19, 20, 21, 22, 23};
19534 const int HiMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
19535 24, 25, 26, 27, 28, 29, 30, 31};
19536 return DAG.getNode(X86ISD::PACKUS, dl, VT,
19537 DAG.getVectorShuffle(MVT::v16i16, dl, Lo, Hi, LoMask),
19538 DAG.getVectorShuffle(MVT::v16i16, dl, Lo, Hi, HiMask));
19541 SDValue ExA = DAG.getNode(ExSSE41, dl, MVT::v16i16, A);
19542 SDValue ExB = DAG.getNode(ExSSE41, dl, MVT::v16i16, B);
19543 SDValue Mul = DAG.getNode(ISD::MUL, dl, MVT::v16i16, ExA, ExB);
19544 SDValue MulH = DAG.getNode(ISD::SRL, dl, MVT::v16i16, Mul,
19545 DAG.getConstant(8, dl, MVT::v16i16));
19546 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i16, MulH, Lo);
19547 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i16, MulH, Hi);
19548 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
19551 assert(VT == MVT::v16i8 &&
19552 "Pre-AVX2 support only supports v16i8 multiplication");
19553 MVT ExVT = MVT::v8i16;
19555 // Extract the lo parts and zero/sign extend to i16.
19557 if (Subtarget.hasSSE41()) {
19558 ALo = DAG.getNode(ExSSE41, dl, ExVT, A);
19559 BLo = DAG.getNode(ExSSE41, dl, ExVT, B);
19561 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
19562 -1, 4, -1, 5, -1, 6, -1, 7};
19563 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
19564 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
19565 ALo = DAG.getBitcast(ExVT, ALo);
19566 BLo = DAG.getBitcast(ExVT, BLo);
19567 ALo = DAG.getNode(ExShift, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
19568 BLo = DAG.getNode(ExShift, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
19571 // Extract the hi parts and zero/sign extend to i16.
19573 if (Subtarget.hasSSE41()) {
19574 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
19575 -1, -1, -1, -1, -1, -1, -1, -1};
19576 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
19577 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
19578 AHi = DAG.getNode(ExSSE41, dl, ExVT, AHi);
19579 BHi = DAG.getNode(ExSSE41, dl, ExVT, BHi);
19581 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
19582 -1, 12, -1, 13, -1, 14, -1, 15};
19583 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
19584 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
19585 AHi = DAG.getBitcast(ExVT, AHi);
19586 BHi = DAG.getBitcast(ExVT, BHi);
19587 AHi = DAG.getNode(ExShift, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
19588 BHi = DAG.getNode(ExShift, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
19591 // Multiply, lshr the upper 8bits to the lower 8bits of the lo/hi results and
19592 // pack back to v16i8.
19593 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
19594 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
19595 RLo = DAG.getNode(ISD::SRL, dl, ExVT, RLo, DAG.getConstant(8, dl, ExVT));
19596 RHi = DAG.getNode(ISD::SRL, dl, ExVT, RHi, DAG.getConstant(8, dl, ExVT));
19597 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
19600 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
19601 assert(Subtarget.isTargetWin64() && "Unexpected target");
19602 EVT VT = Op.getValueType();
19603 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
19604 "Unexpected return type for lowering");
19608 switch (Op->getOpcode()) {
19609 default: llvm_unreachable("Unexpected request for libcall!");
19610 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
19611 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
19612 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
19613 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
19614 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
19615 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
19619 SDValue InChain = DAG.getEntryNode();
19621 TargetLowering::ArgListTy Args;
19622 TargetLowering::ArgListEntry Entry;
19623 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
19624 EVT ArgVT = Op->getOperand(i).getValueType();
19625 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
19626 "Unexpected argument type for lowering");
19627 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
19628 Entry.Node = StackPtr;
19629 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr,
19630 MachinePointerInfo(), /* Alignment = */ 16);
19631 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19632 Entry.Ty = PointerType::get(ArgTy,0);
19633 Entry.isSExt = false;
19634 Entry.isZExt = false;
19635 Args.push_back(Entry);
19638 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
19639 getPointerTy(DAG.getDataLayout()));
19641 TargetLowering::CallLoweringInfo CLI(DAG);
19642 CLI.setDebugLoc(dl).setChain(InChain)
19643 .setCallee(getLibcallCallingConv(LC),
19644 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
19645 Callee, std::move(Args))
19646 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
19648 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
19649 return DAG.getBitcast(VT, CallInfo.first);
19652 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget &Subtarget,
19653 SelectionDAG &DAG) {
19654 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
19655 MVT VT = Op0.getSimpleValueType();
19658 // Decompose 256-bit ops into smaller 128-bit ops.
19659 if (VT.is256BitVector() && !Subtarget.hasInt256()) {
19660 unsigned Opcode = Op.getOpcode();
19661 unsigned NumElems = VT.getVectorNumElements();
19662 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(), NumElems / 2);
19663 SDValue Lo0 = extract128BitVector(Op0, 0, DAG, dl);
19664 SDValue Lo1 = extract128BitVector(Op1, 0, DAG, dl);
19665 SDValue Hi0 = extract128BitVector(Op0, NumElems / 2, DAG, dl);
19666 SDValue Hi1 = extract128BitVector(Op1, NumElems / 2, DAG, dl);
19667 SDValue Lo = DAG.getNode(Opcode, dl, DAG.getVTList(HalfVT, HalfVT), Lo0, Lo1);
19668 SDValue Hi = DAG.getNode(Opcode, dl, DAG.getVTList(HalfVT, HalfVT), Hi0, Hi1);
19670 DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo.getValue(0), Hi.getValue(0)),
19671 DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo.getValue(1), Hi.getValue(1))
19673 return DAG.getMergeValues(Ops, dl);
19676 assert((VT == MVT::v4i32 && Subtarget.hasSSE2()) ||
19677 (VT == MVT::v8i32 && Subtarget.hasInt256()));
19679 // PMULxD operations multiply each even value (starting at 0) of LHS with
19680 // the related value of RHS and produce a widen result.
19681 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
19682 // => <2 x i64> <ae|cg>
19684 // In other word, to have all the results, we need to perform two PMULxD:
19685 // 1. one with the even values.
19686 // 2. one with the odd values.
19687 // To achieve #2, with need to place the odd values at an even position.
19689 // Place the odd value at an even position (basically, shift all values 1
19690 // step to the left):
19691 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
19692 // <a|b|c|d> => <b|undef|d|undef>
19693 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0,
19694 makeArrayRef(&Mask[0], VT.getVectorNumElements()));
19695 // <e|f|g|h> => <f|undef|h|undef>
19696 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1,
19697 makeArrayRef(&Mask[0], VT.getVectorNumElements()));
19699 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
19701 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
19702 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
19704 (!IsSigned || !Subtarget.hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
19705 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
19706 // => <2 x i64> <ae|cg>
19707 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
19708 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
19709 // => <2 x i64> <bf|dh>
19710 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
19712 // Shuffle it back into the right order.
19713 SDValue Highs, Lows;
19714 if (VT == MVT::v8i32) {
19715 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
19716 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
19717 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
19718 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
19720 const int HighMask[] = {1, 5, 3, 7};
19721 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
19722 const int LowMask[] = {0, 4, 2, 6};
19723 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
19726 // If we have a signed multiply but no PMULDQ fix up the high parts of a
19727 // unsigned multiply.
19728 if (IsSigned && !Subtarget.hasSSE41()) {
19729 SDValue ShAmt = DAG.getConstant(
19731 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
19732 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
19733 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
19734 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
19735 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
19737 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
19738 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
19741 // The first result of MUL_LOHI is actually the low value, followed by the
19743 SDValue Ops[] = {Lows, Highs};
19744 return DAG.getMergeValues(Ops, dl);
19747 // Return true if the required (according to Opcode) shift-imm form is natively
19748 // supported by the Subtarget
19749 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget &Subtarget,
19751 if (VT.getScalarSizeInBits() < 16)
19754 if (VT.is512BitVector() &&
19755 (VT.getScalarSizeInBits() > 16 || Subtarget.hasBWI()))
19758 bool LShift = VT.is128BitVector() ||
19759 (VT.is256BitVector() && Subtarget.hasInt256());
19761 bool AShift = LShift && (Subtarget.hasVLX() ||
19762 (VT != MVT::v2i64 && VT != MVT::v4i64));
19763 return (Opcode == ISD::SRA) ? AShift : LShift;
19766 // The shift amount is a variable, but it is the same for all vector lanes.
19767 // These instructions are defined together with shift-immediate.
19769 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget &Subtarget,
19771 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
19774 // Return true if the required (according to Opcode) variable-shift form is
19775 // natively supported by the Subtarget
19776 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget &Subtarget,
19779 if (!Subtarget.hasInt256() || VT.getScalarSizeInBits() < 16)
19782 // vXi16 supported only on AVX-512, BWI
19783 if (VT.getScalarSizeInBits() == 16 && !Subtarget.hasBWI())
19786 if (VT.is512BitVector() || Subtarget.hasVLX())
19789 bool LShift = VT.is128BitVector() || VT.is256BitVector();
19790 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
19791 return (Opcode == ISD::SRA) ? AShift : LShift;
19794 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
19795 const X86Subtarget &Subtarget) {
19796 MVT VT = Op.getSimpleValueType();
19798 SDValue R = Op.getOperand(0);
19799 SDValue Amt = Op.getOperand(1);
19801 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
19802 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
19804 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
19805 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
19806 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
19807 SDValue Ex = DAG.getBitcast(ExVT, R);
19809 if (ShiftAmt >= 32) {
19810 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
19812 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
19813 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
19814 ShiftAmt - 32, DAG);
19815 if (VT == MVT::v2i64)
19816 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
19817 if (VT == MVT::v4i64)
19818 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
19819 {9, 1, 11, 3, 13, 5, 15, 7});
19821 // SRA upper i32, SHL whole i64 and select lower i32.
19822 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
19825 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
19826 Lower = DAG.getBitcast(ExVT, Lower);
19827 if (VT == MVT::v2i64)
19828 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
19829 if (VT == MVT::v4i64)
19830 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
19831 {8, 1, 10, 3, 12, 5, 14, 7});
19833 return DAG.getBitcast(VT, Ex);
19836 // Optimize shl/srl/sra with constant shift amount.
19837 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
19838 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
19839 uint64_t ShiftAmt = ShiftConst->getZExtValue();
19841 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
19842 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
19844 // i64 SRA needs to be performed as partial shifts.
19845 if ((VT == MVT::v2i64 || (Subtarget.hasInt256() && VT == MVT::v4i64)) &&
19846 Op.getOpcode() == ISD::SRA && !Subtarget.hasXOP())
19847 return ArithmeticShiftRight64(ShiftAmt);
19849 if (VT == MVT::v16i8 ||
19850 (Subtarget.hasInt256() && VT == MVT::v32i8) ||
19851 VT == MVT::v64i8) {
19852 unsigned NumElts = VT.getVectorNumElements();
19853 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
19855 // Simple i8 add case
19856 if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
19857 return DAG.getNode(ISD::ADD, dl, VT, R, R);
19859 // ashr(R, 7) === cmp_slt(R, 0)
19860 if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
19861 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19862 if (VT.is512BitVector()) {
19863 assert(VT == MVT::v64i8 && "Unexpected element type!");
19864 SDValue CMP = DAG.getNode(X86ISD::PCMPGTM, dl, MVT::v64i1, Zeros, R);
19865 return DAG.getNode(ISD::SIGN_EXTEND, dl, VT, CMP);
19867 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
19870 // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
19871 if (VT == MVT::v16i8 && Subtarget.hasXOP())
19874 if (Op.getOpcode() == ISD::SHL) {
19875 // Make a large shift.
19876 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
19878 SHL = DAG.getBitcast(VT, SHL);
19879 // Zero out the rightmost bits.
19880 return DAG.getNode(ISD::AND, dl, VT, SHL,
19881 DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, VT));
19883 if (Op.getOpcode() == ISD::SRL) {
19884 // Make a large shift.
19885 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
19887 SRL = DAG.getBitcast(VT, SRL);
19888 // Zero out the leftmost bits.
19889 return DAG.getNode(ISD::AND, dl, VT, SRL,
19890 DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
19892 if (Op.getOpcode() == ISD::SRA) {
19893 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
19894 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
19896 SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
19897 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
19898 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
19901 llvm_unreachable("Unknown shift opcode.");
19906 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
19907 if (!Subtarget.is64Bit() && !Subtarget.hasXOP() &&
19908 (VT == MVT::v2i64 || (Subtarget.hasInt256() && VT == MVT::v4i64))) {
19910 // Peek through any splat that was introduced for i64 shift vectorization.
19911 int SplatIndex = -1;
19912 if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
19913 if (SVN->isSplat()) {
19914 SplatIndex = SVN->getSplatIndex();
19915 Amt = Amt.getOperand(0);
19916 assert(SplatIndex < (int)VT.getVectorNumElements() &&
19917 "Splat shuffle referencing second operand");
19920 if (Amt.getOpcode() != ISD::BITCAST ||
19921 Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
19924 Amt = Amt.getOperand(0);
19925 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
19926 VT.getVectorNumElements();
19927 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
19928 uint64_t ShiftAmt = 0;
19929 unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
19930 for (unsigned i = 0; i != Ratio; ++i) {
19931 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
19935 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
19938 // Check remaining shift amounts (if not a splat).
19939 if (SplatIndex < 0) {
19940 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
19941 uint64_t ShAmt = 0;
19942 for (unsigned j = 0; j != Ratio; ++j) {
19943 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
19947 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
19949 if (ShAmt != ShiftAmt)
19954 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
19955 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
19957 if (Op.getOpcode() == ISD::SRA)
19958 return ArithmeticShiftRight64(ShiftAmt);
19964 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
19965 const X86Subtarget &Subtarget) {
19966 MVT VT = Op.getSimpleValueType();
19968 SDValue R = Op.getOperand(0);
19969 SDValue Amt = Op.getOperand(1);
19971 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
19972 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
19974 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
19975 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
19977 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
19979 MVT EltVT = VT.getVectorElementType();
19981 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
19982 // Check if this build_vector node is doing a splat.
19983 // If so, then set BaseShAmt equal to the splat value.
19984 BaseShAmt = BV->getSplatValue();
19985 if (BaseShAmt && BaseShAmt.isUndef())
19986 BaseShAmt = SDValue();
19988 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
19989 Amt = Amt.getOperand(0);
19991 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
19992 if (SVN && SVN->isSplat()) {
19993 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
19994 SDValue InVec = Amt.getOperand(0);
19995 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
19996 assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
19997 "Unexpected shuffle index found!");
19998 BaseShAmt = InVec.getOperand(SplatIdx);
19999 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
20000 if (ConstantSDNode *C =
20001 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
20002 if (C->getZExtValue() == SplatIdx)
20003 BaseShAmt = InVec.getOperand(1);
20008 // Avoid introducing an extract element from a shuffle.
20009 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
20010 DAG.getIntPtrConstant(SplatIdx, dl));
20014 if (BaseShAmt.getNode()) {
20015 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
20016 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
20017 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
20018 else if (EltVT.bitsLT(MVT::i32))
20019 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
20021 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
20025 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
20026 if (!Subtarget.is64Bit() && VT == MVT::v2i64 &&
20027 Amt.getOpcode() == ISD::BITCAST &&
20028 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
20029 Amt = Amt.getOperand(0);
20030 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
20031 VT.getVectorNumElements();
20032 std::vector<SDValue> Vals(Ratio);
20033 for (unsigned i = 0; i != Ratio; ++i)
20034 Vals[i] = Amt.getOperand(i);
20035 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
20036 for (unsigned j = 0; j != Ratio; ++j)
20037 if (Vals[j] != Amt.getOperand(i + j))
20041 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
20042 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
20047 static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
20048 SelectionDAG &DAG) {
20049 MVT VT = Op.getSimpleValueType();
20051 SDValue R = Op.getOperand(0);
20052 SDValue Amt = Op.getOperand(1);
20053 bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
20055 assert(VT.isVector() && "Custom lowering only for vector shifts!");
20056 assert(Subtarget.hasSSE2() && "Only custom lower when we have SSE2!");
20058 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
20061 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
20064 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
20067 // XOP has 128-bit variable logical/arithmetic shifts.
20068 // +ve/-ve Amt = shift left/right.
20069 if (Subtarget.hasXOP() &&
20070 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
20071 VT == MVT::v8i16 || VT == MVT::v16i8)) {
20072 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
20073 SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
20074 Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
20076 if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
20077 return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
20078 if (Op.getOpcode() == ISD::SRA)
20079 return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
20082 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
20083 // shifts per-lane and then shuffle the partial results back together.
20084 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
20085 // Splat the shift amounts so the scalar shifts above will catch it.
20086 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
20087 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
20088 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
20089 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
20090 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
20093 // i64 vector arithmetic shift can be emulated with the transform:
20094 // M = lshr(SIGN_BIT, Amt)
20095 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
20096 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget.hasInt256())) &&
20097 Op.getOpcode() == ISD::SRA) {
20098 SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
20099 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
20100 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
20101 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
20102 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
20106 // If possible, lower this packed shift into a vector multiply instead of
20107 // expanding it into a sequence of scalar shifts.
20108 // Do this only if the vector shift count is a constant build_vector.
20109 if (ConstantAmt && Op.getOpcode() == ISD::SHL &&
20110 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
20111 (Subtarget.hasInt256() && VT == MVT::v16i16))) {
20112 SmallVector<SDValue, 8> Elts;
20113 MVT SVT = VT.getVectorElementType();
20114 unsigned SVTBits = SVT.getSizeInBits();
20115 APInt One(SVTBits, 1);
20116 unsigned NumElems = VT.getVectorNumElements();
20118 for (unsigned i=0; i !=NumElems; ++i) {
20119 SDValue Op = Amt->getOperand(i);
20120 if (Op->isUndef()) {
20121 Elts.push_back(Op);
20125 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
20126 APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
20127 uint64_t ShAmt = C.getZExtValue();
20128 if (ShAmt >= SVTBits) {
20129 Elts.push_back(DAG.getUNDEF(SVT));
20132 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
20134 SDValue BV = DAG.getBuildVector(VT, dl, Elts);
20135 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
20138 // Lower SHL with variable shift amount.
20139 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
20140 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
20142 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
20143 DAG.getConstant(0x3f800000U, dl, VT));
20144 Op = DAG.getBitcast(MVT::v4f32, Op);
20145 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
20146 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
20149 // If possible, lower this shift as a sequence of two shifts by
20150 // constant plus a MOVSS/MOVSD instead of scalarizing it.
20152 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
20154 // Could be rewritten as:
20155 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
20157 // The advantage is that the two shifts from the example would be
20158 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
20159 // the vector shift into four scalar shifts plus four pairs of vector
20161 if (ConstantAmt && (VT == MVT::v8i16 || VT == MVT::v4i32)) {
20162 unsigned TargetOpcode = X86ISD::MOVSS;
20163 bool CanBeSimplified;
20164 // The splat value for the first packed shift (the 'X' from the example).
20165 SDValue Amt1 = Amt->getOperand(0);
20166 // The splat value for the second packed shift (the 'Y' from the example).
20167 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) : Amt->getOperand(2);
20169 // See if it is possible to replace this node with a sequence of
20170 // two shifts followed by a MOVSS/MOVSD
20171 if (VT == MVT::v4i32) {
20172 // Check if it is legal to use a MOVSS.
20173 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
20174 Amt2 == Amt->getOperand(3);
20175 if (!CanBeSimplified) {
20176 // Otherwise, check if we can still simplify this node using a MOVSD.
20177 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
20178 Amt->getOperand(2) == Amt->getOperand(3);
20179 TargetOpcode = X86ISD::MOVSD;
20180 Amt2 = Amt->getOperand(2);
20183 // Do similar checks for the case where the machine value type
20185 CanBeSimplified = Amt1 == Amt->getOperand(1);
20186 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
20187 CanBeSimplified = Amt2 == Amt->getOperand(i);
20189 if (!CanBeSimplified) {
20190 TargetOpcode = X86ISD::MOVSD;
20191 CanBeSimplified = true;
20192 Amt2 = Amt->getOperand(4);
20193 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
20194 CanBeSimplified = Amt1 == Amt->getOperand(i);
20195 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
20196 CanBeSimplified = Amt2 == Amt->getOperand(j);
20200 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
20201 isa<ConstantSDNode>(Amt2)) {
20202 // Replace this node with two shifts followed by a MOVSS/MOVSD.
20203 MVT CastVT = MVT::v4i32;
20205 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
20206 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
20208 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
20209 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
20210 if (TargetOpcode == X86ISD::MOVSD)
20211 CastVT = MVT::v2i64;
20212 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
20213 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
20214 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
20216 return DAG.getBitcast(VT, Result);
20220 // v4i32 Non Uniform Shifts.
20221 // If the shift amount is constant we can shift each lane using the SSE2
20222 // immediate shifts, else we need to zero-extend each lane to the lower i64
20223 // and shift using the SSE2 variable shifts.
20224 // The separate results can then be blended together.
20225 if (VT == MVT::v4i32) {
20226 unsigned Opc = Op.getOpcode();
20227 SDValue Amt0, Amt1, Amt2, Amt3;
20229 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
20230 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
20231 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
20232 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
20234 // ISD::SHL is handled above but we include it here for completeness.
20237 llvm_unreachable("Unknown target vector shift node");
20239 Opc = X86ISD::VSHL;
20242 Opc = X86ISD::VSRL;
20245 Opc = X86ISD::VSRA;
20248 // The SSE2 shifts use the lower i64 as the same shift amount for
20249 // all lanes and the upper i64 is ignored. These shuffle masks
20250 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
20251 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
20252 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
20253 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
20254 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
20255 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
20258 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
20259 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
20260 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
20261 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
20262 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
20263 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
20264 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
20267 if (VT == MVT::v16i8 ||
20268 (VT == MVT::v32i8 && Subtarget.hasInt256() && !Subtarget.hasXOP())) {
20269 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
20270 unsigned ShiftOpcode = Op->getOpcode();
20272 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
20273 // On SSE41 targets we make use of the fact that VSELECT lowers
20274 // to PBLENDVB which selects bytes based just on the sign bit.
20275 if (Subtarget.hasSSE41()) {
20276 V0 = DAG.getBitcast(VT, V0);
20277 V1 = DAG.getBitcast(VT, V1);
20278 Sel = DAG.getBitcast(VT, Sel);
20279 return DAG.getBitcast(SelVT,
20280 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
20282 // On pre-SSE41 targets we test for the sign bit by comparing to
20283 // zero - a negative value will set all bits of the lanes to true
20284 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
20285 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
20286 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
20287 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
20290 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
20291 // We can safely do this using i16 shifts as we're only interested in
20292 // the 3 lower bits of each byte.
20293 Amt = DAG.getBitcast(ExtVT, Amt);
20294 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
20295 Amt = DAG.getBitcast(VT, Amt);
20297 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
20298 // r = VSELECT(r, shift(r, 4), a);
20300 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
20301 R = SignBitSelect(VT, Amt, M, R);
20304 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
20306 // r = VSELECT(r, shift(r, 2), a);
20307 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
20308 R = SignBitSelect(VT, Amt, M, R);
20311 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
20313 // return VSELECT(r, shift(r, 1), a);
20314 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
20315 R = SignBitSelect(VT, Amt, M, R);
20319 if (Op->getOpcode() == ISD::SRA) {
20320 // For SRA we need to unpack each byte to the higher byte of a i16 vector
20321 // so we can correctly sign extend. We don't care what happens to the
20323 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
20324 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
20325 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
20326 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
20327 ALo = DAG.getBitcast(ExtVT, ALo);
20328 AHi = DAG.getBitcast(ExtVT, AHi);
20329 RLo = DAG.getBitcast(ExtVT, RLo);
20330 RHi = DAG.getBitcast(ExtVT, RHi);
20332 // r = VSELECT(r, shift(r, 4), a);
20333 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
20334 DAG.getConstant(4, dl, ExtVT));
20335 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
20336 DAG.getConstant(4, dl, ExtVT));
20337 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
20338 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
20341 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
20342 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
20344 // r = VSELECT(r, shift(r, 2), a);
20345 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
20346 DAG.getConstant(2, dl, ExtVT));
20347 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
20348 DAG.getConstant(2, dl, ExtVT));
20349 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
20350 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
20353 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
20354 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
20356 // r = VSELECT(r, shift(r, 1), a);
20357 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
20358 DAG.getConstant(1, dl, ExtVT));
20359 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
20360 DAG.getConstant(1, dl, ExtVT));
20361 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
20362 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
20364 // Logical shift the result back to the lower byte, leaving a zero upper
20366 // meaning that we can safely pack with PACKUSWB.
20368 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
20370 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
20371 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
20375 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
20376 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
20377 // solution better.
20378 if (Subtarget.hasInt256() && VT == MVT::v8i16) {
20379 MVT ExtVT = MVT::v8i32;
20381 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
20382 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
20383 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
20384 return DAG.getNode(ISD::TRUNCATE, dl, VT,
20385 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
20388 if (Subtarget.hasInt256() && !Subtarget.hasXOP() && VT == MVT::v16i16) {
20389 MVT ExtVT = MVT::v8i32;
20390 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
20391 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
20392 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
20393 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Z, R);
20394 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Z, R);
20395 ALo = DAG.getBitcast(ExtVT, ALo);
20396 AHi = DAG.getBitcast(ExtVT, AHi);
20397 RLo = DAG.getBitcast(ExtVT, RLo);
20398 RHi = DAG.getBitcast(ExtVT, RHi);
20399 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
20400 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
20401 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
20402 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
20403 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
20406 if (VT == MVT::v8i16) {
20407 unsigned ShiftOpcode = Op->getOpcode();
20409 // If we have a constant shift amount, the non-SSE41 path is best as
20410 // avoiding bitcasts make it easier to constant fold and reduce to PBLENDW.
20411 bool UseSSE41 = Subtarget.hasSSE41() &&
20412 !ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
20414 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
20415 // On SSE41 targets we make use of the fact that VSELECT lowers
20416 // to PBLENDVB which selects bytes based just on the sign bit.
20418 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
20419 V0 = DAG.getBitcast(ExtVT, V0);
20420 V1 = DAG.getBitcast(ExtVT, V1);
20421 Sel = DAG.getBitcast(ExtVT, Sel);
20422 return DAG.getBitcast(
20423 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
20425 // On pre-SSE41 targets we splat the sign bit - a negative value will
20426 // set all bits of the lanes to true and VSELECT uses that in
20427 // its OR(AND(V0,C),AND(V1,~C)) lowering.
20429 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
20430 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
20433 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
20435 // On SSE41 targets we need to replicate the shift mask in both
20436 // bytes for PBLENDVB.
20439 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
20440 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
20442 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
20445 // r = VSELECT(r, shift(r, 8), a);
20446 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
20447 R = SignBitSelect(Amt, M, R);
20450 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
20452 // r = VSELECT(r, shift(r, 4), a);
20453 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
20454 R = SignBitSelect(Amt, M, R);
20457 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
20459 // r = VSELECT(r, shift(r, 2), a);
20460 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
20461 R = SignBitSelect(Amt, M, R);
20464 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
20466 // return VSELECT(r, shift(r, 1), a);
20467 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
20468 R = SignBitSelect(Amt, M, R);
20472 // Decompose 256-bit shifts into smaller 128-bit shifts.
20473 if (VT.is256BitVector())
20474 return Lower256IntArith(Op, DAG);
20479 static SDValue LowerRotate(SDValue Op, const X86Subtarget &Subtarget,
20480 SelectionDAG &DAG) {
20481 MVT VT = Op.getSimpleValueType();
20483 SDValue R = Op.getOperand(0);
20484 SDValue Amt = Op.getOperand(1);
20486 assert(VT.isVector() && "Custom lowering only for vector rotates!");
20487 assert(Subtarget.hasXOP() && "XOP support required for vector rotates!");
20488 assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
20490 // XOP has 128-bit vector variable + immediate rotates.
20491 // +ve/-ve Amt = rotate left/right.
20493 // Split 256-bit integers.
20494 if (VT.is256BitVector())
20495 return Lower256IntArith(Op, DAG);
20497 assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
20499 // Attempt to rotate by immediate.
20500 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
20501 if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
20502 uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
20503 assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
20504 return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
20505 DAG.getConstant(RotateAmt, DL, MVT::i8));
20509 // Use general rotate by variable (per-element).
20510 return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
20513 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
20514 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
20515 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
20516 // looks for this combo and may remove the "setcc" instruction if the "setcc"
20517 // has only one use.
20518 SDNode *N = Op.getNode();
20519 SDValue LHS = N->getOperand(0);
20520 SDValue RHS = N->getOperand(1);
20521 unsigned BaseOp = 0;
20524 switch (Op.getOpcode()) {
20525 default: llvm_unreachable("Unknown ovf instruction!");
20527 // A subtract of one will be selected as a INC. Note that INC doesn't
20528 // set CF, so we can't do this for UADDO.
20529 if (isOneConstant(RHS)) {
20530 BaseOp = X86ISD::INC;
20531 Cond = X86::COND_O;
20534 BaseOp = X86ISD::ADD;
20535 Cond = X86::COND_O;
20538 BaseOp = X86ISD::ADD;
20539 Cond = X86::COND_B;
20542 // A subtract of one will be selected as a DEC. Note that DEC doesn't
20543 // set CF, so we can't do this for USUBO.
20544 if (isOneConstant(RHS)) {
20545 BaseOp = X86ISD::DEC;
20546 Cond = X86::COND_O;
20549 BaseOp = X86ISD::SUB;
20550 Cond = X86::COND_O;
20553 BaseOp = X86ISD::SUB;
20554 Cond = X86::COND_B;
20557 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
20558 Cond = X86::COND_O;
20560 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
20561 if (N->getValueType(0) == MVT::i8) {
20562 BaseOp = X86ISD::UMUL8;
20563 Cond = X86::COND_O;
20566 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
20568 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
20571 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20572 DAG.getConstant(X86::COND_O, DL, MVT::i32),
20573 SDValue(Sum.getNode(), 2));
20575 if (N->getValueType(1) == MVT::i1) {
20576 SetCC = DAG.getNode(ISD::AssertZext, DL, MVT::i8, SetCC,
20577 DAG.getValueType(MVT::i1));
20578 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
20580 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
20584 // Also sets EFLAGS.
20585 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
20586 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
20589 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20590 DAG.getConstant(Cond, DL, MVT::i32),
20591 SDValue(Sum.getNode(), 1));
20593 if (N->getValueType(1) == MVT::i1) {
20594 SetCC = DAG.getNode(ISD::AssertZext, DL, MVT::i8, SetCC,
20595 DAG.getValueType(MVT::i1));
20596 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
20598 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
20601 /// Returns true if the operand type is exactly twice the native width, and
20602 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
20603 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
20604 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
20605 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
20606 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
20609 return !Subtarget.is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
20610 else if (OpWidth == 128)
20611 return Subtarget.hasCmpxchg16b();
20616 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
20617 return needsCmpXchgNb(SI->getValueOperand()->getType());
20620 // Note: this turns large loads into lock cmpxchg8b/16b.
20621 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
20622 TargetLowering::AtomicExpansionKind
20623 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
20624 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
20625 return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
20626 : AtomicExpansionKind::None;
20629 TargetLowering::AtomicExpansionKind
20630 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
20631 unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
20632 Type *MemType = AI->getType();
20634 // If the operand is too big, we must see if cmpxchg8/16b is available
20635 // and default to library calls otherwise.
20636 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
20637 return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
20638 : AtomicExpansionKind::None;
20641 AtomicRMWInst::BinOp Op = AI->getOperation();
20644 llvm_unreachable("Unknown atomic operation");
20645 case AtomicRMWInst::Xchg:
20646 case AtomicRMWInst::Add:
20647 case AtomicRMWInst::Sub:
20648 // It's better to use xadd, xsub or xchg for these in all cases.
20649 return AtomicExpansionKind::None;
20650 case AtomicRMWInst::Or:
20651 case AtomicRMWInst::And:
20652 case AtomicRMWInst::Xor:
20653 // If the atomicrmw's result isn't actually used, we can just add a "lock"
20654 // prefix to a normal instruction for these operations.
20655 return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
20656 : AtomicExpansionKind::None;
20657 case AtomicRMWInst::Nand:
20658 case AtomicRMWInst::Max:
20659 case AtomicRMWInst::Min:
20660 case AtomicRMWInst::UMax:
20661 case AtomicRMWInst::UMin:
20662 // These always require a non-trivial set of data operations on x86. We must
20663 // use a cmpxchg loop.
20664 return AtomicExpansionKind::CmpXChg;
20669 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
20670 unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
20671 Type *MemType = AI->getType();
20672 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
20673 // there is no benefit in turning such RMWs into loads, and it is actually
20674 // harmful as it introduces a mfence.
20675 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
20678 auto Builder = IRBuilder<>(AI);
20679 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
20680 auto SynchScope = AI->getSynchScope();
20681 // We must restrict the ordering to avoid generating loads with Release or
20682 // ReleaseAcquire orderings.
20683 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
20684 auto Ptr = AI->getPointerOperand();
20686 // Before the load we need a fence. Here is an example lifted from
20687 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
20690 // x.store(1, relaxed);
20691 // r1 = y.fetch_add(0, release);
20693 // y.fetch_add(42, acquire);
20694 // r2 = x.load(relaxed);
20695 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
20696 // lowered to just a load without a fence. A mfence flushes the store buffer,
20697 // making the optimization clearly correct.
20698 // FIXME: it is required if isReleaseOrStronger(Order) but it is not clear
20699 // otherwise, we might be able to be more aggressive on relaxed idempotent
20700 // rmw. In practice, they do not look useful, so we don't try to be
20701 // especially clever.
20702 if (SynchScope == SingleThread)
20703 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
20704 // the IR level, so we must wrap it in an intrinsic.
20707 if (!Subtarget.hasMFence())
20708 // FIXME: it might make sense to use a locked operation here but on a
20709 // different cache-line to prevent cache-line bouncing. In practice it
20710 // is probably a small win, and x86 processors without mfence are rare
20711 // enough that we do not bother.
20715 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
20716 Builder.CreateCall(MFence, {});
20718 // Finally we can emit the atomic load.
20719 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
20720 AI->getType()->getPrimitiveSizeInBits());
20721 Loaded->setAtomic(Order, SynchScope);
20722 AI->replaceAllUsesWith(Loaded);
20723 AI->eraseFromParent();
20727 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget &Subtarget,
20728 SelectionDAG &DAG) {
20730 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
20731 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
20732 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
20733 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
20735 // The only fence that needs an instruction is a sequentially-consistent
20736 // cross-thread fence.
20737 if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
20738 FenceScope == CrossThread) {
20739 if (Subtarget.hasMFence())
20740 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
20742 SDValue Chain = Op.getOperand(0);
20743 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
20745 DAG.getRegister(X86::ESP, MVT::i32), // Base
20746 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
20747 DAG.getRegister(0, MVT::i32), // Index
20748 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
20749 DAG.getRegister(0, MVT::i32), // Segment.
20753 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
20754 return SDValue(Res, 0);
20757 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
20758 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
20761 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget &Subtarget,
20762 SelectionDAG &DAG) {
20763 MVT T = Op.getSimpleValueType();
20767 switch(T.SimpleTy) {
20768 default: llvm_unreachable("Invalid value type!");
20769 case MVT::i8: Reg = X86::AL; size = 1; break;
20770 case MVT::i16: Reg = X86::AX; size = 2; break;
20771 case MVT::i32: Reg = X86::EAX; size = 4; break;
20773 assert(Subtarget.is64Bit() && "Node not type legal!");
20774 Reg = X86::RAX; size = 8;
20777 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
20778 Op.getOperand(2), SDValue());
20779 SDValue Ops[] = { cpIn.getValue(0),
20782 DAG.getTargetConstant(size, DL, MVT::i8),
20783 cpIn.getValue(1) };
20784 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
20785 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
20786 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
20790 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
20791 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
20792 MVT::i32, cpOut.getValue(2));
20793 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
20794 DAG.getConstant(X86::COND_E, DL, MVT::i8),
20797 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
20798 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
20799 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
20803 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget &Subtarget,
20804 SelectionDAG &DAG) {
20805 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
20806 MVT DstVT = Op.getSimpleValueType();
20808 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 ||
20809 SrcVT == MVT::i64) {
20810 assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
20811 if (DstVT != MVT::f64)
20812 // This conversion needs to be expanded.
20815 SDValue Op0 = Op->getOperand(0);
20816 SmallVector<SDValue, 16> Elts;
20820 if (SrcVT.isVector()) {
20821 NumElts = SrcVT.getVectorNumElements();
20822 SVT = SrcVT.getVectorElementType();
20824 // Widen the vector in input in the case of MVT::v2i32.
20825 // Example: from MVT::v2i32 to MVT::v4i32.
20826 for (unsigned i = 0, e = NumElts; i != e; ++i)
20827 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, Op0,
20828 DAG.getIntPtrConstant(i, dl)));
20830 assert(SrcVT == MVT::i64 && !Subtarget.is64Bit() &&
20831 "Unexpected source type in LowerBITCAST");
20832 Elts.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op0,
20833 DAG.getIntPtrConstant(0, dl)));
20834 Elts.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op0,
20835 DAG.getIntPtrConstant(1, dl)));
20839 // Explicitly mark the extra elements as Undef.
20840 Elts.append(NumElts, DAG.getUNDEF(SVT));
20842 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
20843 SDValue BV = DAG.getBuildVector(NewVT, dl, Elts);
20844 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
20845 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
20846 DAG.getIntPtrConstant(0, dl));
20849 assert(Subtarget.is64Bit() && !Subtarget.hasSSE2() &&
20850 Subtarget.hasMMX() && "Unexpected custom BITCAST");
20851 assert((DstVT == MVT::i64 ||
20852 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
20853 "Unexpected custom BITCAST");
20854 // i64 <=> MMX conversions are Legal.
20855 if (SrcVT==MVT::i64 && DstVT.isVector())
20857 if (DstVT==MVT::i64 && SrcVT.isVector())
20859 // MMX <=> MMX conversions are Legal.
20860 if (SrcVT.isVector() && DstVT.isVector())
20862 // All other conversions need to be expanded.
20866 /// Compute the horizontal sum of bytes in V for the elements of VT.
20868 /// Requires V to be a byte vector and VT to be an integer vector type with
20869 /// wider elements than V's type. The width of the elements of VT determines
20870 /// how many bytes of V are summed horizontally to produce each element of the
20872 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
20873 const X86Subtarget &Subtarget,
20874 SelectionDAG &DAG) {
20876 MVT ByteVecVT = V.getSimpleValueType();
20877 MVT EltVT = VT.getVectorElementType();
20878 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
20879 "Expected value to have byte element type.");
20880 assert(EltVT != MVT::i8 &&
20881 "Horizontal byte sum only makes sense for wider elements!");
20882 unsigned VecSize = VT.getSizeInBits();
20883 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
20885 // PSADBW instruction horizontally add all bytes and leave the result in i64
20886 // chunks, thus directly computes the pop count for v2i64 and v4i64.
20887 if (EltVT == MVT::i64) {
20888 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
20889 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
20890 V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
20891 return DAG.getBitcast(VT, V);
20894 if (EltVT == MVT::i32) {
20895 // We unpack the low half and high half into i32s interleaved with zeros so
20896 // that we can use PSADBW to horizontally sum them. The most useful part of
20897 // this is that it lines up the results of two PSADBW instructions to be
20898 // two v2i64 vectors which concatenated are the 4 population counts. We can
20899 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
20900 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
20901 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
20902 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
20904 // Do the horizontal sums into two v2i64s.
20905 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
20906 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
20907 Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
20908 DAG.getBitcast(ByteVecVT, Low), Zeros);
20909 High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
20910 DAG.getBitcast(ByteVecVT, High), Zeros);
20912 // Merge them together.
20913 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
20914 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
20915 DAG.getBitcast(ShortVecVT, Low),
20916 DAG.getBitcast(ShortVecVT, High));
20918 return DAG.getBitcast(VT, V);
20921 // The only element type left is i16.
20922 assert(EltVT == MVT::i16 && "Unknown how to handle type");
20924 // To obtain pop count for each i16 element starting from the pop count for
20925 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
20926 // right by 8. It is important to shift as i16s as i8 vector shift isn't
20927 // directly supported.
20928 SDValue ShifterV = DAG.getConstant(8, DL, VT);
20929 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
20930 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
20931 DAG.getBitcast(ByteVecVT, V));
20932 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
20935 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, const SDLoc &DL,
20936 const X86Subtarget &Subtarget,
20937 SelectionDAG &DAG) {
20938 MVT VT = Op.getSimpleValueType();
20939 MVT EltVT = VT.getVectorElementType();
20940 unsigned VecSize = VT.getSizeInBits();
20942 // Implement a lookup table in register by using an algorithm based on:
20943 // http://wm.ite.pl/articles/sse-popcount.html
20945 // The general idea is that every lower byte nibble in the input vector is an
20946 // index into a in-register pre-computed pop count table. We then split up the
20947 // input vector in two new ones: (1) a vector with only the shifted-right
20948 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
20949 // masked out higher ones) for each byte. PSHUB is used separately with both
20950 // to index the in-register table. Next, both are added and the result is a
20951 // i8 vector where each element contains the pop count for input byte.
20953 // To obtain the pop count for elements != i8, we follow up with the same
20954 // approach and use additional tricks as described below.
20956 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
20957 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
20958 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
20959 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
20961 int NumByteElts = VecSize / 8;
20962 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
20963 SDValue In = DAG.getBitcast(ByteVecVT, Op);
20964 SmallVector<SDValue, 64> LUTVec;
20965 for (int i = 0; i < NumByteElts; ++i)
20966 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
20967 SDValue InRegLUT = DAG.getBuildVector(ByteVecVT, DL, LUTVec);
20968 SDValue M0F = DAG.getConstant(0x0F, DL, ByteVecVT);
20971 SDValue FourV = DAG.getConstant(4, DL, ByteVecVT);
20972 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
20975 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
20977 // The input vector is used as the shuffle mask that index elements into the
20978 // LUT. After counting low and high nibbles, add the vector to obtain the
20979 // final pop count per i8 element.
20980 SDValue HighPopCnt =
20981 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
20982 SDValue LowPopCnt =
20983 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
20984 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
20986 if (EltVT == MVT::i8)
20989 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
20992 static SDValue LowerVectorCTPOPBitmath(SDValue Op, const SDLoc &DL,
20993 const X86Subtarget &Subtarget,
20994 SelectionDAG &DAG) {
20995 MVT VT = Op.getSimpleValueType();
20996 assert(VT.is128BitVector() &&
20997 "Only 128-bit vector bitmath lowering supported.");
20999 int VecSize = VT.getSizeInBits();
21000 MVT EltVT = VT.getVectorElementType();
21001 int Len = EltVT.getSizeInBits();
21003 // This is the vectorized version of the "best" algorithm from
21004 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
21005 // with a minor tweak to use a series of adds + shifts instead of vector
21006 // multiplications. Implemented for all integer vector types. We only use
21007 // this when we don't have SSSE3 which allows a LUT-based lowering that is
21008 // much faster, even faster than using native popcnt instructions.
21010 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
21011 MVT VT = V.getSimpleValueType();
21012 SDValue ShifterV = DAG.getConstant(Shifter, DL, VT);
21013 return DAG.getNode(OpCode, DL, VT, V, ShifterV);
21015 auto GetMask = [&](SDValue V, APInt Mask) {
21016 MVT VT = V.getSimpleValueType();
21017 SDValue MaskV = DAG.getConstant(Mask, DL, VT);
21018 return DAG.getNode(ISD::AND, DL, VT, V, MaskV);
21021 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
21022 // x86, so set the SRL type to have elements at least i16 wide. This is
21023 // correct because all of our SRLs are followed immediately by a mask anyways
21024 // that handles any bits that sneak into the high bits of the byte elements.
21025 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
21029 // v = v - ((v >> 1) & 0x55555555...)
21031 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
21032 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
21033 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
21035 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
21036 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
21037 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
21038 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
21039 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
21041 // v = (v + (v >> 4)) & 0x0F0F0F0F...
21042 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
21043 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
21044 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
21046 // At this point, V contains the byte-wise population count, and we are
21047 // merely doing a horizontal sum if necessary to get the wider element
21049 if (EltVT == MVT::i8)
21052 return LowerHorizontalByteSum(
21053 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
21057 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget &Subtarget,
21058 SelectionDAG &DAG) {
21059 MVT VT = Op.getSimpleValueType();
21060 assert((VT.is512BitVector() || VT.is256BitVector() || VT.is128BitVector()) &&
21061 "Unknown CTPOP type to handle");
21062 SDLoc DL(Op.getNode());
21063 SDValue Op0 = Op.getOperand(0);
21065 if (!Subtarget.hasSSSE3()) {
21066 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
21067 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
21068 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
21071 if (VT.is256BitVector() && !Subtarget.hasInt256()) {
21072 unsigned NumElems = VT.getVectorNumElements();
21074 // Extract each 128-bit vector, compute pop count and concat the result.
21075 SDValue LHS = extract128BitVector(Op0, 0, DAG, DL);
21076 SDValue RHS = extract128BitVector(Op0, NumElems / 2, DAG, DL);
21078 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
21079 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
21080 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
21083 if (VT.is512BitVector() && !Subtarget.hasBWI()) {
21084 unsigned NumElems = VT.getVectorNumElements();
21086 // Extract each 256-bit vector, compute pop count and concat the result.
21087 SDValue LHS = extract256BitVector(Op0, 0, DAG, DL);
21088 SDValue RHS = extract256BitVector(Op0, NumElems / 2, DAG, DL);
21090 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
21091 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
21092 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
21095 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
21098 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget &Subtarget,
21099 SelectionDAG &DAG) {
21100 assert(Op.getSimpleValueType().isVector() &&
21101 "We only do custom lowering for vector population count.");
21102 return LowerVectorCTPOP(Op, Subtarget, DAG);
21105 static SDValue LowerBITREVERSE_XOP(SDValue Op, SelectionDAG &DAG) {
21106 MVT VT = Op.getSimpleValueType();
21107 SDValue In = Op.getOperand(0);
21110 // For scalars, its still beneficial to transfer to/from the SIMD unit to
21111 // perform the BITREVERSE.
21112 if (!VT.isVector()) {
21113 MVT VecVT = MVT::getVectorVT(VT, 128 / VT.getSizeInBits());
21114 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, In);
21115 Res = DAG.getNode(ISD::BITREVERSE, DL, VecVT, Res);
21116 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Res,
21117 DAG.getIntPtrConstant(0, DL));
21120 MVT SVT = VT.getVectorElementType();
21121 int NumElts = VT.getVectorNumElements();
21122 int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
21124 // Decompose 256-bit ops into smaller 128-bit ops.
21125 if (VT.is256BitVector()) {
21126 SDValue Lo = extract128BitVector(In, 0, DAG, DL);
21127 SDValue Hi = extract128BitVector(In, NumElts / 2, DAG, DL);
21129 MVT HalfVT = MVT::getVectorVT(SVT, NumElts / 2);
21130 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
21131 DAG.getNode(ISD::BITREVERSE, DL, HalfVT, Lo),
21132 DAG.getNode(ISD::BITREVERSE, DL, HalfVT, Hi));
21135 assert(VT.is128BitVector() &&
21136 "Only 128-bit vector bitreverse lowering supported.");
21138 // VPPERM reverses the bits of a byte with the permute Op (2 << 5), and we
21139 // perform the BSWAP in the shuffle.
21140 // Its best to shuffle using the second operand as this will implicitly allow
21141 // memory folding for multiple vectors.
21142 SmallVector<SDValue, 16> MaskElts;
21143 for (int i = 0; i != NumElts; ++i) {
21144 for (int j = ScalarSizeInBytes - 1; j >= 0; --j) {
21145 int SourceByte = 16 + (i * ScalarSizeInBytes) + j;
21146 int PermuteByte = SourceByte | (2 << 5);
21147 MaskElts.push_back(DAG.getConstant(PermuteByte, DL, MVT::i8));
21151 SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, MaskElts);
21152 SDValue Res = DAG.getBitcast(MVT::v16i8, In);
21153 Res = DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, DAG.getUNDEF(MVT::v16i8),
21155 return DAG.getBitcast(VT, Res);
21158 static SDValue LowerBITREVERSE(SDValue Op, const X86Subtarget &Subtarget,
21159 SelectionDAG &DAG) {
21160 if (Subtarget.hasXOP())
21161 return LowerBITREVERSE_XOP(Op, DAG);
21163 assert(Subtarget.hasSSSE3() && "SSSE3 required for BITREVERSE");
21165 MVT VT = Op.getSimpleValueType();
21166 SDValue In = Op.getOperand(0);
21169 unsigned NumElts = VT.getVectorNumElements();
21170 assert(VT.getScalarType() == MVT::i8 &&
21171 "Only byte vector BITREVERSE supported");
21173 // Decompose 256-bit ops into smaller 128-bit ops on pre-AVX2.
21174 if (VT.is256BitVector() && !Subtarget.hasInt256()) {
21175 MVT HalfVT = MVT::getVectorVT(MVT::i8, NumElts / 2);
21176 SDValue Lo = extract128BitVector(In, 0, DAG, DL);
21177 SDValue Hi = extract128BitVector(In, NumElts / 2, DAG, DL);
21178 Lo = DAG.getNode(ISD::BITREVERSE, DL, HalfVT, Lo);
21179 Hi = DAG.getNode(ISD::BITREVERSE, DL, HalfVT, Hi);
21180 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
21183 // Perform BITREVERSE using PSHUFB lookups. Each byte is split into
21184 // two nibbles and a PSHUFB lookup to find the bitreverse of each
21185 // 0-15 value (moved to the other nibble).
21186 SDValue NibbleMask = DAG.getConstant(0xF, DL, VT);
21187 SDValue Lo = DAG.getNode(ISD::AND, DL, VT, In, NibbleMask);
21188 SDValue Hi = DAG.getNode(ISD::SRL, DL, VT, In, DAG.getConstant(4, DL, VT));
21190 const int LoLUT[16] = {
21191 /* 0 */ 0x00, /* 1 */ 0x80, /* 2 */ 0x40, /* 3 */ 0xC0,
21192 /* 4 */ 0x20, /* 5 */ 0xA0, /* 6 */ 0x60, /* 7 */ 0xE0,
21193 /* 8 */ 0x10, /* 9 */ 0x90, /* a */ 0x50, /* b */ 0xD0,
21194 /* c */ 0x30, /* d */ 0xB0, /* e */ 0x70, /* f */ 0xF0};
21195 const int HiLUT[16] = {
21196 /* 0 */ 0x00, /* 1 */ 0x08, /* 2 */ 0x04, /* 3 */ 0x0C,
21197 /* 4 */ 0x02, /* 5 */ 0x0A, /* 6 */ 0x06, /* 7 */ 0x0E,
21198 /* 8 */ 0x01, /* 9 */ 0x09, /* a */ 0x05, /* b */ 0x0D,
21199 /* c */ 0x03, /* d */ 0x0B, /* e */ 0x07, /* f */ 0x0F};
21201 SmallVector<SDValue, 16> LoMaskElts, HiMaskElts;
21202 for (unsigned i = 0; i < NumElts; ++i) {
21203 LoMaskElts.push_back(DAG.getConstant(LoLUT[i % 16], DL, MVT::i8));
21204 HiMaskElts.push_back(DAG.getConstant(HiLUT[i % 16], DL, MVT::i8));
21207 SDValue LoMask = DAG.getBuildVector(VT, DL, LoMaskElts);
21208 SDValue HiMask = DAG.getBuildVector(VT, DL, HiMaskElts);
21209 Lo = DAG.getNode(X86ISD::PSHUFB, DL, VT, LoMask, Lo);
21210 Hi = DAG.getNode(X86ISD::PSHUFB, DL, VT, HiMask, Hi);
21211 return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
21214 static SDValue lowerAtomicArithWithLOCK(SDValue N, SelectionDAG &DAG) {
21215 unsigned NewOpc = 0;
21216 switch (N->getOpcode()) {
21217 case ISD::ATOMIC_LOAD_ADD:
21218 NewOpc = X86ISD::LADD;
21220 case ISD::ATOMIC_LOAD_SUB:
21221 NewOpc = X86ISD::LSUB;
21223 case ISD::ATOMIC_LOAD_OR:
21224 NewOpc = X86ISD::LOR;
21226 case ISD::ATOMIC_LOAD_XOR:
21227 NewOpc = X86ISD::LXOR;
21229 case ISD::ATOMIC_LOAD_AND:
21230 NewOpc = X86ISD::LAND;
21233 llvm_unreachable("Unknown ATOMIC_LOAD_ opcode");
21236 MachineMemOperand *MMO = cast<MemSDNode>(N)->getMemOperand();
21237 return DAG.getMemIntrinsicNode(
21238 NewOpc, SDLoc(N), DAG.getVTList(MVT::i32, MVT::Other),
21239 {N->getOperand(0), N->getOperand(1), N->getOperand(2)},
21240 /*MemVT=*/N->getSimpleValueType(0), MMO);
21243 /// Lower atomic_load_ops into LOCK-prefixed operations.
21244 static SDValue lowerAtomicArith(SDValue N, SelectionDAG &DAG,
21245 const X86Subtarget &Subtarget) {
21246 SDValue Chain = N->getOperand(0);
21247 SDValue LHS = N->getOperand(1);
21248 SDValue RHS = N->getOperand(2);
21249 unsigned Opc = N->getOpcode();
21250 MVT VT = N->getSimpleValueType(0);
21253 // We can lower atomic_load_add into LXADD. However, any other atomicrmw op
21254 // can only be lowered when the result is unused. They should have already
21255 // been transformed into a cmpxchg loop in AtomicExpand.
21256 if (N->hasAnyUseOfValue(0)) {
21257 // Handle (atomic_load_sub p, v) as (atomic_load_add p, -v), to be able to
21258 // select LXADD if LOCK_SUB can't be selected.
21259 if (Opc == ISD::ATOMIC_LOAD_SUB) {
21260 AtomicSDNode *AN = cast<AtomicSDNode>(N.getNode());
21261 RHS = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), RHS);
21262 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, VT, Chain, LHS,
21263 RHS, AN->getMemOperand(), AN->getOrdering(),
21264 AN->getSynchScope());
21266 assert(Opc == ISD::ATOMIC_LOAD_ADD &&
21267 "Used AtomicRMW ops other than Add should have been expanded!");
21271 SDValue LockOp = lowerAtomicArithWithLOCK(N, DAG);
21272 // RAUW the chain, but don't worry about the result, as it's unused.
21273 assert(!N->hasAnyUseOfValue(0));
21274 DAG.ReplaceAllUsesOfValueWith(N.getValue(1), LockOp.getValue(1));
21278 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
21279 SDNode *Node = Op.getNode();
21281 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
21283 // Convert seq_cst store -> xchg
21284 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
21285 // FIXME: On 32-bit, store -> fist or movq would be more efficient
21286 // (The only way to get a 16-byte store is cmpxchg16b)
21287 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
21288 if (cast<AtomicSDNode>(Node)->getOrdering() ==
21289 AtomicOrdering::SequentiallyConsistent ||
21290 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
21291 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
21292 cast<AtomicSDNode>(Node)->getMemoryVT(),
21293 Node->getOperand(0),
21294 Node->getOperand(1), Node->getOperand(2),
21295 cast<AtomicSDNode>(Node)->getMemOperand(),
21296 cast<AtomicSDNode>(Node)->getOrdering(),
21297 cast<AtomicSDNode>(Node)->getSynchScope());
21298 return Swap.getValue(1);
21300 // Other atomic stores have a simple pattern.
21304 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
21305 MVT VT = Op.getNode()->getSimpleValueType(0);
21307 // Let legalize expand this if it isn't a legal type yet.
21308 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
21311 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
21314 bool ExtraOp = false;
21315 switch (Op.getOpcode()) {
21316 default: llvm_unreachable("Invalid code");
21317 case ISD::ADDC: Opc = X86ISD::ADD; break;
21318 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
21319 case ISD::SUBC: Opc = X86ISD::SUB; break;
21320 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
21324 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
21326 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
21327 Op.getOperand(1), Op.getOperand(2));
21330 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget &Subtarget,
21331 SelectionDAG &DAG) {
21332 assert(Subtarget.isTargetDarwin() && Subtarget.is64Bit());
21334 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
21335 // which returns the values as { float, float } (in XMM0) or
21336 // { double, double } (which is returned in XMM0, XMM1).
21338 SDValue Arg = Op.getOperand(0);
21339 EVT ArgVT = Arg.getValueType();
21340 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
21342 TargetLowering::ArgListTy Args;
21343 TargetLowering::ArgListEntry Entry;
21347 Entry.isSExt = false;
21348 Entry.isZExt = false;
21349 Args.push_back(Entry);
21351 bool isF64 = ArgVT == MVT::f64;
21352 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
21353 // the small struct {f32, f32} is returned in (eax, edx). For f64,
21354 // the results are returned via SRet in memory.
21355 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
21356 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21358 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
21360 Type *RetTy = isF64
21361 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
21362 : (Type*)VectorType::get(ArgTy, 4);
21364 TargetLowering::CallLoweringInfo CLI(DAG);
21365 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
21366 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args));
21368 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
21371 // Returned in xmm0 and xmm1.
21372 return CallResult.first;
21374 // Returned in bits 0:31 and 32:64 xmm0.
21375 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
21376 CallResult.first, DAG.getIntPtrConstant(0, dl));
21377 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
21378 CallResult.first, DAG.getIntPtrConstant(1, dl));
21379 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
21380 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
21383 /// Widen a vector input to a vector of NVT. The
21384 /// input vector must have the same element type as NVT.
21385 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
21386 bool FillWithZeroes = false) {
21387 // Check if InOp already has the right width.
21388 MVT InVT = InOp.getSimpleValueType();
21392 if (InOp.isUndef())
21393 return DAG.getUNDEF(NVT);
21395 assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
21396 "input and widen element type must match");
21398 unsigned InNumElts = InVT.getVectorNumElements();
21399 unsigned WidenNumElts = NVT.getVectorNumElements();
21400 assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
21401 "Unexpected request for vector widening");
21403 EVT EltVT = NVT.getVectorElementType();
21406 if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
21407 InOp.getNumOperands() == 2) {
21408 SDValue N1 = InOp.getOperand(1);
21409 if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
21411 InOp = InOp.getOperand(0);
21412 InVT = InOp.getSimpleValueType();
21413 InNumElts = InVT.getVectorNumElements();
21416 if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
21417 ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
21418 SmallVector<SDValue, 16> Ops;
21419 for (unsigned i = 0; i < InNumElts; ++i)
21420 Ops.push_back(InOp.getOperand(i));
21422 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
21423 DAG.getUNDEF(EltVT);
21424 for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
21425 Ops.push_back(FillVal);
21426 return DAG.getBuildVector(NVT, dl, Ops);
21428 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
21430 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
21431 InOp, DAG.getIntPtrConstant(0, dl));
21434 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget &Subtarget,
21435 SelectionDAG &DAG) {
21436 assert(Subtarget.hasAVX512() &&
21437 "MGATHER/MSCATTER are supported on AVX-512 arch only");
21439 // X86 scatter kills mask register, so its type should be added to
21440 // the list of return values.
21441 // If the "scatter" has 2 return values, it is already handled.
21442 if (Op.getNode()->getNumValues() == 2)
21445 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
21446 SDValue Src = N->getValue();
21447 MVT VT = Src.getSimpleValueType();
21448 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
21451 SDValue NewScatter;
21452 SDValue Index = N->getIndex();
21453 SDValue Mask = N->getMask();
21454 SDValue Chain = N->getChain();
21455 SDValue BasePtr = N->getBasePtr();
21456 MVT MemVT = N->getMemoryVT().getSimpleVT();
21457 MVT IndexVT = Index.getSimpleValueType();
21458 MVT MaskVT = Mask.getSimpleValueType();
21460 if (MemVT.getScalarSizeInBits() < VT.getScalarSizeInBits()) {
21461 // The v2i32 value was promoted to v2i64.
21462 // Now we "redo" the type legalizer's work and widen the original
21463 // v2i32 value to v4i32. The original v2i32 is retrieved from v2i64
21465 assert((MemVT == MVT::v2i32 && VT == MVT::v2i64) &&
21466 "Unexpected memory type");
21467 int ShuffleMask[] = {0, 2, -1, -1};
21468 Src = DAG.getVectorShuffle(MVT::v4i32, dl, DAG.getBitcast(MVT::v4i32, Src),
21469 DAG.getUNDEF(MVT::v4i32), ShuffleMask);
21470 // Now we have 4 elements instead of 2.
21471 // Expand the index.
21472 MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), 4);
21473 Index = ExtendToType(Index, NewIndexVT, DAG);
21475 // Expand the mask with zeroes
21476 // Mask may be <2 x i64> or <2 x i1> at this moment
21477 assert((MaskVT == MVT::v2i1 || MaskVT == MVT::v2i64) &&
21478 "Unexpected mask type");
21479 MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), 4);
21480 Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
21484 unsigned NumElts = VT.getVectorNumElements();
21485 if (!Subtarget.hasVLX() && !VT.is512BitVector() &&
21486 !Index.getSimpleValueType().is512BitVector()) {
21487 // AVX512F supports only 512-bit vectors. Or data or index should
21488 // be 512 bit wide. If now the both index and data are 256-bit, but
21489 // the vector contains 8 elements, we just sign-extend the index
21490 if (IndexVT == MVT::v8i32)
21491 // Just extend index
21492 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
21494 // The minimal number of elts in scatter is 8
21497 MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
21498 // Use original index here, do not modify the index twice
21499 Index = ExtendToType(N->getIndex(), NewIndexVT, DAG);
21500 if (IndexVT.getScalarType() == MVT::i32)
21501 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
21504 // At this point we have promoted mask operand
21505 assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
21506 MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
21507 // Use the original mask here, do not modify the mask twice
21508 Mask = ExtendToType(N->getMask(), ExtMaskVT, DAG, true);
21510 // The value that should be stored
21511 MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
21512 Src = ExtendToType(Src, NewVT, DAG);
21515 // If the mask is "wide" at this point - truncate it to i1 vector
21516 MVT BitMaskVT = MVT::getVectorVT(MVT::i1, NumElts);
21517 Mask = DAG.getNode(ISD::TRUNCATE, dl, BitMaskVT, Mask);
21519 // The mask is killed by scatter, add it to the values
21520 SDVTList VTs = DAG.getVTList(BitMaskVT, MVT::Other);
21521 SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index};
21522 NewScatter = DAG.getMaskedScatter(VTs, N->getMemoryVT(), dl, Ops,
21523 N->getMemOperand());
21524 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
21525 return SDValue(NewScatter.getNode(), 1);
21528 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget &Subtarget,
21529 SelectionDAG &DAG) {
21531 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
21532 MVT VT = Op.getSimpleValueType();
21533 MVT ScalarVT = VT.getScalarType();
21534 SDValue Mask = N->getMask();
21537 assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
21538 "Cannot lower masked load op.");
21540 assert(((ScalarVT == MVT::i32 || ScalarVT == MVT::f32) ||
21541 (Subtarget.hasBWI() &&
21542 (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
21543 "Unsupported masked load op.");
21545 // This operation is legal for targets with VLX, but without
21546 // VLX the vector should be widened to 512 bit
21547 unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
21548 MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
21549 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
21550 SDValue Src0 = N->getSrc0();
21551 Src0 = ExtendToType(Src0, WideDataVT, DAG);
21552 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
21553 SDValue NewLoad = DAG.getMaskedLoad(WideDataVT, dl, N->getChain(),
21554 N->getBasePtr(), Mask, Src0,
21555 N->getMemoryVT(), N->getMemOperand(),
21556 N->getExtensionType());
21558 SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
21559 NewLoad.getValue(0),
21560 DAG.getIntPtrConstant(0, dl));
21561 SDValue RetOps[] = {Exract, NewLoad.getValue(1)};
21562 return DAG.getMergeValues(RetOps, dl);
21565 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget &Subtarget,
21566 SelectionDAG &DAG) {
21567 MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
21568 SDValue DataToStore = N->getValue();
21569 MVT VT = DataToStore.getSimpleValueType();
21570 MVT ScalarVT = VT.getScalarType();
21571 SDValue Mask = N->getMask();
21574 assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
21575 "Cannot lower masked store op.");
21577 assert(((ScalarVT == MVT::i32 || ScalarVT == MVT::f32) ||
21578 (Subtarget.hasBWI() &&
21579 (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
21580 "Unsupported masked store op.");
21582 // This operation is legal for targets with VLX, but without
21583 // VLX the vector should be widened to 512 bit
21584 unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
21585 MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
21586 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
21587 DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
21588 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
21589 return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
21590 Mask, N->getMemoryVT(), N->getMemOperand(),
21591 N->isTruncatingStore());
21594 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget &Subtarget,
21595 SelectionDAG &DAG) {
21596 assert(Subtarget.hasAVX512() &&
21597 "MGATHER/MSCATTER are supported on AVX-512 arch only");
21599 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
21601 MVT VT = Op.getSimpleValueType();
21602 SDValue Index = N->getIndex();
21603 SDValue Mask = N->getMask();
21604 SDValue Src0 = N->getValue();
21605 MVT IndexVT = Index.getSimpleValueType();
21606 MVT MaskVT = Mask.getSimpleValueType();
21608 unsigned NumElts = VT.getVectorNumElements();
21609 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
21611 if (!Subtarget.hasVLX() && !VT.is512BitVector() &&
21612 !Index.getSimpleValueType().is512BitVector()) {
21613 // AVX512F supports only 512-bit vectors. Or data or index should
21614 // be 512 bit wide. If now the both index and data are 256-bit, but
21615 // the vector contains 8 elements, we just sign-extend the index
21616 if (NumElts == 8) {
21617 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
21618 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
21619 N->getOperand(3), Index };
21620 DAG.UpdateNodeOperands(N, Ops);
21624 // Minimal number of elements in Gather
21627 MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
21628 Index = ExtendToType(Index, NewIndexVT, DAG);
21629 if (IndexVT.getScalarType() == MVT::i32)
21630 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
21633 MVT MaskBitVT = MVT::getVectorVT(MVT::i1, NumElts);
21634 // At this point we have promoted mask operand
21635 assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
21636 MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
21637 Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
21638 Mask = DAG.getNode(ISD::TRUNCATE, dl, MaskBitVT, Mask);
21640 // The pass-thru value
21641 MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
21642 Src0 = ExtendToType(Src0, NewVT, DAG);
21644 SDValue Ops[] = { N->getChain(), Src0, Mask, N->getBasePtr(), Index };
21645 SDValue NewGather = DAG.getMaskedGather(DAG.getVTList(NewVT, MVT::Other),
21646 N->getMemoryVT(), dl, Ops,
21647 N->getMemOperand());
21648 SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
21649 NewGather.getValue(0),
21650 DAG.getIntPtrConstant(0, dl));
21651 SDValue RetOps[] = {Exract, NewGather.getValue(1)};
21652 return DAG.getMergeValues(RetOps, dl);
21657 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
21658 SelectionDAG &DAG) const {
21659 // TODO: Eventually, the lowering of these nodes should be informed by or
21660 // deferred to the GC strategy for the function in which they appear. For
21661 // now, however, they must be lowered to something. Since they are logically
21662 // no-ops in the case of a null GC strategy (or a GC strategy which does not
21663 // require special handling for these nodes), lower them as literal NOOPs for
21665 SmallVector<SDValue, 2> Ops;
21667 Ops.push_back(Op.getOperand(0));
21668 if (Op->getGluedNode())
21669 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
21672 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
21673 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
21678 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
21679 SelectionDAG &DAG) const {
21680 // TODO: Eventually, the lowering of these nodes should be informed by or
21681 // deferred to the GC strategy for the function in which they appear. For
21682 // now, however, they must be lowered to something. Since they are logically
21683 // no-ops in the case of a null GC strategy (or a GC strategy which does not
21684 // require special handling for these nodes), lower them as literal NOOPs for
21686 SmallVector<SDValue, 2> Ops;
21688 Ops.push_back(Op.getOperand(0));
21689 if (Op->getGluedNode())
21690 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
21693 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
21694 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
21699 /// Provide custom lowering hooks for some operations.
21700 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
21701 switch (Op.getOpcode()) {
21702 default: llvm_unreachable("Should not custom lower this!");
21703 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
21704 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
21705 return LowerCMP_SWAP(Op, Subtarget, DAG);
21706 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
21707 case ISD::ATOMIC_LOAD_ADD:
21708 case ISD::ATOMIC_LOAD_SUB:
21709 case ISD::ATOMIC_LOAD_OR:
21710 case ISD::ATOMIC_LOAD_XOR:
21711 case ISD::ATOMIC_LOAD_AND: return lowerAtomicArith(Op, DAG, Subtarget);
21712 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op, DAG);
21713 case ISD::BITREVERSE: return LowerBITREVERSE(Op, Subtarget, DAG);
21714 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
21715 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
21716 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
21717 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
21718 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
21719 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
21720 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
21721 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
21722 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
21723 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
21724 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
21725 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
21726 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
21727 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
21728 case ISD::SHL_PARTS:
21729 case ISD::SRA_PARTS:
21730 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
21731 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
21732 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
21733 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
21734 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
21735 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
21736 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
21737 case ISD::SIGN_EXTEND_VECTOR_INREG:
21738 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
21739 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
21740 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
21741 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
21742 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
21744 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
21745 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
21746 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
21747 case ISD::SETCC: return LowerSETCC(Op, DAG);
21748 case ISD::SETCCE: return LowerSETCCE(Op, DAG);
21749 case ISD::SELECT: return LowerSELECT(Op, DAG);
21750 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
21751 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
21752 case ISD::VASTART: return LowerVASTART(Op, DAG);
21753 case ISD::VAARG: return LowerVAARG(Op, DAG);
21754 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
21755 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
21756 case ISD::INTRINSIC_VOID:
21757 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
21758 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
21759 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
21760 case ISD::FRAME_TO_ARGS_OFFSET:
21761 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
21762 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
21763 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
21764 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
21765 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
21766 case ISD::EH_SJLJ_SETUP_DISPATCH:
21767 return lowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
21768 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
21769 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
21770 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
21772 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ(Op, Subtarget, DAG);
21774 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op, DAG);
21775 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
21777 case ISD::MULHU: return LowerMULH(Op, Subtarget, DAG);
21778 case ISD::UMUL_LOHI:
21779 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
21780 case ISD::ROTL: return LowerRotate(Op, Subtarget, DAG);
21783 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
21789 case ISD::UMULO: return LowerXALUO(Op, DAG);
21790 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
21791 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
21795 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
21796 case ISD::ADD: return LowerADD(Op, DAG);
21797 case ISD::SUB: return LowerSUB(Op, DAG);
21801 case ISD::UMIN: return LowerMINMAX(Op, DAG);
21802 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
21803 case ISD::MLOAD: return LowerMLOAD(Op, Subtarget, DAG);
21804 case ISD::MSTORE: return LowerMSTORE(Op, Subtarget, DAG);
21805 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
21806 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
21807 case ISD::GC_TRANSITION_START:
21808 return LowerGC_TRANSITION_START(Op, DAG);
21809 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
21810 case ISD::STORE: return LowerTruncatingStore(Op, Subtarget, DAG);
21814 /// Places new result values for the node in Results (their number
21815 /// and types must exactly match those of the original return values of
21816 /// the node), or leaves Results empty, which indicates that the node is not
21817 /// to be custom lowered after all.
21818 void X86TargetLowering::LowerOperationWrapper(SDNode *N,
21819 SmallVectorImpl<SDValue> &Results,
21820 SelectionDAG &DAG) const {
21821 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
21823 if (!Res.getNode())
21826 assert((N->getNumValues() <= Res->getNumValues()) &&
21827 "Lowering returned the wrong number of results!");
21829 // Places new result values base on N result number.
21830 // In some cases (LowerSINT_TO_FP for example) Res has more result values
21831 // than original node, chain should be dropped(last value).
21832 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
21833 Results.push_back(Res.getValue(I));
21836 /// Replace a node with an illegal result type with a new node built out of
21838 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
21839 SmallVectorImpl<SDValue>&Results,
21840 SelectionDAG &DAG) const {
21842 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21843 switch (N->getOpcode()) {
21845 llvm_unreachable("Do not know how to custom type legalize this operation!");
21846 case X86ISD::AVG: {
21847 // Legalize types for X86ISD::AVG by expanding vectors.
21848 assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
21850 auto InVT = N->getValueType(0);
21851 auto InVTSize = InVT.getSizeInBits();
21852 const unsigned RegSize =
21853 (InVTSize > 128) ? ((InVTSize > 256) ? 512 : 256) : 128;
21854 assert((!Subtarget.hasAVX512() || RegSize < 512) &&
21855 "512-bit vector requires AVX512");
21856 assert((!Subtarget.hasAVX2() || RegSize < 256) &&
21857 "256-bit vector requires AVX2");
21859 auto ElemVT = InVT.getVectorElementType();
21860 auto RegVT = EVT::getVectorVT(*DAG.getContext(), ElemVT,
21861 RegSize / ElemVT.getSizeInBits());
21862 assert(RegSize % InVT.getSizeInBits() == 0);
21863 unsigned NumConcat = RegSize / InVT.getSizeInBits();
21865 SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
21866 Ops[0] = N->getOperand(0);
21867 SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
21868 Ops[0] = N->getOperand(1);
21869 SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
21871 SDValue Res = DAG.getNode(X86ISD::AVG, dl, RegVT, InVec0, InVec1);
21872 Results.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InVT, Res,
21873 DAG.getIntPtrConstant(0, dl)));
21876 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
21877 case X86ISD::FMINC:
21879 case X86ISD::FMAXC:
21880 case X86ISD::FMAX: {
21881 EVT VT = N->getValueType(0);
21882 assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
21883 SDValue UNDEF = DAG.getUNDEF(VT);
21884 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
21885 N->getOperand(0), UNDEF);
21886 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
21887 N->getOperand(1), UNDEF);
21888 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
21891 case ISD::SIGN_EXTEND_INREG:
21896 // We don't want to expand or promote these.
21903 case ISD::UDIVREM: {
21904 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
21905 Results.push_back(V);
21908 case ISD::FP_TO_SINT:
21909 case ISD::FP_TO_UINT: {
21910 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
21912 std::pair<SDValue,SDValue> Vals =
21913 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
21914 SDValue FIST = Vals.first, StackSlot = Vals.second;
21915 if (FIST.getNode()) {
21916 EVT VT = N->getValueType(0);
21917 // Return a load from the stack slot.
21918 if (StackSlot.getNode())
21920 DAG.getLoad(VT, dl, FIST, StackSlot, MachinePointerInfo()));
21922 Results.push_back(FIST);
21926 case ISD::UINT_TO_FP: {
21927 assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
21928 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
21929 N->getValueType(0) != MVT::v2f32)
21931 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
21934 DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl, MVT::v2f64);
21935 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
21936 DAG.getBitcast(MVT::v2i64, VBias));
21937 Or = DAG.getBitcast(MVT::v2f64, Or);
21938 // TODO: Are there any fast-math-flags to propagate here?
21939 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
21940 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
21943 case ISD::FP_ROUND: {
21944 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
21946 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
21947 Results.push_back(V);
21950 case ISD::FP_EXTEND: {
21951 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
21952 // No other ValueType for FP_EXTEND should reach this point.
21953 assert(N->getValueType(0) == MVT::v2f32 &&
21954 "Do not know how to legalize this Node");
21957 case ISD::INTRINSIC_W_CHAIN: {
21958 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21960 default : llvm_unreachable("Do not know how to custom type "
21961 "legalize this intrinsic operation!");
21962 case Intrinsic::x86_rdtsc:
21963 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
21965 case Intrinsic::x86_rdtscp:
21966 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
21968 case Intrinsic::x86_rdpmc:
21969 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
21972 case ISD::INTRINSIC_WO_CHAIN: {
21973 if (SDValue V = LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), Subtarget, DAG))
21974 Results.push_back(V);
21977 case ISD::READCYCLECOUNTER: {
21978 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
21981 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
21982 EVT T = N->getValueType(0);
21983 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
21984 bool Regs64bit = T == MVT::i128;
21985 MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
21986 SDValue cpInL, cpInH;
21987 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
21988 DAG.getConstant(0, dl, HalfT));
21989 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
21990 DAG.getConstant(1, dl, HalfT));
21991 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
21992 Regs64bit ? X86::RAX : X86::EAX,
21994 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
21995 Regs64bit ? X86::RDX : X86::EDX,
21996 cpInH, cpInL.getValue(1));
21997 SDValue swapInL, swapInH;
21998 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
21999 DAG.getConstant(0, dl, HalfT));
22000 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
22001 DAG.getConstant(1, dl, HalfT));
22003 DAG.getCopyToReg(cpInH.getValue(0), dl, Regs64bit ? X86::RCX : X86::ECX,
22004 swapInH, cpInH.getValue(1));
22005 // If the current function needs the base pointer, RBX,
22006 // we shouldn't use cmpxchg directly.
22007 // Indeed the lowering of that instruction will clobber
22008 // that register and since RBX will be a reserved register
22009 // the register allocator will not make sure its value will
22010 // be properly saved and restored around this live-range.
22011 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
22013 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
22014 unsigned BasePtr = TRI->getBaseRegister();
22015 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
22016 if (TRI->hasBasePointer(DAG.getMachineFunction()) &&
22017 (BasePtr == X86::RBX || BasePtr == X86::EBX)) {
22018 // ISel prefers the LCMPXCHG64 variant.
22019 // If that assert breaks, that means it is not the case anymore,
22020 // and we need to teach LCMPXCHG8_SAVE_EBX_DAG how to save RBX,
22021 // not just EBX. This is a matter of accepting i64 input for that
22022 // pseudo, and restoring into the register of the right wide
22023 // in expand pseudo. Everything else should just work.
22024 assert(((Regs64bit == (BasePtr == X86::RBX)) || BasePtr == X86::EBX) &&
22025 "Saving only half of the RBX");
22026 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_SAVE_RBX_DAG
22027 : X86ISD::LCMPXCHG8_SAVE_EBX_DAG;
22028 SDValue RBXSave = DAG.getCopyFromReg(swapInH.getValue(0), dl,
22029 Regs64bit ? X86::RBX : X86::EBX,
22030 HalfT, swapInH.getValue(1));
22031 SDValue Ops[] = {/*Chain*/ RBXSave.getValue(1), N->getOperand(1), swapInL,
22033 /*Glue*/ RBXSave.getValue(2)};
22034 Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
22037 Regs64bit ? X86ISD::LCMPXCHG16_DAG : X86ISD::LCMPXCHG8_DAG;
22038 swapInL = DAG.getCopyToReg(swapInH.getValue(0), dl,
22039 Regs64bit ? X86::RBX : X86::EBX, swapInL,
22040 swapInH.getValue(1));
22041 SDValue Ops[] = {swapInL.getValue(0), N->getOperand(1),
22042 swapInL.getValue(1)};
22043 Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
22045 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
22046 Regs64bit ? X86::RAX : X86::EAX,
22047 HalfT, Result.getValue(1));
22048 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
22049 Regs64bit ? X86::RDX : X86::EDX,
22050 HalfT, cpOutL.getValue(2));
22051 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
22053 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
22054 MVT::i32, cpOutH.getValue(2));
22056 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
22057 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
22058 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
22060 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
22061 Results.push_back(Success);
22062 Results.push_back(EFLAGS.getValue(1));
22065 case ISD::ATOMIC_SWAP:
22066 case ISD::ATOMIC_LOAD_ADD:
22067 case ISD::ATOMIC_LOAD_SUB:
22068 case ISD::ATOMIC_LOAD_AND:
22069 case ISD::ATOMIC_LOAD_OR:
22070 case ISD::ATOMIC_LOAD_XOR:
22071 case ISD::ATOMIC_LOAD_NAND:
22072 case ISD::ATOMIC_LOAD_MIN:
22073 case ISD::ATOMIC_LOAD_MAX:
22074 case ISD::ATOMIC_LOAD_UMIN:
22075 case ISD::ATOMIC_LOAD_UMAX:
22076 case ISD::ATOMIC_LOAD: {
22077 // Delegate to generic TypeLegalization. Situations we can really handle
22078 // should have already been dealt with by AtomicExpandPass.cpp.
22081 case ISD::BITCAST: {
22082 assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
22083 EVT DstVT = N->getValueType(0);
22084 EVT SrcVT = N->getOperand(0)->getValueType(0);
22086 if (SrcVT != MVT::f64 ||
22087 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
22090 unsigned NumElts = DstVT.getVectorNumElements();
22091 EVT SVT = DstVT.getVectorElementType();
22092 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
22093 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
22094 MVT::v2f64, N->getOperand(0));
22095 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
22097 if (ExperimentalVectorWideningLegalization) {
22098 // If we are legalizing vectors by widening, we already have the desired
22099 // legal vector type, just return it.
22100 Results.push_back(ToVecInt);
22104 SmallVector<SDValue, 8> Elts;
22105 for (unsigned i = 0, e = NumElts; i != e; ++i)
22106 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
22107 ToVecInt, DAG.getIntPtrConstant(i, dl)));
22109 Results.push_back(DAG.getBuildVector(DstVT, dl, Elts));
22114 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
22115 switch ((X86ISD::NodeType)Opcode) {
22116 case X86ISD::FIRST_NUMBER: break;
22117 case X86ISD::BSF: return "X86ISD::BSF";
22118 case X86ISD::BSR: return "X86ISD::BSR";
22119 case X86ISD::SHLD: return "X86ISD::SHLD";
22120 case X86ISD::SHRD: return "X86ISD::SHRD";
22121 case X86ISD::FAND: return "X86ISD::FAND";
22122 case X86ISD::FANDN: return "X86ISD::FANDN";
22123 case X86ISD::FOR: return "X86ISD::FOR";
22124 case X86ISD::FXOR: return "X86ISD::FXOR";
22125 case X86ISD::FILD: return "X86ISD::FILD";
22126 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
22127 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
22128 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
22129 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
22130 case X86ISD::FLD: return "X86ISD::FLD";
22131 case X86ISD::FST: return "X86ISD::FST";
22132 case X86ISD::CALL: return "X86ISD::CALL";
22133 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
22134 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
22135 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
22136 case X86ISD::BT: return "X86ISD::BT";
22137 case X86ISD::CMP: return "X86ISD::CMP";
22138 case X86ISD::COMI: return "X86ISD::COMI";
22139 case X86ISD::UCOMI: return "X86ISD::UCOMI";
22140 case X86ISD::CMPM: return "X86ISD::CMPM";
22141 case X86ISD::CMPMU: return "X86ISD::CMPMU";
22142 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
22143 case X86ISD::SETCC: return "X86ISD::SETCC";
22144 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
22145 case X86ISD::FSETCC: return "X86ISD::FSETCC";
22146 case X86ISD::CMOV: return "X86ISD::CMOV";
22147 case X86ISD::BRCOND: return "X86ISD::BRCOND";
22148 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
22149 case X86ISD::IRET: return "X86ISD::IRET";
22150 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
22151 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
22152 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
22153 case X86ISD::Wrapper: return "X86ISD::Wrapper";
22154 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
22155 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
22156 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
22157 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
22158 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
22159 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
22160 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
22161 case X86ISD::PINSRB: return "X86ISD::PINSRB";
22162 case X86ISD::PINSRW: return "X86ISD::PINSRW";
22163 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
22164 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
22165 case X86ISD::ANDNP: return "X86ISD::ANDNP";
22166 case X86ISD::BLENDI: return "X86ISD::BLENDI";
22167 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
22168 case X86ISD::ADDUS: return "X86ISD::ADDUS";
22169 case X86ISD::SUBUS: return "X86ISD::SUBUS";
22170 case X86ISD::HADD: return "X86ISD::HADD";
22171 case X86ISD::HSUB: return "X86ISD::HSUB";
22172 case X86ISD::FHADD: return "X86ISD::FHADD";
22173 case X86ISD::FHSUB: return "X86ISD::FHSUB";
22174 case X86ISD::ABS: return "X86ISD::ABS";
22175 case X86ISD::CONFLICT: return "X86ISD::CONFLICT";
22176 case X86ISD::FMAX: return "X86ISD::FMAX";
22177 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
22178 case X86ISD::FMIN: return "X86ISD::FMIN";
22179 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
22180 case X86ISD::FMAXC: return "X86ISD::FMAXC";
22181 case X86ISD::FMINC: return "X86ISD::FMINC";
22182 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
22183 case X86ISD::FRSQRTS: return "X86ISD::FRSQRTS";
22184 case X86ISD::FRCP: return "X86ISD::FRCP";
22185 case X86ISD::FRCPS: return "X86ISD::FRCPS";
22186 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
22187 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
22188 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
22189 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
22190 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
22191 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
22192 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
22193 case X86ISD::EH_SJLJ_SETUP_DISPATCH:
22194 return "X86ISD::EH_SJLJ_SETUP_DISPATCH";
22195 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
22196 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
22197 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
22198 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
22199 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
22200 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
22201 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
22202 case X86ISD::LCMPXCHG8_SAVE_EBX_DAG:
22203 return "X86ISD::LCMPXCHG8_SAVE_EBX_DAG";
22204 case X86ISD::LCMPXCHG16_SAVE_RBX_DAG:
22205 return "X86ISD::LCMPXCHG16_SAVE_RBX_DAG";
22206 case X86ISD::LADD: return "X86ISD::LADD";
22207 case X86ISD::LSUB: return "X86ISD::LSUB";
22208 case X86ISD::LOR: return "X86ISD::LOR";
22209 case X86ISD::LXOR: return "X86ISD::LXOR";
22210 case X86ISD::LAND: return "X86ISD::LAND";
22211 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
22212 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
22213 case X86ISD::VZEXT: return "X86ISD::VZEXT";
22214 case X86ISD::VSEXT: return "X86ISD::VSEXT";
22215 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
22216 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
22217 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
22218 case X86ISD::VINSERT: return "X86ISD::VINSERT";
22219 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
22220 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
22221 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
22222 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
22223 case X86ISD::CVT2MASK: return "X86ISD::CVT2MASK";
22224 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
22225 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
22226 case X86ISD::VSHL: return "X86ISD::VSHL";
22227 case X86ISD::VSRL: return "X86ISD::VSRL";
22228 case X86ISD::VSRA: return "X86ISD::VSRA";
22229 case X86ISD::VSHLI: return "X86ISD::VSHLI";
22230 case X86ISD::VSRLI: return "X86ISD::VSRLI";
22231 case X86ISD::VSRAI: return "X86ISD::VSRAI";
22232 case X86ISD::VSRAV: return "X86ISD::VSRAV";
22233 case X86ISD::VROTLI: return "X86ISD::VROTLI";
22234 case X86ISD::VROTRI: return "X86ISD::VROTRI";
22235 case X86ISD::VPPERM: return "X86ISD::VPPERM";
22236 case X86ISD::CMPP: return "X86ISD::CMPP";
22237 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
22238 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
22239 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
22240 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
22241 case X86ISD::ADD: return "X86ISD::ADD";
22242 case X86ISD::SUB: return "X86ISD::SUB";
22243 case X86ISD::ADC: return "X86ISD::ADC";
22244 case X86ISD::SBB: return "X86ISD::SBB";
22245 case X86ISD::SMUL: return "X86ISD::SMUL";
22246 case X86ISD::UMUL: return "X86ISD::UMUL";
22247 case X86ISD::SMUL8: return "X86ISD::SMUL8";
22248 case X86ISD::UMUL8: return "X86ISD::UMUL8";
22249 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
22250 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
22251 case X86ISD::INC: return "X86ISD::INC";
22252 case X86ISD::DEC: return "X86ISD::DEC";
22253 case X86ISD::OR: return "X86ISD::OR";
22254 case X86ISD::XOR: return "X86ISD::XOR";
22255 case X86ISD::AND: return "X86ISD::AND";
22256 case X86ISD::BEXTR: return "X86ISD::BEXTR";
22257 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
22258 case X86ISD::MOVMSK: return "X86ISD::MOVMSK";
22259 case X86ISD::PTEST: return "X86ISD::PTEST";
22260 case X86ISD::TESTP: return "X86ISD::TESTP";
22261 case X86ISD::TESTM: return "X86ISD::TESTM";
22262 case X86ISD::TESTNM: return "X86ISD::TESTNM";
22263 case X86ISD::KORTEST: return "X86ISD::KORTEST";
22264 case X86ISD::KTEST: return "X86ISD::KTEST";
22265 case X86ISD::PACKSS: return "X86ISD::PACKSS";
22266 case X86ISD::PACKUS: return "X86ISD::PACKUS";
22267 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
22268 case X86ISD::VALIGN: return "X86ISD::VALIGN";
22269 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
22270 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
22271 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
22272 case X86ISD::SHUFP: return "X86ISD::SHUFP";
22273 case X86ISD::SHUF128: return "X86ISD::SHUF128";
22274 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
22275 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
22276 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
22277 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
22278 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
22279 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
22280 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
22281 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
22282 case X86ISD::MOVSD: return "X86ISD::MOVSD";
22283 case X86ISD::MOVSS: return "X86ISD::MOVSS";
22284 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
22285 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
22286 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
22287 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
22288 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
22289 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
22290 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
22291 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
22292 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
22293 case X86ISD::VPERMV: return "X86ISD::VPERMV";
22294 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
22295 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
22296 case X86ISD::VPERMI: return "X86ISD::VPERMI";
22297 case X86ISD::VPTERNLOG: return "X86ISD::VPTERNLOG";
22298 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
22299 case X86ISD::VFIXUPIMMS: return "X86ISD::VFIXUPIMMS";
22300 case X86ISD::VRANGE: return "X86ISD::VRANGE";
22301 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
22302 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
22303 case X86ISD::PSADBW: return "X86ISD::PSADBW";
22304 case X86ISD::DBPSADBW: return "X86ISD::DBPSADBW";
22305 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
22306 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
22307 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
22308 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
22309 case X86ISD::MFENCE: return "X86ISD::MFENCE";
22310 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
22311 case X86ISD::SAHF: return "X86ISD::SAHF";
22312 case X86ISD::RDRAND: return "X86ISD::RDRAND";
22313 case X86ISD::RDSEED: return "X86ISD::RDSEED";
22314 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
22315 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
22316 case X86ISD::VPROT: return "X86ISD::VPROT";
22317 case X86ISD::VPROTI: return "X86ISD::VPROTI";
22318 case X86ISD::VPSHA: return "X86ISD::VPSHA";
22319 case X86ISD::VPSHL: return "X86ISD::VPSHL";
22320 case X86ISD::VPCOM: return "X86ISD::VPCOM";
22321 case X86ISD::VPCOMU: return "X86ISD::VPCOMU";
22322 case X86ISD::VPERMIL2: return "X86ISD::VPERMIL2";
22323 case X86ISD::FMADD: return "X86ISD::FMADD";
22324 case X86ISD::FMSUB: return "X86ISD::FMSUB";
22325 case X86ISD::FNMADD: return "X86ISD::FNMADD";
22326 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
22327 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
22328 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
22329 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
22330 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
22331 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
22332 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
22333 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
22334 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
22335 case X86ISD::VPMADD52H: return "X86ISD::VPMADD52H";
22336 case X86ISD::VPMADD52L: return "X86ISD::VPMADD52L";
22337 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
22338 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
22339 case X86ISD::VGETMANT: return "X86ISD::VGETMANT";
22340 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
22341 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
22342 case X86ISD::XTEST: return "X86ISD::XTEST";
22343 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
22344 case X86ISD::EXPAND: return "X86ISD::EXPAND";
22345 case X86ISD::SELECT: return "X86ISD::SELECT";
22346 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
22347 case X86ISD::RCP28: return "X86ISD::RCP28";
22348 case X86ISD::EXP2: return "X86ISD::EXP2";
22349 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
22350 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
22351 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
22352 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
22353 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
22354 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
22355 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
22356 case X86ISD::SCALEF: return "X86ISD::SCALEF";
22357 case X86ISD::SCALEFS: return "X86ISD::SCALEFS";
22358 case X86ISD::ADDS: return "X86ISD::ADDS";
22359 case X86ISD::SUBS: return "X86ISD::SUBS";
22360 case X86ISD::AVG: return "X86ISD::AVG";
22361 case X86ISD::MULHRS: return "X86ISD::MULHRS";
22362 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
22363 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
22364 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
22365 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
22366 case X86ISD::VFPCLASS: return "X86ISD::VFPCLASS";
22367 case X86ISD::VFPCLASSS: return "X86ISD::VFPCLASSS";
22368 case X86ISD::MULTISHIFT: return "X86ISD::MULTISHIFT";
22369 case X86ISD::SCALAR_FP_TO_SINT_RND: return "X86ISD::SCALAR_FP_TO_SINT_RND";
22370 case X86ISD::SCALAR_FP_TO_UINT_RND: return "X86ISD::SCALAR_FP_TO_UINT_RND";
22375 /// Return true if the addressing mode represented by AM is legal for this
22376 /// target, for a load/store of the specified type.
22377 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
22378 const AddrMode &AM, Type *Ty,
22379 unsigned AS) const {
22380 // X86 supports extremely general addressing modes.
22381 CodeModel::Model M = getTargetMachine().getCodeModel();
22383 // X86 allows a sign-extended 32-bit immediate field as a displacement.
22384 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
22388 unsigned GVFlags = Subtarget.classifyGlobalReference(AM.BaseGV);
22390 // If a reference to this global requires an extra load, we can't fold it.
22391 if (isGlobalStubReference(GVFlags))
22394 // If BaseGV requires a register for the PIC base, we cannot also have a
22395 // BaseReg specified.
22396 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
22399 // If lower 4G is not available, then we must use rip-relative addressing.
22400 if ((M != CodeModel::Small || isPositionIndependent()) &&
22401 Subtarget.is64Bit() && (AM.BaseOffs || AM.Scale > 1))
22405 switch (AM.Scale) {
22411 // These scales always work.
22416 // These scales are formed with basereg+scalereg. Only accept if there is
22421 default: // Other stuff never works.
22428 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
22429 unsigned Bits = Ty->getScalarSizeInBits();
22431 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
22432 // particularly cheaper than those without.
22436 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
22437 // variable shifts just as cheap as scalar ones.
22438 if (Subtarget.hasInt256() && (Bits == 32 || Bits == 64))
22441 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
22442 // fully general vector.
22446 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
22447 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
22449 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
22450 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
22451 return NumBits1 > NumBits2;
22454 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
22455 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
22458 if (!isTypeLegal(EVT::getEVT(Ty1)))
22461 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
22463 // Assuming the caller doesn't have a zeroext or signext return parameter,
22464 // truncation all the way down to i1 is valid.
22468 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
22469 return isInt<32>(Imm);
22472 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
22473 // Can also use sub to handle negated immediates.
22474 return isInt<32>(Imm);
22477 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
22478 if (!VT1.isInteger() || !VT2.isInteger())
22480 unsigned NumBits1 = VT1.getSizeInBits();
22481 unsigned NumBits2 = VT2.getSizeInBits();
22482 return NumBits1 > NumBits2;
22485 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
22486 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
22487 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget.is64Bit();
22490 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
22491 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
22492 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget.is64Bit();
22495 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
22496 EVT VT1 = Val.getValueType();
22497 if (isZExtFree(VT1, VT2))
22500 if (Val.getOpcode() != ISD::LOAD)
22503 if (!VT1.isSimple() || !VT1.isInteger() ||
22504 !VT2.isSimple() || !VT2.isInteger())
22507 switch (VT1.getSimpleVT().SimpleTy) {
22512 // X86 has 8, 16, and 32-bit zero-extending loads.
22519 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
22522 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
22523 if (!Subtarget.hasAnyFMA())
22526 VT = VT.getScalarType();
22528 if (!VT.isSimple())
22531 switch (VT.getSimpleVT().SimpleTy) {
22542 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
22543 // i16 instructions are longer (0x66 prefix) and potentially slower.
22544 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
22547 /// Targets can use this to indicate that they only support *some*
22548 /// VECTOR_SHUFFLE operations, those with specific masks.
22549 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
22550 /// are assumed to be legal.
22552 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
22554 if (!VT.isSimple())
22557 // Not for i1 vectors
22558 if (VT.getSimpleVT().getScalarType() == MVT::i1)
22561 // Very little shuffling can be done for 64-bit vectors right now.
22562 if (VT.getSimpleVT().getSizeInBits() == 64)
22565 // We only care that the types being shuffled are legal. The lowering can
22566 // handle any possible shuffle mask that results.
22567 return isTypeLegal(VT.getSimpleVT());
22571 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
22573 // Just delegate to the generic legality, clear masks aren't special.
22574 return isShuffleMaskLegal(Mask, VT);
22577 //===----------------------------------------------------------------------===//
22578 // X86 Scheduler Hooks
22579 //===----------------------------------------------------------------------===//
22581 /// Utility function to emit xbegin specifying the start of an RTM region.
22582 static MachineBasicBlock *emitXBegin(MachineInstr &MI, MachineBasicBlock *MBB,
22583 const TargetInstrInfo *TII) {
22584 DebugLoc DL = MI.getDebugLoc();
22586 const BasicBlock *BB = MBB->getBasicBlock();
22587 MachineFunction::iterator I = ++MBB->getIterator();
22589 // For the v = xbegin(), we generate
22600 MachineBasicBlock *thisMBB = MBB;
22601 MachineFunction *MF = MBB->getParent();
22602 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
22603 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
22604 MF->insert(I, mainMBB);
22605 MF->insert(I, sinkMBB);
22607 // Transfer the remainder of BB and its successor edges to sinkMBB.
22608 sinkMBB->splice(sinkMBB->begin(), MBB,
22609 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
22610 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
22614 // # fallthrough to mainMBB
22615 // # abortion to sinkMBB
22616 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
22617 thisMBB->addSuccessor(mainMBB);
22618 thisMBB->addSuccessor(sinkMBB);
22622 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
22623 mainMBB->addSuccessor(sinkMBB);
22626 // EAX is live into the sinkMBB
22627 sinkMBB->addLiveIn(X86::EAX);
22628 BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(TargetOpcode::COPY),
22629 MI.getOperand(0).getReg())
22632 MI.eraseFromParent();
22636 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
22637 // or XMM0_V32I8 in AVX all of this code can be replaced with that
22638 // in the .td file.
22639 static MachineBasicBlock *emitPCMPSTRM(MachineInstr &MI, MachineBasicBlock *BB,
22640 const TargetInstrInfo *TII) {
22642 switch (MI.getOpcode()) {
22643 default: llvm_unreachable("illegal opcode!");
22644 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
22645 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
22646 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
22647 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
22648 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
22649 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
22650 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
22651 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
22654 DebugLoc dl = MI.getDebugLoc();
22655 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
22657 unsigned NumArgs = MI.getNumOperands();
22658 for (unsigned i = 1; i < NumArgs; ++i) {
22659 MachineOperand &Op = MI.getOperand(i);
22660 if (!(Op.isReg() && Op.isImplicit()))
22661 MIB.addOperand(Op);
22663 if (MI.hasOneMemOperand())
22664 MIB->setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
22666 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), MI.getOperand(0).getReg())
22667 .addReg(X86::XMM0);
22669 MI.eraseFromParent();
22673 // FIXME: Custom handling because TableGen doesn't support multiple implicit
22674 // defs in an instruction pattern
22675 static MachineBasicBlock *emitPCMPSTRI(MachineInstr &MI, MachineBasicBlock *BB,
22676 const TargetInstrInfo *TII) {
22678 switch (MI.getOpcode()) {
22679 default: llvm_unreachable("illegal opcode!");
22680 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
22681 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
22682 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
22683 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
22684 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
22685 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
22686 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
22687 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
22690 DebugLoc dl = MI.getDebugLoc();
22691 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
22693 unsigned NumArgs = MI.getNumOperands(); // remove the results
22694 for (unsigned i = 1; i < NumArgs; ++i) {
22695 MachineOperand &Op = MI.getOperand(i);
22696 if (!(Op.isReg() && Op.isImplicit()))
22697 MIB.addOperand(Op);
22699 if (MI.hasOneMemOperand())
22700 MIB->setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
22702 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), MI.getOperand(0).getReg())
22705 MI.eraseFromParent();
22709 static MachineBasicBlock *emitWRPKRU(MachineInstr &MI, MachineBasicBlock *BB,
22710 const X86Subtarget &Subtarget) {
22711 DebugLoc dl = MI.getDebugLoc();
22712 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
22714 // insert input VAL into EAX
22715 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
22716 .addReg(MI.getOperand(0).getReg());
22717 // insert zero to ECX
22718 BuildMI(*BB, MI, dl, TII->get(X86::MOV32r0), X86::ECX);
22720 // insert zero to EDX
22721 BuildMI(*BB, MI, dl, TII->get(X86::MOV32r0), X86::EDX);
22723 // insert WRPKRU instruction
22724 BuildMI(*BB, MI, dl, TII->get(X86::WRPKRUr));
22726 MI.eraseFromParent(); // The pseudo is gone now.
22730 static MachineBasicBlock *emitRDPKRU(MachineInstr &MI, MachineBasicBlock *BB,
22731 const X86Subtarget &Subtarget) {
22732 DebugLoc dl = MI.getDebugLoc();
22733 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
22735 // insert zero to ECX
22736 BuildMI(*BB, MI, dl, TII->get(X86::MOV32r0), X86::ECX);
22738 // insert RDPKRU instruction
22739 BuildMI(*BB, MI, dl, TII->get(X86::RDPKRUr));
22740 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), MI.getOperand(0).getReg())
22743 MI.eraseFromParent(); // The pseudo is gone now.
22747 static MachineBasicBlock *emitMonitor(MachineInstr &MI, MachineBasicBlock *BB,
22748 const X86Subtarget &Subtarget,
22750 DebugLoc dl = MI.getDebugLoc();
22751 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
22752 // Address into RAX/EAX, other two args into ECX, EDX.
22753 unsigned MemOpc = Subtarget.is64Bit() ? X86::LEA64r : X86::LEA32r;
22754 unsigned MemReg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
22755 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
22756 for (int i = 0; i < X86::AddrNumOperands; ++i)
22757 MIB.addOperand(MI.getOperand(i));
22759 unsigned ValOps = X86::AddrNumOperands;
22760 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
22761 .addReg(MI.getOperand(ValOps).getReg());
22762 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
22763 .addReg(MI.getOperand(ValOps + 1).getReg());
22765 // The instruction doesn't actually take any operands though.
22766 BuildMI(*BB, MI, dl, TII->get(Opc));
22768 MI.eraseFromParent(); // The pseudo is gone now.
22772 MachineBasicBlock *
22773 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr &MI,
22774 MachineBasicBlock *MBB) const {
22775 // Emit va_arg instruction on X86-64.
22777 // Operands to this pseudo-instruction:
22778 // 0 ) Output : destination address (reg)
22779 // 1-5) Input : va_list address (addr, i64mem)
22780 // 6 ) ArgSize : Size (in bytes) of vararg type
22781 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
22782 // 8 ) Align : Alignment of type
22783 // 9 ) EFLAGS (implicit-def)
22785 assert(MI.getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
22786 static_assert(X86::AddrNumOperands == 5,
22787 "VAARG_64 assumes 5 address operands");
22789 unsigned DestReg = MI.getOperand(0).getReg();
22790 MachineOperand &Base = MI.getOperand(1);
22791 MachineOperand &Scale = MI.getOperand(2);
22792 MachineOperand &Index = MI.getOperand(3);
22793 MachineOperand &Disp = MI.getOperand(4);
22794 MachineOperand &Segment = MI.getOperand(5);
22795 unsigned ArgSize = MI.getOperand(6).getImm();
22796 unsigned ArgMode = MI.getOperand(7).getImm();
22797 unsigned Align = MI.getOperand(8).getImm();
22799 // Memory Reference
22800 assert(MI.hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
22801 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
22802 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
22804 // Machine Information
22805 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
22806 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
22807 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
22808 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
22809 DebugLoc DL = MI.getDebugLoc();
22811 // struct va_list {
22814 // i64 overflow_area (address)
22815 // i64 reg_save_area (address)
22817 // sizeof(va_list) = 24
22818 // alignment(va_list) = 8
22820 unsigned TotalNumIntRegs = 6;
22821 unsigned TotalNumXMMRegs = 8;
22822 bool UseGPOffset = (ArgMode == 1);
22823 bool UseFPOffset = (ArgMode == 2);
22824 unsigned MaxOffset = TotalNumIntRegs * 8 +
22825 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
22827 /* Align ArgSize to a multiple of 8 */
22828 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
22829 bool NeedsAlign = (Align > 8);
22831 MachineBasicBlock *thisMBB = MBB;
22832 MachineBasicBlock *overflowMBB;
22833 MachineBasicBlock *offsetMBB;
22834 MachineBasicBlock *endMBB;
22836 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
22837 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
22838 unsigned OffsetReg = 0;
22840 if (!UseGPOffset && !UseFPOffset) {
22841 // If we only pull from the overflow region, we don't create a branch.
22842 // We don't need to alter control flow.
22843 OffsetDestReg = 0; // unused
22844 OverflowDestReg = DestReg;
22846 offsetMBB = nullptr;
22847 overflowMBB = thisMBB;
22850 // First emit code to check if gp_offset (or fp_offset) is below the bound.
22851 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
22852 // If not, pull from overflow_area. (branch to overflowMBB)
22857 // offsetMBB overflowMBB
22862 // Registers for the PHI in endMBB
22863 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
22864 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
22866 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
22867 MachineFunction *MF = MBB->getParent();
22868 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22869 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22870 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22872 MachineFunction::iterator MBBIter = ++MBB->getIterator();
22874 // Insert the new basic blocks
22875 MF->insert(MBBIter, offsetMBB);
22876 MF->insert(MBBIter, overflowMBB);
22877 MF->insert(MBBIter, endMBB);
22879 // Transfer the remainder of MBB and its successor edges to endMBB.
22880 endMBB->splice(endMBB->begin(), thisMBB,
22881 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
22882 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
22884 // Make offsetMBB and overflowMBB successors of thisMBB
22885 thisMBB->addSuccessor(offsetMBB);
22886 thisMBB->addSuccessor(overflowMBB);
22888 // endMBB is a successor of both offsetMBB and overflowMBB
22889 offsetMBB->addSuccessor(endMBB);
22890 overflowMBB->addSuccessor(endMBB);
22892 // Load the offset value into a register
22893 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
22894 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
22898 .addDisp(Disp, UseFPOffset ? 4 : 0)
22899 .addOperand(Segment)
22900 .setMemRefs(MMOBegin, MMOEnd);
22902 // Check if there is enough room left to pull this argument.
22903 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
22905 .addImm(MaxOffset + 8 - ArgSizeA8);
22907 // Branch to "overflowMBB" if offset >= max
22908 // Fall through to "offsetMBB" otherwise
22909 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
22910 .addMBB(overflowMBB);
22913 // In offsetMBB, emit code to use the reg_save_area.
22915 assert(OffsetReg != 0);
22917 // Read the reg_save_area address.
22918 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
22919 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
22924 .addOperand(Segment)
22925 .setMemRefs(MMOBegin, MMOEnd);
22927 // Zero-extend the offset
22928 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
22929 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
22932 .addImm(X86::sub_32bit);
22934 // Add the offset to the reg_save_area to get the final address.
22935 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
22936 .addReg(OffsetReg64)
22937 .addReg(RegSaveReg);
22939 // Compute the offset for the next argument
22940 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
22941 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
22943 .addImm(UseFPOffset ? 16 : 8);
22945 // Store it back into the va_list.
22946 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
22950 .addDisp(Disp, UseFPOffset ? 4 : 0)
22951 .addOperand(Segment)
22952 .addReg(NextOffsetReg)
22953 .setMemRefs(MMOBegin, MMOEnd);
22956 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
22961 // Emit code to use overflow area
22964 // Load the overflow_area address into a register.
22965 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
22966 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
22971 .addOperand(Segment)
22972 .setMemRefs(MMOBegin, MMOEnd);
22974 // If we need to align it, do so. Otherwise, just copy the address
22975 // to OverflowDestReg.
22977 // Align the overflow address
22978 assert(isPowerOf2_32(Align) && "Alignment must be a power of 2");
22979 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
22981 // aligned_addr = (addr + (align-1)) & ~(align-1)
22982 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
22983 .addReg(OverflowAddrReg)
22986 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
22988 .addImm(~(uint64_t)(Align-1));
22990 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
22991 .addReg(OverflowAddrReg);
22994 // Compute the next overflow address after this argument.
22995 // (the overflow address should be kept 8-byte aligned)
22996 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
22997 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
22998 .addReg(OverflowDestReg)
22999 .addImm(ArgSizeA8);
23001 // Store the new overflow address.
23002 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
23007 .addOperand(Segment)
23008 .addReg(NextAddrReg)
23009 .setMemRefs(MMOBegin, MMOEnd);
23011 // If we branched, emit the PHI to the front of endMBB.
23013 BuildMI(*endMBB, endMBB->begin(), DL,
23014 TII->get(X86::PHI), DestReg)
23015 .addReg(OffsetDestReg).addMBB(offsetMBB)
23016 .addReg(OverflowDestReg).addMBB(overflowMBB);
23019 // Erase the pseudo instruction
23020 MI.eraseFromParent();
23025 MachineBasicBlock *X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
23026 MachineInstr &MI, MachineBasicBlock *MBB) const {
23027 // Emit code to save XMM registers to the stack. The ABI says that the
23028 // number of registers to save is given in %al, so it's theoretically
23029 // possible to do an indirect jump trick to avoid saving all of them,
23030 // however this code takes a simpler approach and just executes all
23031 // of the stores if %al is non-zero. It's less code, and it's probably
23032 // easier on the hardware branch predictor, and stores aren't all that
23033 // expensive anyway.
23035 // Create the new basic blocks. One block contains all the XMM stores,
23036 // and one block is the final destination regardless of whether any
23037 // stores were performed.
23038 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
23039 MachineFunction *F = MBB->getParent();
23040 MachineFunction::iterator MBBIter = ++MBB->getIterator();
23041 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
23042 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
23043 F->insert(MBBIter, XMMSaveMBB);
23044 F->insert(MBBIter, EndMBB);
23046 // Transfer the remainder of MBB and its successor edges to EndMBB.
23047 EndMBB->splice(EndMBB->begin(), MBB,
23048 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
23049 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
23051 // The original block will now fall through to the XMM save block.
23052 MBB->addSuccessor(XMMSaveMBB);
23053 // The XMMSaveMBB will fall through to the end block.
23054 XMMSaveMBB->addSuccessor(EndMBB);
23056 // Now add the instructions.
23057 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
23058 DebugLoc DL = MI.getDebugLoc();
23060 unsigned CountReg = MI.getOperand(0).getReg();
23061 int64_t RegSaveFrameIndex = MI.getOperand(1).getImm();
23062 int64_t VarArgsFPOffset = MI.getOperand(2).getImm();
23064 if (!Subtarget.isCallingConvWin64(F->getFunction()->getCallingConv())) {
23065 // If %al is 0, branch around the XMM save block.
23066 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
23067 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
23068 MBB->addSuccessor(EndMBB);
23071 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
23072 // that was just emitted, but clearly shouldn't be "saved".
23073 assert((MI.getNumOperands() <= 3 ||
23074 !MI.getOperand(MI.getNumOperands() - 1).isReg() ||
23075 MI.getOperand(MI.getNumOperands() - 1).getReg() == X86::EFLAGS) &&
23076 "Expected last argument to be EFLAGS");
23077 unsigned MOVOpc = Subtarget.hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
23078 // In the XMM save block, save all the XMM argument registers.
23079 for (int i = 3, e = MI.getNumOperands() - 1; i != e; ++i) {
23080 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
23081 MachineMemOperand *MMO = F->getMachineMemOperand(
23082 MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
23083 MachineMemOperand::MOStore,
23084 /*Size=*/16, /*Align=*/16);
23085 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
23086 .addFrameIndex(RegSaveFrameIndex)
23087 .addImm(/*Scale=*/1)
23088 .addReg(/*IndexReg=*/0)
23089 .addImm(/*Disp=*/Offset)
23090 .addReg(/*Segment=*/0)
23091 .addReg(MI.getOperand(i).getReg())
23092 .addMemOperand(MMO);
23095 MI.eraseFromParent(); // The pseudo instruction is gone now.
23100 // The EFLAGS operand of SelectItr might be missing a kill marker
23101 // because there were multiple uses of EFLAGS, and ISel didn't know
23102 // which to mark. Figure out whether SelectItr should have had a
23103 // kill marker, and set it if it should. Returns the correct kill
23105 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
23106 MachineBasicBlock* BB,
23107 const TargetRegisterInfo* TRI) {
23108 // Scan forward through BB for a use/def of EFLAGS.
23109 MachineBasicBlock::iterator miI(std::next(SelectItr));
23110 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
23111 const MachineInstr& mi = *miI;
23112 if (mi.readsRegister(X86::EFLAGS))
23114 if (mi.definesRegister(X86::EFLAGS))
23115 break; // Should have kill-flag - update below.
23118 // If we hit the end of the block, check whether EFLAGS is live into a
23120 if (miI == BB->end()) {
23121 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
23122 sEnd = BB->succ_end();
23123 sItr != sEnd; ++sItr) {
23124 MachineBasicBlock* succ = *sItr;
23125 if (succ->isLiveIn(X86::EFLAGS))
23130 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
23131 // out. SelectMI should have a kill flag on EFLAGS.
23132 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
23136 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
23137 // together with other CMOV pseudo-opcodes into a single basic-block with
23138 // conditional jump around it.
23139 static bool isCMOVPseudo(MachineInstr &MI) {
23140 switch (MI.getOpcode()) {
23141 case X86::CMOV_FR32:
23142 case X86::CMOV_FR64:
23143 case X86::CMOV_GR8:
23144 case X86::CMOV_GR16:
23145 case X86::CMOV_GR32:
23146 case X86::CMOV_RFP32:
23147 case X86::CMOV_RFP64:
23148 case X86::CMOV_RFP80:
23149 case X86::CMOV_V2F64:
23150 case X86::CMOV_V2I64:
23151 case X86::CMOV_V4F32:
23152 case X86::CMOV_V4F64:
23153 case X86::CMOV_V4I64:
23154 case X86::CMOV_V16F32:
23155 case X86::CMOV_V8F32:
23156 case X86::CMOV_V8F64:
23157 case X86::CMOV_V8I64:
23158 case X86::CMOV_V8I1:
23159 case X86::CMOV_V16I1:
23160 case X86::CMOV_V32I1:
23161 case X86::CMOV_V64I1:
23169 MachineBasicBlock *
23170 X86TargetLowering::EmitLoweredSelect(MachineInstr &MI,
23171 MachineBasicBlock *BB) const {
23172 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
23173 DebugLoc DL = MI.getDebugLoc();
23175 // To "insert" a SELECT_CC instruction, we actually have to insert the
23176 // diamond control-flow pattern. The incoming instruction knows the
23177 // destination vreg to set, the condition code register to branch on, the
23178 // true/false values to select between, and a branch opcode to use.
23179 const BasicBlock *LLVM_BB = BB->getBasicBlock();
23180 MachineFunction::iterator It = ++BB->getIterator();
23185 // cmpTY ccX, r1, r2
23187 // fallthrough --> copy0MBB
23188 MachineBasicBlock *thisMBB = BB;
23189 MachineFunction *F = BB->getParent();
23191 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
23192 // as described above, by inserting a BB, and then making a PHI at the join
23193 // point to select the true and false operands of the CMOV in the PHI.
23195 // The code also handles two different cases of multiple CMOV opcodes
23199 // In this case, there are multiple CMOVs in a row, all which are based on
23200 // the same condition setting (or the exact opposite condition setting).
23201 // In this case we can lower all the CMOVs using a single inserted BB, and
23202 // then make a number of PHIs at the join point to model the CMOVs. The only
23203 // trickiness here, is that in a case like:
23205 // t2 = CMOV cond1 t1, f1
23206 // t3 = CMOV cond1 t2, f2
23208 // when rewriting this into PHIs, we have to perform some renaming on the
23209 // temps since you cannot have a PHI operand refer to a PHI result earlier
23210 // in the same block. The "simple" but wrong lowering would be:
23212 // t2 = PHI t1(BB1), f1(BB2)
23213 // t3 = PHI t2(BB1), f2(BB2)
23215 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
23216 // renaming is to note that on the path through BB1, t2 is really just a
23217 // copy of t1, and do that renaming, properly generating:
23219 // t2 = PHI t1(BB1), f1(BB2)
23220 // t3 = PHI t1(BB1), f2(BB2)
23222 // Case 2, we lower cascaded CMOVs such as
23224 // (CMOV (CMOV F, T, cc1), T, cc2)
23226 // to two successives branches. For that, we look for another CMOV as the
23227 // following instruction.
23229 // Without this, we would add a PHI between the two jumps, which ends up
23230 // creating a few copies all around. For instance, for
23232 // (sitofp (zext (fcmp une)))
23234 // we would generate:
23236 // ucomiss %xmm1, %xmm0
23237 // movss <1.0f>, %xmm0
23238 // movaps %xmm0, %xmm1
23240 // xorps %xmm1, %xmm1
23243 // movaps %xmm1, %xmm0
23247 // because this custom-inserter would have generated:
23259 // A: X = ...; Y = ...
23261 // C: Z = PHI [X, A], [Y, B]
23263 // E: PHI [X, C], [Z, D]
23265 // If we lower both CMOVs in a single step, we can instead generate:
23277 // A: X = ...; Y = ...
23279 // E: PHI [X, A], [X, C], [Y, D]
23281 // Which, in our sitofp/fcmp example, gives us something like:
23283 // ucomiss %xmm1, %xmm0
23284 // movss <1.0f>, %xmm0
23287 // xorps %xmm0, %xmm0
23291 MachineInstr *CascadedCMOV = nullptr;
23292 MachineInstr *LastCMOV = &MI;
23293 X86::CondCode CC = X86::CondCode(MI.getOperand(3).getImm());
23294 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
23295 MachineBasicBlock::iterator NextMIIt =
23296 std::next(MachineBasicBlock::iterator(MI));
23298 // Check for case 1, where there are multiple CMOVs with the same condition
23299 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
23300 // number of jumps the most.
23302 if (isCMOVPseudo(MI)) {
23303 // See if we have a string of CMOVS with the same condition.
23304 while (NextMIIt != BB->end() && isCMOVPseudo(*NextMIIt) &&
23305 (NextMIIt->getOperand(3).getImm() == CC ||
23306 NextMIIt->getOperand(3).getImm() == OppCC)) {
23307 LastCMOV = &*NextMIIt;
23312 // This checks for case 2, but only do this if we didn't already find
23313 // case 1, as indicated by LastCMOV == MI.
23314 if (LastCMOV == &MI && NextMIIt != BB->end() &&
23315 NextMIIt->getOpcode() == MI.getOpcode() &&
23316 NextMIIt->getOperand(2).getReg() == MI.getOperand(2).getReg() &&
23317 NextMIIt->getOperand(1).getReg() == MI.getOperand(0).getReg() &&
23318 NextMIIt->getOperand(1).isKill()) {
23319 CascadedCMOV = &*NextMIIt;
23322 MachineBasicBlock *jcc1MBB = nullptr;
23324 // If we have a cascaded CMOV, we lower it to two successive branches to
23325 // the same block. EFLAGS is used by both, so mark it as live in the second.
23326 if (CascadedCMOV) {
23327 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
23328 F->insert(It, jcc1MBB);
23329 jcc1MBB->addLiveIn(X86::EFLAGS);
23332 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
23333 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
23334 F->insert(It, copy0MBB);
23335 F->insert(It, sinkMBB);
23337 // If the EFLAGS register isn't dead in the terminator, then claim that it's
23338 // live into the sink and copy blocks.
23339 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
23341 MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
23342 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
23343 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
23344 copy0MBB->addLiveIn(X86::EFLAGS);
23345 sinkMBB->addLiveIn(X86::EFLAGS);
23348 // Transfer the remainder of BB and its successor edges to sinkMBB.
23349 sinkMBB->splice(sinkMBB->begin(), BB,
23350 std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
23351 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
23353 // Add the true and fallthrough blocks as its successors.
23354 if (CascadedCMOV) {
23355 // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
23356 BB->addSuccessor(jcc1MBB);
23358 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
23359 // jump to the sinkMBB.
23360 jcc1MBB->addSuccessor(copy0MBB);
23361 jcc1MBB->addSuccessor(sinkMBB);
23363 BB->addSuccessor(copy0MBB);
23366 // The true block target of the first (or only) branch is always sinkMBB.
23367 BB->addSuccessor(sinkMBB);
23369 // Create the conditional branch instruction.
23370 unsigned Opc = X86::GetCondBranchFromCond(CC);
23371 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
23373 if (CascadedCMOV) {
23374 unsigned Opc2 = X86::GetCondBranchFromCond(
23375 (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
23376 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
23380 // %FalseValue = ...
23381 // # fallthrough to sinkMBB
23382 copy0MBB->addSuccessor(sinkMBB);
23385 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
23387 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
23388 MachineBasicBlock::iterator MIItEnd =
23389 std::next(MachineBasicBlock::iterator(LastCMOV));
23390 MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
23391 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
23392 MachineInstrBuilder MIB;
23394 // As we are creating the PHIs, we have to be careful if there is more than
23395 // one. Later CMOVs may reference the results of earlier CMOVs, but later
23396 // PHIs have to reference the individual true/false inputs from earlier PHIs.
23397 // That also means that PHI construction must work forward from earlier to
23398 // later, and that the code must maintain a mapping from earlier PHI's
23399 // destination registers, and the registers that went into the PHI.
23401 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
23402 unsigned DestReg = MIIt->getOperand(0).getReg();
23403 unsigned Op1Reg = MIIt->getOperand(1).getReg();
23404 unsigned Op2Reg = MIIt->getOperand(2).getReg();
23406 // If this CMOV we are generating is the opposite condition from
23407 // the jump we generated, then we have to swap the operands for the
23408 // PHI that is going to be generated.
23409 if (MIIt->getOperand(3).getImm() == OppCC)
23410 std::swap(Op1Reg, Op2Reg);
23412 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
23413 Op1Reg = RegRewriteTable[Op1Reg].first;
23415 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
23416 Op2Reg = RegRewriteTable[Op2Reg].second;
23418 MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
23419 TII->get(X86::PHI), DestReg)
23420 .addReg(Op1Reg).addMBB(copy0MBB)
23421 .addReg(Op2Reg).addMBB(thisMBB);
23423 // Add this PHI to the rewrite table.
23424 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
23427 // If we have a cascaded CMOV, the second Jcc provides the same incoming
23428 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
23429 if (CascadedCMOV) {
23430 MIB.addReg(MI.getOperand(2).getReg()).addMBB(jcc1MBB);
23431 // Copy the PHI result to the register defined by the second CMOV.
23432 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
23433 DL, TII->get(TargetOpcode::COPY),
23434 CascadedCMOV->getOperand(0).getReg())
23435 .addReg(MI.getOperand(0).getReg());
23436 CascadedCMOV->eraseFromParent();
23439 // Now remove the CMOV(s).
23440 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
23441 (MIIt++)->eraseFromParent();
23446 MachineBasicBlock *
23447 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr &MI,
23448 MachineBasicBlock *BB) const {
23449 // Combine the following atomic floating-point modification pattern:
23450 // a.store(reg OP a.load(acquire), release)
23451 // Transform them into:
23452 // OPss (%gpr), %xmm
23453 // movss %xmm, (%gpr)
23454 // Or sd equivalent for 64-bit operations.
23456 switch (MI.getOpcode()) {
23457 default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
23458 case X86::RELEASE_FADD32mr:
23459 FOp = X86::ADDSSrm;
23460 MOp = X86::MOVSSmr;
23462 case X86::RELEASE_FADD64mr:
23463 FOp = X86::ADDSDrm;
23464 MOp = X86::MOVSDmr;
23467 const X86InstrInfo *TII = Subtarget.getInstrInfo();
23468 DebugLoc DL = MI.getDebugLoc();
23469 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
23470 unsigned ValOpIdx = X86::AddrNumOperands;
23471 unsigned VSrc = MI.getOperand(ValOpIdx).getReg();
23472 MachineInstrBuilder MIB =
23473 BuildMI(*BB, MI, DL, TII->get(FOp),
23474 MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
23476 for (int i = 0; i < X86::AddrNumOperands; ++i) {
23477 MachineOperand &Operand = MI.getOperand(i);
23478 // Clear any kill flags on register operands as we'll create a second
23479 // instruction using the same address operands.
23480 if (Operand.isReg())
23481 Operand.setIsKill(false);
23482 MIB.addOperand(Operand);
23484 MachineInstr *FOpMI = MIB;
23485 MIB = BuildMI(*BB, MI, DL, TII->get(MOp));
23486 for (int i = 0; i < X86::AddrNumOperands; ++i)
23487 MIB.addOperand(MI.getOperand(i));
23488 MIB.addReg(FOpMI->getOperand(0).getReg(), RegState::Kill);
23489 MI.eraseFromParent(); // The pseudo instruction is gone now.
23493 MachineBasicBlock *
23494 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr &MI,
23495 MachineBasicBlock *BB) const {
23496 MachineFunction *MF = BB->getParent();
23497 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
23498 DebugLoc DL = MI.getDebugLoc();
23499 const BasicBlock *LLVM_BB = BB->getBasicBlock();
23501 assert(MF->shouldSplitStack());
23503 const bool Is64Bit = Subtarget.is64Bit();
23504 const bool IsLP64 = Subtarget.isTarget64BitLP64();
23506 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
23507 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
23510 // ... [Till the alloca]
23511 // If stacklet is not large enough, jump to mallocMBB
23514 // Allocate by subtracting from RSP
23515 // Jump to continueMBB
23518 // Allocate by call to runtime
23522 // [rest of original BB]
23525 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
23526 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
23527 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
23529 MachineRegisterInfo &MRI = MF->getRegInfo();
23530 const TargetRegisterClass *AddrRegClass =
23531 getRegClassFor(getPointerTy(MF->getDataLayout()));
23533 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
23534 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
23535 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
23536 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
23537 sizeVReg = MI.getOperand(1).getReg(),
23539 IsLP64 || Subtarget.isTargetNaCl64() ? X86::RSP : X86::ESP;
23541 MachineFunction::iterator MBBIter = ++BB->getIterator();
23543 MF->insert(MBBIter, bumpMBB);
23544 MF->insert(MBBIter, mallocMBB);
23545 MF->insert(MBBIter, continueMBB);
23547 continueMBB->splice(continueMBB->begin(), BB,
23548 std::next(MachineBasicBlock::iterator(MI)), BB->end());
23549 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
23551 // Add code to the main basic block to check if the stack limit has been hit,
23552 // and if so, jump to mallocMBB otherwise to bumpMBB.
23553 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
23554 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
23555 .addReg(tmpSPVReg).addReg(sizeVReg);
23556 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
23557 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
23558 .addReg(SPLimitVReg);
23559 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
23561 // bumpMBB simply decreases the stack pointer, since we know the current
23562 // stacklet has enough space.
23563 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
23564 .addReg(SPLimitVReg);
23565 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
23566 .addReg(SPLimitVReg);
23567 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
23569 // Calls into a routine in libgcc to allocate more space from the heap.
23570 const uint32_t *RegMask =
23571 Subtarget.getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
23573 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
23575 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
23576 .addExternalSymbol("__morestack_allocate_stack_space")
23577 .addRegMask(RegMask)
23578 .addReg(X86::RDI, RegState::Implicit)
23579 .addReg(X86::RAX, RegState::ImplicitDefine);
23580 } else if (Is64Bit) {
23581 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
23583 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
23584 .addExternalSymbol("__morestack_allocate_stack_space")
23585 .addRegMask(RegMask)
23586 .addReg(X86::EDI, RegState::Implicit)
23587 .addReg(X86::EAX, RegState::ImplicitDefine);
23589 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
23591 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
23592 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
23593 .addExternalSymbol("__morestack_allocate_stack_space")
23594 .addRegMask(RegMask)
23595 .addReg(X86::EAX, RegState::ImplicitDefine);
23599 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
23602 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
23603 .addReg(IsLP64 ? X86::RAX : X86::EAX);
23604 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
23606 // Set up the CFG correctly.
23607 BB->addSuccessor(bumpMBB);
23608 BB->addSuccessor(mallocMBB);
23609 mallocMBB->addSuccessor(continueMBB);
23610 bumpMBB->addSuccessor(continueMBB);
23612 // Take care of the PHI nodes.
23613 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
23614 MI.getOperand(0).getReg())
23615 .addReg(mallocPtrVReg)
23617 .addReg(bumpSPPtrVReg)
23620 // Delete the original pseudo instruction.
23621 MI.eraseFromParent();
23624 return continueMBB;
23627 MachineBasicBlock *
23628 X86TargetLowering::EmitLoweredCatchRet(MachineInstr &MI,
23629 MachineBasicBlock *BB) const {
23630 MachineFunction *MF = BB->getParent();
23631 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
23632 MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
23633 DebugLoc DL = MI.getDebugLoc();
23635 assert(!isAsynchronousEHPersonality(
23636 classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
23637 "SEH does not use catchret!");
23639 // Only 32-bit EH needs to worry about manually restoring stack pointers.
23640 if (!Subtarget.is32Bit())
23643 // C++ EH creates a new target block to hold the restore code, and wires up
23644 // the new block to the return destination with a normal JMP_4.
23645 MachineBasicBlock *RestoreMBB =
23646 MF->CreateMachineBasicBlock(BB->getBasicBlock());
23647 assert(BB->succ_size() == 1);
23648 MF->insert(std::next(BB->getIterator()), RestoreMBB);
23649 RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
23650 BB->addSuccessor(RestoreMBB);
23651 MI.getOperand(0).setMBB(RestoreMBB);
23653 auto RestoreMBBI = RestoreMBB->begin();
23654 BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
23655 BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
23659 MachineBasicBlock *
23660 X86TargetLowering::EmitLoweredCatchPad(MachineInstr &MI,
23661 MachineBasicBlock *BB) const {
23662 MachineFunction *MF = BB->getParent();
23663 const Constant *PerFn = MF->getFunction()->getPersonalityFn();
23664 bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
23665 // Only 32-bit SEH requires special handling for catchpad.
23666 if (IsSEH && Subtarget.is32Bit()) {
23667 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
23668 DebugLoc DL = MI.getDebugLoc();
23669 BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
23671 MI.eraseFromParent();
23675 MachineBasicBlock *
23676 X86TargetLowering::EmitLoweredTLSAddr(MachineInstr &MI,
23677 MachineBasicBlock *BB) const {
23678 // So, here we replace TLSADDR with the sequence:
23679 // adjust_stackdown -> TLSADDR -> adjust_stackup.
23680 // We need this because TLSADDR is lowered into calls
23681 // inside MC, therefore without the two markers shrink-wrapping
23682 // may push the prologue/epilogue pass them.
23683 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
23684 DebugLoc DL = MI.getDebugLoc();
23685 MachineFunction &MF = *BB->getParent();
23687 // Emit CALLSEQ_START right before the instruction.
23688 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
23689 MachineInstrBuilder CallseqStart =
23690 BuildMI(MF, DL, TII.get(AdjStackDown)).addImm(0).addImm(0);
23691 BB->insert(MachineBasicBlock::iterator(MI), CallseqStart);
23693 // Emit CALLSEQ_END right after the instruction.
23694 // We don't call erase from parent because we want to keep the
23695 // original instruction around.
23696 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
23697 MachineInstrBuilder CallseqEnd =
23698 BuildMI(MF, DL, TII.get(AdjStackUp)).addImm(0).addImm(0);
23699 BB->insertAfter(MachineBasicBlock::iterator(MI), CallseqEnd);
23704 MachineBasicBlock *
23705 X86TargetLowering::EmitLoweredTLSCall(MachineInstr &MI,
23706 MachineBasicBlock *BB) const {
23707 // This is pretty easy. We're taking the value that we received from
23708 // our load from the relocation, sticking it in either RDI (x86-64)
23709 // or EAX and doing an indirect call. The return value will then
23710 // be in the normal return register.
23711 MachineFunction *F = BB->getParent();
23712 const X86InstrInfo *TII = Subtarget.getInstrInfo();
23713 DebugLoc DL = MI.getDebugLoc();
23715 assert(Subtarget.isTargetDarwin() && "Darwin only instr emitted?");
23716 assert(MI.getOperand(3).isGlobal() && "This should be a global");
23718 // Get a register mask for the lowered call.
23719 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
23720 // proper register mask.
23721 const uint32_t *RegMask =
23722 Subtarget.is64Bit() ?
23723 Subtarget.getRegisterInfo()->getDarwinTLSCallPreservedMask() :
23724 Subtarget.getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
23725 if (Subtarget.is64Bit()) {
23726 MachineInstrBuilder MIB =
23727 BuildMI(*BB, MI, DL, TII->get(X86::MOV64rm), X86::RDI)
23731 .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
23732 MI.getOperand(3).getTargetFlags())
23734 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
23735 addDirectMem(MIB, X86::RDI);
23736 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
23737 } else if (!isPositionIndependent()) {
23738 MachineInstrBuilder MIB =
23739 BuildMI(*BB, MI, DL, TII->get(X86::MOV32rm), X86::EAX)
23743 .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
23744 MI.getOperand(3).getTargetFlags())
23746 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
23747 addDirectMem(MIB, X86::EAX);
23748 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
23750 MachineInstrBuilder MIB =
23751 BuildMI(*BB, MI, DL, TII->get(X86::MOV32rm), X86::EAX)
23752 .addReg(TII->getGlobalBaseReg(F))
23755 .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
23756 MI.getOperand(3).getTargetFlags())
23758 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
23759 addDirectMem(MIB, X86::EAX);
23760 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
23763 MI.eraseFromParent(); // The pseudo instruction is gone now.
23767 MachineBasicBlock *
23768 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
23769 MachineBasicBlock *MBB) const {
23770 DebugLoc DL = MI.getDebugLoc();
23771 MachineFunction *MF = MBB->getParent();
23772 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
23773 MachineRegisterInfo &MRI = MF->getRegInfo();
23775 const BasicBlock *BB = MBB->getBasicBlock();
23776 MachineFunction::iterator I = ++MBB->getIterator();
23778 // Memory Reference
23779 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
23780 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
23783 unsigned MemOpndSlot = 0;
23785 unsigned CurOp = 0;
23787 DstReg = MI.getOperand(CurOp++).getReg();
23788 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
23789 assert(RC->hasType(MVT::i32) && "Invalid destination!");
23790 unsigned mainDstReg = MRI.createVirtualRegister(RC);
23791 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
23793 MemOpndSlot = CurOp;
23795 MVT PVT = getPointerTy(MF->getDataLayout());
23796 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
23797 "Invalid Pointer Size!");
23799 // For v = setjmp(buf), we generate
23802 // buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
23803 // SjLjSetup restoreMBB
23809 // v = phi(main, restore)
23812 // if base pointer being used, load it from frame
23815 MachineBasicBlock *thisMBB = MBB;
23816 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
23817 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
23818 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
23819 MF->insert(I, mainMBB);
23820 MF->insert(I, sinkMBB);
23821 MF->push_back(restoreMBB);
23822 restoreMBB->setHasAddressTaken();
23824 MachineInstrBuilder MIB;
23826 // Transfer the remainder of BB and its successor edges to sinkMBB.
23827 sinkMBB->splice(sinkMBB->begin(), MBB,
23828 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
23829 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
23832 unsigned PtrStoreOpc = 0;
23833 unsigned LabelReg = 0;
23834 const int64_t LabelOffset = 1 * PVT.getStoreSize();
23835 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
23836 !isPositionIndependent();
23838 // Prepare IP either in reg or imm.
23839 if (!UseImmLabel) {
23840 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
23841 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
23842 LabelReg = MRI.createVirtualRegister(PtrRC);
23843 if (Subtarget.is64Bit()) {
23844 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
23848 .addMBB(restoreMBB)
23851 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
23852 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
23853 .addReg(XII->getGlobalBaseReg(MF))
23856 .addMBB(restoreMBB, Subtarget.classifyBlockAddressReference())
23860 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
23862 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
23863 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
23864 if (i == X86::AddrDisp)
23865 MIB.addDisp(MI.getOperand(MemOpndSlot + i), LabelOffset);
23867 MIB.addOperand(MI.getOperand(MemOpndSlot + i));
23870 MIB.addReg(LabelReg);
23872 MIB.addMBB(restoreMBB);
23873 MIB.setMemRefs(MMOBegin, MMOEnd);
23875 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
23876 .addMBB(restoreMBB);
23878 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
23879 MIB.addRegMask(RegInfo->getNoPreservedMask());
23880 thisMBB->addSuccessor(mainMBB);
23881 thisMBB->addSuccessor(restoreMBB);
23885 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
23886 mainMBB->addSuccessor(sinkMBB);
23889 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
23890 TII->get(X86::PHI), DstReg)
23891 .addReg(mainDstReg).addMBB(mainMBB)
23892 .addReg(restoreDstReg).addMBB(restoreMBB);
23895 if (RegInfo->hasBasePointer(*MF)) {
23896 const bool Uses64BitFramePtr =
23897 Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
23898 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
23899 X86FI->setRestoreBasePointer(MF);
23900 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
23901 unsigned BasePtr = RegInfo->getBaseRegister();
23902 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
23903 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
23904 FramePtr, true, X86FI->getRestoreBasePointerOffset())
23905 .setMIFlag(MachineInstr::FrameSetup);
23907 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
23908 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
23909 restoreMBB->addSuccessor(sinkMBB);
23911 MI.eraseFromParent();
23915 MachineBasicBlock *
23916 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
23917 MachineBasicBlock *MBB) const {
23918 DebugLoc DL = MI.getDebugLoc();
23919 MachineFunction *MF = MBB->getParent();
23920 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
23921 MachineRegisterInfo &MRI = MF->getRegInfo();
23923 // Memory Reference
23924 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
23925 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
23927 MVT PVT = getPointerTy(MF->getDataLayout());
23928 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
23929 "Invalid Pointer Size!");
23931 const TargetRegisterClass *RC =
23932 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
23933 unsigned Tmp = MRI.createVirtualRegister(RC);
23934 // Since FP is only updated here but NOT referenced, it's treated as GPR.
23935 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
23936 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
23937 unsigned SP = RegInfo->getStackRegister();
23939 MachineInstrBuilder MIB;
23941 const int64_t LabelOffset = 1 * PVT.getStoreSize();
23942 const int64_t SPOffset = 2 * PVT.getStoreSize();
23944 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
23945 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
23948 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
23949 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
23950 MIB.addOperand(MI.getOperand(i));
23951 MIB.setMemRefs(MMOBegin, MMOEnd);
23953 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
23954 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
23955 if (i == X86::AddrDisp)
23956 MIB.addDisp(MI.getOperand(i), LabelOffset);
23958 MIB.addOperand(MI.getOperand(i));
23960 MIB.setMemRefs(MMOBegin, MMOEnd);
23962 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
23963 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
23964 if (i == X86::AddrDisp)
23965 MIB.addDisp(MI.getOperand(i), SPOffset);
23967 MIB.addOperand(MI.getOperand(i));
23969 MIB.setMemRefs(MMOBegin, MMOEnd);
23971 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
23973 MI.eraseFromParent();
23977 void X86TargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
23978 MachineBasicBlock *MBB,
23979 MachineBasicBlock *DispatchBB,
23981 DebugLoc DL = MI.getDebugLoc();
23982 MachineFunction *MF = MBB->getParent();
23983 MachineRegisterInfo *MRI = &MF->getRegInfo();
23984 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
23986 MVT PVT = getPointerTy(MF->getDataLayout());
23987 assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
23992 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
23993 !isPositionIndependent();
23996 Op = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
23998 const TargetRegisterClass *TRC =
23999 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
24000 VR = MRI->createVirtualRegister(TRC);
24001 Op = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
24003 /* const X86InstrInfo *XII = static_cast<const X86InstrInfo *>(TII); */
24005 if (Subtarget.is64Bit())
24006 BuildMI(*MBB, MI, DL, TII->get(X86::LEA64r), VR)
24010 .addMBB(DispatchBB)
24013 BuildMI(*MBB, MI, DL, TII->get(X86::LEA32r), VR)
24014 .addReg(0) /* XII->getGlobalBaseReg(MF) */
24017 .addMBB(DispatchBB, Subtarget.classifyBlockAddressReference())
24021 MachineInstrBuilder MIB = BuildMI(*MBB, MI, DL, TII->get(Op));
24022 addFrameReference(MIB, FI, 36);
24024 MIB.addMBB(DispatchBB);
24029 MachineBasicBlock *
24030 X86TargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
24031 MachineBasicBlock *BB) const {
24032 DebugLoc DL = MI.getDebugLoc();
24033 MachineFunction *MF = BB->getParent();
24034 MachineModuleInfo *MMI = &MF->getMMI();
24035 MachineFrameInfo *MFI = MF->getFrameInfo();
24036 MachineRegisterInfo *MRI = &MF->getRegInfo();
24037 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
24038 int FI = MFI->getFunctionContextIndex();
24040 // Get a mapping of the call site numbers to all of the landing pads they're
24041 // associated with.
24042 DenseMap<unsigned, SmallVector<MachineBasicBlock *, 2>> CallSiteNumToLPad;
24043 unsigned MaxCSNum = 0;
24044 for (auto &MBB : *MF) {
24045 if (!MBB.isEHPad())
24048 MCSymbol *Sym = nullptr;
24049 for (const auto &MI : MBB) {
24050 if (MI.isDebugValue())
24053 assert(MI.isEHLabel() && "expected EH_LABEL");
24054 Sym = MI.getOperand(0).getMCSymbol();
24058 if (!MMI->hasCallSiteLandingPad(Sym))
24061 for (unsigned CSI : MMI->getCallSiteLandingPad(Sym)) {
24062 CallSiteNumToLPad[CSI].push_back(&MBB);
24063 MaxCSNum = std::max(MaxCSNum, CSI);
24067 // Get an ordered list of the machine basic blocks for the jump table.
24068 std::vector<MachineBasicBlock *> LPadList;
24069 SmallPtrSet<MachineBasicBlock *, 32> InvokeBBs;
24070 LPadList.reserve(CallSiteNumToLPad.size());
24072 for (unsigned CSI = 1; CSI <= MaxCSNum; ++CSI) {
24073 for (auto &LP : CallSiteNumToLPad[CSI]) {
24074 LPadList.push_back(LP);
24075 InvokeBBs.insert(LP->pred_begin(), LP->pred_end());
24079 assert(!LPadList.empty() &&
24080 "No landing pad destinations for the dispatch jump table!");
24082 // Create the MBBs for the dispatch code.
24084 // Shove the dispatch's address into the return slot in the function context.
24085 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
24086 DispatchBB->setIsEHPad(true);
24088 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
24089 BuildMI(TrapBB, DL, TII->get(X86::TRAP));
24090 DispatchBB->addSuccessor(TrapBB);
24092 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
24093 DispatchBB->addSuccessor(DispContBB);
24096 MF->push_back(DispatchBB);
24097 MF->push_back(DispContBB);
24098 MF->push_back(TrapBB);
24100 // Insert code into the entry block that creates and registers the function
24102 SetupEntryBlockForSjLj(MI, BB, DispatchBB, FI);
24104 // Create the jump table and associated information
24105 MachineJumpTableInfo *JTI =
24106 MF->getOrCreateJumpTableInfo(getJumpTableEncoding());
24107 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
24109 const X86InstrInfo *XII = static_cast<const X86InstrInfo *>(TII);
24110 const X86RegisterInfo &RI = XII->getRegisterInfo();
24112 // Add a register mask with no preserved registers. This results in all
24113 // registers being marked as clobbered.
24114 if (RI.hasBasePointer(*MF)) {
24115 const bool FPIs64Bit =
24116 Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
24117 X86MachineFunctionInfo *MFI = MF->getInfo<X86MachineFunctionInfo>();
24118 MFI->setRestoreBasePointer(MF);
24120 unsigned FP = RI.getFrameRegister(*MF);
24121 unsigned BP = RI.getBaseRegister();
24122 unsigned Op = FPIs64Bit ? X86::MOV64rm : X86::MOV32rm;
24123 addRegOffset(BuildMI(DispatchBB, DL, TII->get(Op), BP), FP, true,
24124 MFI->getRestoreBasePointerOffset())
24125 .addRegMask(RI.getNoPreservedMask());
24127 BuildMI(DispatchBB, DL, TII->get(X86::NOOP))
24128 .addRegMask(RI.getNoPreservedMask());
24131 unsigned IReg = MRI->createVirtualRegister(&X86::GR32RegClass);
24132 addFrameReference(BuildMI(DispatchBB, DL, TII->get(X86::MOV32rm), IReg), FI,
24134 BuildMI(DispatchBB, DL, TII->get(X86::CMP32ri))
24136 .addImm(LPadList.size());
24137 BuildMI(DispatchBB, DL, TII->get(X86::JA_1)).addMBB(TrapBB);
24139 unsigned JReg = MRI->createVirtualRegister(&X86::GR32RegClass);
24140 BuildMI(DispContBB, DL, TII->get(X86::SUB32ri), JReg)
24143 BuildMI(DispContBB, DL,
24144 TII->get(Subtarget.is64Bit() ? X86::JMP64m : X86::JMP32m))
24146 .addImm(Subtarget.is64Bit() ? 8 : 4)
24148 .addJumpTableIndex(MJTI)
24151 // Add the jump table entries as successors to the MBB.
24152 SmallPtrSet<MachineBasicBlock *, 8> SeenMBBs;
24153 for (auto &LP : LPadList)
24154 if (SeenMBBs.insert(LP).second)
24155 DispContBB->addSuccessor(LP);
24157 // N.B. the order the invoke BBs are processed in doesn't matter here.
24158 SmallVector<MachineBasicBlock *, 64> MBBLPads;
24159 const MCPhysReg *SavedRegs =
24160 Subtarget.getRegisterInfo()->getCalleeSavedRegs(MF);
24161 for (MachineBasicBlock *MBB : InvokeBBs) {
24162 // Remove the landing pad successor from the invoke block and replace it
24163 // with the new dispatch block.
24164 // Keep a copy of Successors since it's modified inside the loop.
24165 SmallVector<MachineBasicBlock *, 8> Successors(MBB->succ_rbegin(),
24167 // FIXME: Avoid quadratic complexity.
24168 for (auto MBBS : Successors) {
24169 if (MBBS->isEHPad()) {
24170 MBB->removeSuccessor(MBBS);
24171 MBBLPads.push_back(MBBS);
24175 MBB->addSuccessor(DispatchBB);
24177 // Find the invoke call and mark all of the callee-saved registers as
24178 // 'implicit defined' so that they're spilled. This prevents code from
24179 // moving instructions to before the EH block, where they will never be
24181 for (auto &II : reverse(*MBB)) {
24185 DenseMap<unsigned, bool> DefRegs;
24186 for (auto &MOp : II.operands())
24188 DefRegs[MOp.getReg()] = true;
24190 MachineInstrBuilder MIB(*MF, &II);
24191 for (unsigned RI = 0; SavedRegs[RI]; ++RI) {
24192 unsigned Reg = SavedRegs[RI];
24194 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
24201 // Mark all former landing pads as non-landing pads. The dispatch is the only
24202 // landing pad now.
24203 for (auto &LP : MBBLPads)
24204 LP->setIsEHPad(false);
24206 // The instruction is gone now.
24207 MI.eraseFromParent();
24211 // Replace 213-type (isel default) FMA3 instructions with 231-type for
24212 // accumulator loops. Writing back to the accumulator allows the coalescer
24213 // to remove extra copies in the loop.
24214 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
24215 MachineBasicBlock *
24216 X86TargetLowering::emitFMA3Instr(MachineInstr &MI,
24217 MachineBasicBlock *MBB) const {
24218 MachineOperand &AddendOp = MI.getOperand(3);
24220 // Bail out early if the addend isn't a register - we can't switch these.
24221 if (!AddendOp.isReg())
24224 MachineFunction &MF = *MBB->getParent();
24225 MachineRegisterInfo &MRI = MF.getRegInfo();
24227 // Check whether the addend is defined by a PHI:
24228 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
24229 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
24230 if (!AddendDef.isPHI())
24233 // Look for the following pattern:
24235 // %addend = phi [%entry, 0], [%loop, %result]
24237 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
24241 // %addend = phi [%entry, 0], [%loop, %result]
24243 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
24245 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
24246 assert(AddendDef.getOperand(i).isReg());
24247 MachineOperand PHISrcOp = AddendDef.getOperand(i);
24248 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
24249 if (&PHISrcInst == &MI) {
24250 // Found a matching instruction.
24251 unsigned NewFMAOpc = 0;
24252 switch (MI.getOpcode()) {
24253 case X86::VFMADDPDr213r:
24254 NewFMAOpc = X86::VFMADDPDr231r;
24256 case X86::VFMADDPSr213r:
24257 NewFMAOpc = X86::VFMADDPSr231r;
24259 case X86::VFMADDSDr213r:
24260 NewFMAOpc = X86::VFMADDSDr231r;
24262 case X86::VFMADDSSr213r:
24263 NewFMAOpc = X86::VFMADDSSr231r;
24265 case X86::VFMSUBPDr213r:
24266 NewFMAOpc = X86::VFMSUBPDr231r;
24268 case X86::VFMSUBPSr213r:
24269 NewFMAOpc = X86::VFMSUBPSr231r;
24271 case X86::VFMSUBSDr213r:
24272 NewFMAOpc = X86::VFMSUBSDr231r;
24274 case X86::VFMSUBSSr213r:
24275 NewFMAOpc = X86::VFMSUBSSr231r;
24277 case X86::VFNMADDPDr213r:
24278 NewFMAOpc = X86::VFNMADDPDr231r;
24280 case X86::VFNMADDPSr213r:
24281 NewFMAOpc = X86::VFNMADDPSr231r;
24283 case X86::VFNMADDSDr213r:
24284 NewFMAOpc = X86::VFNMADDSDr231r;
24286 case X86::VFNMADDSSr213r:
24287 NewFMAOpc = X86::VFNMADDSSr231r;
24289 case X86::VFNMSUBPDr213r:
24290 NewFMAOpc = X86::VFNMSUBPDr231r;
24292 case X86::VFNMSUBPSr213r:
24293 NewFMAOpc = X86::VFNMSUBPSr231r;
24295 case X86::VFNMSUBSDr213r:
24296 NewFMAOpc = X86::VFNMSUBSDr231r;
24298 case X86::VFNMSUBSSr213r:
24299 NewFMAOpc = X86::VFNMSUBSSr231r;
24301 case X86::VFMADDSUBPDr213r:
24302 NewFMAOpc = X86::VFMADDSUBPDr231r;
24304 case X86::VFMADDSUBPSr213r:
24305 NewFMAOpc = X86::VFMADDSUBPSr231r;
24307 case X86::VFMSUBADDPDr213r:
24308 NewFMAOpc = X86::VFMSUBADDPDr231r;
24310 case X86::VFMSUBADDPSr213r:
24311 NewFMAOpc = X86::VFMSUBADDPSr231r;
24314 case X86::VFMADDPDr213rY:
24315 NewFMAOpc = X86::VFMADDPDr231rY;
24317 case X86::VFMADDPSr213rY:
24318 NewFMAOpc = X86::VFMADDPSr231rY;
24320 case X86::VFMSUBPDr213rY:
24321 NewFMAOpc = X86::VFMSUBPDr231rY;
24323 case X86::VFMSUBPSr213rY:
24324 NewFMAOpc = X86::VFMSUBPSr231rY;
24326 case X86::VFNMADDPDr213rY:
24327 NewFMAOpc = X86::VFNMADDPDr231rY;
24329 case X86::VFNMADDPSr213rY:
24330 NewFMAOpc = X86::VFNMADDPSr231rY;
24332 case X86::VFNMSUBPDr213rY:
24333 NewFMAOpc = X86::VFNMSUBPDr231rY;
24335 case X86::VFNMSUBPSr213rY:
24336 NewFMAOpc = X86::VFNMSUBPSr231rY;
24338 case X86::VFMADDSUBPDr213rY:
24339 NewFMAOpc = X86::VFMADDSUBPDr231rY;
24341 case X86::VFMADDSUBPSr213rY:
24342 NewFMAOpc = X86::VFMADDSUBPSr231rY;
24344 case X86::VFMSUBADDPDr213rY:
24345 NewFMAOpc = X86::VFMSUBADDPDr231rY;
24347 case X86::VFMSUBADDPSr213rY:
24348 NewFMAOpc = X86::VFMSUBADDPSr231rY;
24351 llvm_unreachable("Unrecognized FMA variant.");
24354 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
24355 MachineInstrBuilder MIB =
24356 BuildMI(MF, MI.getDebugLoc(), TII.get(NewFMAOpc))
24357 .addOperand(MI.getOperand(0))
24358 .addOperand(MI.getOperand(3))
24359 .addOperand(MI.getOperand(2))
24360 .addOperand(MI.getOperand(1));
24361 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
24362 MI.eraseFromParent();
24369 MachineBasicBlock *
24370 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
24371 MachineBasicBlock *BB) const {
24372 switch (MI.getOpcode()) {
24373 default: llvm_unreachable("Unexpected instr type to insert");
24374 case X86::TAILJMPd64:
24375 case X86::TAILJMPr64:
24376 case X86::TAILJMPm64:
24377 case X86::TAILJMPd64_REX:
24378 case X86::TAILJMPr64_REX:
24379 case X86::TAILJMPm64_REX:
24380 llvm_unreachable("TAILJMP64 would not be touched here.");
24381 case X86::TCRETURNdi64:
24382 case X86::TCRETURNri64:
24383 case X86::TCRETURNmi64:
24385 case X86::TLS_addr32:
24386 case X86::TLS_addr64:
24387 case X86::TLS_base_addr32:
24388 case X86::TLS_base_addr64:
24389 return EmitLoweredTLSAddr(MI, BB);
24390 case X86::CATCHRET:
24391 return EmitLoweredCatchRet(MI, BB);
24392 case X86::CATCHPAD:
24393 return EmitLoweredCatchPad(MI, BB);
24394 case X86::SEG_ALLOCA_32:
24395 case X86::SEG_ALLOCA_64:
24396 return EmitLoweredSegAlloca(MI, BB);
24397 case X86::TLSCall_32:
24398 case X86::TLSCall_64:
24399 return EmitLoweredTLSCall(MI, BB);
24400 case X86::CMOV_FR32:
24401 case X86::CMOV_FR64:
24402 case X86::CMOV_FR128:
24403 case X86::CMOV_GR8:
24404 case X86::CMOV_GR16:
24405 case X86::CMOV_GR32:
24406 case X86::CMOV_RFP32:
24407 case X86::CMOV_RFP64:
24408 case X86::CMOV_RFP80:
24409 case X86::CMOV_V2F64:
24410 case X86::CMOV_V2I64:
24411 case X86::CMOV_V4F32:
24412 case X86::CMOV_V4F64:
24413 case X86::CMOV_V4I64:
24414 case X86::CMOV_V16F32:
24415 case X86::CMOV_V8F32:
24416 case X86::CMOV_V8F64:
24417 case X86::CMOV_V8I64:
24418 case X86::CMOV_V8I1:
24419 case X86::CMOV_V16I1:
24420 case X86::CMOV_V32I1:
24421 case X86::CMOV_V64I1:
24422 return EmitLoweredSelect(MI, BB);
24424 case X86::RDFLAGS32:
24425 case X86::RDFLAGS64: {
24426 DebugLoc DL = MI.getDebugLoc();
24427 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
24429 MI.getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
24430 unsigned Pop = MI.getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
24431 MachineInstr *Push = BuildMI(*BB, MI, DL, TII->get(PushF));
24432 // Permit reads of the FLAGS register without it being defined.
24433 // This intrinsic exists to read external processor state in flags, such as
24434 // the trap flag, interrupt flag, and direction flag, none of which are
24435 // modeled by the backend.
24436 Push->getOperand(2).setIsUndef();
24437 BuildMI(*BB, MI, DL, TII->get(Pop), MI.getOperand(0).getReg());
24439 MI.eraseFromParent(); // The pseudo is gone now.
24443 case X86::WRFLAGS32:
24444 case X86::WRFLAGS64: {
24445 DebugLoc DL = MI.getDebugLoc();
24446 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
24448 MI.getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
24450 MI.getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
24451 BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI.getOperand(0).getReg());
24452 BuildMI(*BB, MI, DL, TII->get(PopF));
24454 MI.eraseFromParent(); // The pseudo is gone now.
24458 case X86::RELEASE_FADD32mr:
24459 case X86::RELEASE_FADD64mr:
24460 return EmitLoweredAtomicFP(MI, BB);
24462 case X86::FP32_TO_INT16_IN_MEM:
24463 case X86::FP32_TO_INT32_IN_MEM:
24464 case X86::FP32_TO_INT64_IN_MEM:
24465 case X86::FP64_TO_INT16_IN_MEM:
24466 case X86::FP64_TO_INT32_IN_MEM:
24467 case X86::FP64_TO_INT64_IN_MEM:
24468 case X86::FP80_TO_INT16_IN_MEM:
24469 case X86::FP80_TO_INT32_IN_MEM:
24470 case X86::FP80_TO_INT64_IN_MEM: {
24471 MachineFunction *F = BB->getParent();
24472 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
24473 DebugLoc DL = MI.getDebugLoc();
24475 // Change the floating point control register to use "round towards zero"
24476 // mode when truncating to an integer value.
24477 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
24478 addFrameReference(BuildMI(*BB, MI, DL,
24479 TII->get(X86::FNSTCW16m)), CWFrameIdx);
24481 // Load the old value of the high byte of the control word...
24483 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
24484 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
24487 // Set the high part to be round to zero...
24488 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
24491 // Reload the modified control word now...
24492 addFrameReference(BuildMI(*BB, MI, DL,
24493 TII->get(X86::FLDCW16m)), CWFrameIdx);
24495 // Restore the memory image of control word to original value
24496 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
24499 // Get the X86 opcode to use.
24501 switch (MI.getOpcode()) {
24502 default: llvm_unreachable("illegal opcode!");
24503 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
24504 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
24505 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
24506 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
24507 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
24508 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
24509 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
24510 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
24511 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
24514 X86AddressMode AM = getAddressFromInstr(&MI, 0);
24515 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
24516 .addReg(MI.getOperand(X86::AddrNumOperands).getReg());
24518 // Reload the original control word now.
24519 addFrameReference(BuildMI(*BB, MI, DL,
24520 TII->get(X86::FLDCW16m)), CWFrameIdx);
24522 MI.eraseFromParent(); // The pseudo instruction is gone now.
24525 // String/text processing lowering.
24526 case X86::PCMPISTRM128REG:
24527 case X86::VPCMPISTRM128REG:
24528 case X86::PCMPISTRM128MEM:
24529 case X86::VPCMPISTRM128MEM:
24530 case X86::PCMPESTRM128REG:
24531 case X86::VPCMPESTRM128REG:
24532 case X86::PCMPESTRM128MEM:
24533 case X86::VPCMPESTRM128MEM:
24534 assert(Subtarget.hasSSE42() &&
24535 "Target must have SSE4.2 or AVX features enabled");
24536 return emitPCMPSTRM(MI, BB, Subtarget.getInstrInfo());
24538 // String/text processing lowering.
24539 case X86::PCMPISTRIREG:
24540 case X86::VPCMPISTRIREG:
24541 case X86::PCMPISTRIMEM:
24542 case X86::VPCMPISTRIMEM:
24543 case X86::PCMPESTRIREG:
24544 case X86::VPCMPESTRIREG:
24545 case X86::PCMPESTRIMEM:
24546 case X86::VPCMPESTRIMEM:
24547 assert(Subtarget.hasSSE42() &&
24548 "Target must have SSE4.2 or AVX features enabled");
24549 return emitPCMPSTRI(MI, BB, Subtarget.getInstrInfo());
24551 // Thread synchronization.
24553 return emitMonitor(MI, BB, Subtarget, X86::MONITORrrr);
24554 case X86::MONITORX:
24555 return emitMonitor(MI, BB, Subtarget, X86::MONITORXrrr);
24558 return emitWRPKRU(MI, BB, Subtarget);
24560 return emitRDPKRU(MI, BB, Subtarget);
24563 return emitXBegin(MI, BB, Subtarget.getInstrInfo());
24565 case X86::VASTART_SAVE_XMM_REGS:
24566 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
24568 case X86::VAARG_64:
24569 return EmitVAARG64WithCustomInserter(MI, BB);
24571 case X86::EH_SjLj_SetJmp32:
24572 case X86::EH_SjLj_SetJmp64:
24573 return emitEHSjLjSetJmp(MI, BB);
24575 case X86::EH_SjLj_LongJmp32:
24576 case X86::EH_SjLj_LongJmp64:
24577 return emitEHSjLjLongJmp(MI, BB);
24579 case X86::Int_eh_sjlj_setup_dispatch:
24580 return EmitSjLjDispatchBlock(MI, BB);
24582 case TargetOpcode::STATEPOINT:
24583 // As an implementation detail, STATEPOINT shares the STACKMAP format at
24584 // this point in the process. We diverge later.
24585 return emitPatchPoint(MI, BB);
24587 case TargetOpcode::STACKMAP:
24588 case TargetOpcode::PATCHPOINT:
24589 return emitPatchPoint(MI, BB);
24591 case X86::VFMADDPDr213r:
24592 case X86::VFMADDPSr213r:
24593 case X86::VFMADDSDr213r:
24594 case X86::VFMADDSSr213r:
24595 case X86::VFMSUBPDr213r:
24596 case X86::VFMSUBPSr213r:
24597 case X86::VFMSUBSDr213r:
24598 case X86::VFMSUBSSr213r:
24599 case X86::VFNMADDPDr213r:
24600 case X86::VFNMADDPSr213r:
24601 case X86::VFNMADDSDr213r:
24602 case X86::VFNMADDSSr213r:
24603 case X86::VFNMSUBPDr213r:
24604 case X86::VFNMSUBPSr213r:
24605 case X86::VFNMSUBSDr213r:
24606 case X86::VFNMSUBSSr213r:
24607 case X86::VFMADDSUBPDr213r:
24608 case X86::VFMADDSUBPSr213r:
24609 case X86::VFMSUBADDPDr213r:
24610 case X86::VFMSUBADDPSr213r:
24611 case X86::VFMADDPDr213rY:
24612 case X86::VFMADDPSr213rY:
24613 case X86::VFMSUBPDr213rY:
24614 case X86::VFMSUBPSr213rY:
24615 case X86::VFNMADDPDr213rY:
24616 case X86::VFNMADDPSr213rY:
24617 case X86::VFNMSUBPDr213rY:
24618 case X86::VFNMSUBPSr213rY:
24619 case X86::VFMADDSUBPDr213rY:
24620 case X86::VFMADDSUBPSr213rY:
24621 case X86::VFMSUBADDPDr213rY:
24622 case X86::VFMSUBADDPSr213rY:
24623 return emitFMA3Instr(MI, BB);
24624 case X86::LCMPXCHG8B_SAVE_EBX:
24625 case X86::LCMPXCHG16B_SAVE_RBX: {
24627 MI.getOpcode() == X86::LCMPXCHG8B_SAVE_EBX ? X86::EBX : X86::RBX;
24628 if (!BB->isLiveIn(BasePtr))
24629 BB->addLiveIn(BasePtr);
24635 //===----------------------------------------------------------------------===//
24636 // X86 Optimization Hooks
24637 //===----------------------------------------------------------------------===//
24639 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
24642 const SelectionDAG &DAG,
24643 unsigned Depth) const {
24644 unsigned BitWidth = KnownZero.getBitWidth();
24645 unsigned Opc = Op.getOpcode();
24646 assert((Opc >= ISD::BUILTIN_OP_END ||
24647 Opc == ISD::INTRINSIC_WO_CHAIN ||
24648 Opc == ISD::INTRINSIC_W_CHAIN ||
24649 Opc == ISD::INTRINSIC_VOID) &&
24650 "Should use MaskedValueIsZero if you don't know whether Op"
24651 " is a target node!");
24653 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
24667 // These nodes' second result is a boolean.
24668 if (Op.getResNo() == 0)
24671 case X86ISD::SETCC:
24672 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
24674 case X86ISD::MOVMSK: {
24675 unsigned NumLoBits = Op.getOperand(0).getValueType().getVectorNumElements();
24676 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
24682 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
24684 const SelectionDAG &,
24685 unsigned Depth) const {
24686 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
24687 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
24688 return Op.getValueType().getScalarSizeInBits();
24694 /// Returns true (and the GlobalValue and the offset) if the node is a
24695 /// GlobalAddress + offset.
24696 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
24697 const GlobalValue* &GA,
24698 int64_t &Offset) const {
24699 if (N->getOpcode() == X86ISD::Wrapper) {
24700 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
24701 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
24702 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
24706 return TargetLowering::isGAPlusOffset(N, GA, Offset);
24709 /// Performs shuffle combines for 256-bit vectors.
24710 /// FIXME: This could be expanded to support 512 bit vectors as well.
24711 static SDValue combineShuffle256(SDNode *N, SelectionDAG &DAG,
24712 TargetLowering::DAGCombinerInfo &DCI,
24713 const X86Subtarget &Subtarget) {
24715 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
24716 SDValue V1 = SVOp->getOperand(0);
24717 SDValue V2 = SVOp->getOperand(1);
24718 MVT VT = SVOp->getSimpleValueType(0);
24719 unsigned NumElems = VT.getVectorNumElements();
24721 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
24722 V2.getOpcode() == ISD::CONCAT_VECTORS) {
24726 // V UNDEF BUILD_VECTOR UNDEF
24728 // CONCAT_VECTOR CONCAT_VECTOR
24731 // RESULT: V + zero extended
24733 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
24734 !V2.getOperand(1).isUndef() || !V1.getOperand(1).isUndef())
24737 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
24740 // To match the shuffle mask, the first half of the mask should
24741 // be exactly the first vector, and all the rest a splat with the
24742 // first element of the second one.
24743 for (unsigned i = 0; i != NumElems/2; ++i)
24744 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
24745 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
24748 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
24749 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
24750 if (Ld->hasNUsesOfValue(1, 0)) {
24751 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
24752 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
24754 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
24756 Ld->getPointerInfo(),
24757 Ld->getAlignment(),
24758 false/*isVolatile*/, true/*ReadMem*/,
24759 false/*WriteMem*/);
24761 // Make sure the newly-created LOAD is in the same position as Ld in
24762 // terms of dependency. We create a TokenFactor for Ld and ResNode,
24763 // and update uses of Ld's output chain to use the TokenFactor.
24764 if (Ld->hasAnyUseOfValue(1)) {
24765 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24766 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
24767 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
24768 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
24769 SDValue(ResNode.getNode(), 1));
24772 return DAG.getBitcast(VT, ResNode);
24776 // Emit a zeroed vector and insert the desired subvector on its
24778 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
24779 SDValue InsV = insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
24780 return DCI.CombineTo(N, InsV);
24786 // Attempt to match a combined shuffle mask against supported unary shuffle
24788 // TODO: Investigate sharing more of this with shuffle lowering.
24789 static bool matchUnaryVectorShuffle(MVT SrcVT, ArrayRef<int> Mask,
24790 const X86Subtarget &Subtarget,
24791 unsigned &Shuffle, MVT &ShuffleVT) {
24792 bool FloatDomain = SrcVT.isFloatingPoint() ||
24793 (!Subtarget.hasAVX2() && SrcVT.is256BitVector());
24795 // Match a 128-bit integer vector against a VZEXT_MOVL (MOVQ) instruction.
24796 if (!FloatDomain && SrcVT.is128BitVector() &&
24797 isTargetShuffleEquivalent(Mask, {0, SM_SentinelZero})) {
24798 Shuffle = X86ISD::VZEXT_MOVL;
24799 ShuffleVT = MVT::v2i64;
24803 // Check if we have SSE3 which will let us use MOVDDUP etc. The
24804 // instructions are no slower than UNPCKLPD but has the option to
24805 // fold the input operand into even an unaligned memory load.
24806 if (SrcVT.is128BitVector() && Subtarget.hasSSE3() && FloatDomain) {
24807 if (isTargetShuffleEquivalent(Mask, {0, 0})) {
24808 Shuffle = X86ISD::MOVDDUP;
24809 ShuffleVT = MVT::v2f64;
24812 if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2})) {
24813 Shuffle = X86ISD::MOVSLDUP;
24814 ShuffleVT = MVT::v4f32;
24817 if (isTargetShuffleEquivalent(Mask, {1, 1, 3, 3})) {
24818 Shuffle = X86ISD::MOVSHDUP;
24819 ShuffleVT = MVT::v4f32;
24824 if (SrcVT.is256BitVector() && FloatDomain) {
24825 assert(Subtarget.hasAVX() && "AVX required for 256-bit vector shuffles");
24826 if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2})) {
24827 Shuffle = X86ISD::MOVDDUP;
24828 ShuffleVT = MVT::v4f64;
24831 if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6})) {
24832 Shuffle = X86ISD::MOVSLDUP;
24833 ShuffleVT = MVT::v8f32;
24836 if (isTargetShuffleEquivalent(Mask, {1, 1, 3, 3, 5, 5, 7, 7})) {
24837 Shuffle = X86ISD::MOVSHDUP;
24838 ShuffleVT = MVT::v8f32;
24843 if (SrcVT.is512BitVector() && FloatDomain) {
24844 assert(Subtarget.hasAVX512() &&
24845 "AVX512 required for 512-bit vector shuffles");
24846 if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6})) {
24847 Shuffle = X86ISD::MOVDDUP;
24848 ShuffleVT = MVT::v8f64;
24851 if (isTargetShuffleEquivalent(
24852 Mask, {0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14})) {
24853 Shuffle = X86ISD::MOVSLDUP;
24854 ShuffleVT = MVT::v16f32;
24857 if (isTargetShuffleEquivalent(
24858 Mask, {1, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11, 11, 13, 13, 15, 15})) {
24859 Shuffle = X86ISD::MOVSHDUP;
24860 ShuffleVT = MVT::v16f32;
24865 // Attempt to match against broadcast-from-vector.
24866 if (Subtarget.hasAVX2()) {
24867 unsigned NumElts = Mask.size();
24868 SmallVector<int, 64> BroadcastMask(NumElts, 0);
24869 if (isTargetShuffleEquivalent(Mask, BroadcastMask)) {
24870 unsigned EltSize = SrcVT.getSizeInBits() / NumElts;
24871 ShuffleVT = FloatDomain ? MVT::getFloatingPointVT(EltSize)
24872 : MVT::getIntegerVT(EltSize);
24873 ShuffleVT = MVT::getVectorVT(ShuffleVT, NumElts);
24874 Shuffle = X86ISD::VBROADCAST;
24882 // Attempt to match a combined shuffle mask against supported unary immediate
24883 // permute instructions.
24884 // TODO: Investigate sharing more of this with shuffle lowering.
24885 static bool matchPermuteVectorShuffle(MVT SrcVT, ArrayRef<int> Mask,
24886 const X86Subtarget &Subtarget,
24887 unsigned &Shuffle, MVT &ShuffleVT,
24888 unsigned &PermuteImm) {
24889 // Ensure we don't contain any zero elements.
24890 for (int M : Mask) {
24891 if (M == SM_SentinelZero)
24893 assert(SM_SentinelUndef <= M && M < (int)Mask.size() &&
24894 "Expected unary shuffle");
24897 unsigned MaskScalarSizeInBits = SrcVT.getSizeInBits() / Mask.size();
24898 MVT MaskEltVT = MVT::getIntegerVT(MaskScalarSizeInBits);
24900 // Handle PSHUFLW/PSHUFHW repeated patterns.
24901 if (MaskScalarSizeInBits == 16) {
24902 SmallVector<int, 4> RepeatedMask;
24903 if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
24904 ArrayRef<int> LoMask(Mask.data() + 0, 4);
24905 ArrayRef<int> HiMask(Mask.data() + 4, 4);
24907 // PSHUFLW: permute lower 4 elements only.
24908 if (isUndefOrInRange(LoMask, 0, 4) &&
24909 isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
24910 Shuffle = X86ISD::PSHUFLW;
24911 ShuffleVT = MVT::getVectorVT(MVT::i16, SrcVT.getSizeInBits() / 16);
24912 PermuteImm = getV4X86ShuffleImm(LoMask);
24916 // PSHUFHW: permute upper 4 elements only.
24917 if (isUndefOrInRange(HiMask, 4, 8) &&
24918 isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
24919 // Offset the HiMask so that we can create the shuffle immediate.
24920 int OffsetHiMask[4];
24921 for (int i = 0; i != 4; ++i)
24922 OffsetHiMask[i] = (HiMask[i] < 0 ? HiMask[i] : HiMask[i] - 4);
24924 Shuffle = X86ISD::PSHUFHW;
24925 ShuffleVT = MVT::getVectorVT(MVT::i16, SrcVT.getSizeInBits() / 16);
24926 PermuteImm = getV4X86ShuffleImm(OffsetHiMask);
24935 // We only support permutation of 32/64 bit elements after this.
24936 if (MaskScalarSizeInBits != 32 && MaskScalarSizeInBits != 64)
24939 // AVX introduced the VPERMILPD/VPERMILPS float permutes, before then we
24940 // had to use 2-input SHUFPD/SHUFPS shuffles (not handled here).
24941 bool FloatDomain = SrcVT.isFloatingPoint();
24942 if (FloatDomain && !Subtarget.hasAVX())
24945 // Pre-AVX2 we must use float shuffles on 256-bit vectors.
24946 if (SrcVT.is256BitVector() && !Subtarget.hasAVX2())
24947 FloatDomain = true;
24949 // Check for lane crossing permutes.
24950 if (is128BitLaneCrossingShuffleMask(MaskEltVT, Mask)) {
24951 // PERMPD/PERMQ permutes within a 256-bit vector (AVX2+).
24952 if (Subtarget.hasAVX2() && SrcVT.is256BitVector() && Mask.size() == 4) {
24953 Shuffle = X86ISD::VPERMI;
24954 ShuffleVT = (FloatDomain ? MVT::v4f64 : MVT::v4i64);
24955 PermuteImm = getV4X86ShuffleImm(Mask);
24958 if (Subtarget.hasAVX512() && SrcVT.is512BitVector() && Mask.size() == 8) {
24959 SmallVector<int, 4> RepeatedMask;
24960 if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask)) {
24961 Shuffle = X86ISD::VPERMI;
24962 ShuffleVT = (FloatDomain ? MVT::v8f64 : MVT::v8i64);
24963 PermuteImm = getV4X86ShuffleImm(RepeatedMask);
24970 // VPERMILPD can permute with a non-repeating shuffle.
24971 if (FloatDomain && MaskScalarSizeInBits == 64) {
24972 Shuffle = X86ISD::VPERMILPI;
24973 ShuffleVT = MVT::getVectorVT(MVT::f64, Mask.size());
24975 for (int i = 0, e = Mask.size(); i != e; ++i) {
24977 if (M == SM_SentinelUndef)
24979 assert(((M / 2) == (i / 2)) && "Out of range shuffle mask index");
24980 PermuteImm |= (M & 1) << i;
24985 // We need a repeating shuffle mask for VPERMILPS/PSHUFD.
24986 SmallVector<int, 4> RepeatedMask;
24987 if (!is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask))
24990 // Narrow the repeated mask for 32-bit element permutes.
24991 SmallVector<int, 4> WordMask = RepeatedMask;
24992 if (MaskScalarSizeInBits == 64)
24993 scaleShuffleMask(2, RepeatedMask, WordMask);
24995 Shuffle = (FloatDomain ? X86ISD::VPERMILPI : X86ISD::PSHUFD);
24996 ShuffleVT = (FloatDomain ? MVT::f32 : MVT::i32);
24997 ShuffleVT = MVT::getVectorVT(ShuffleVT, SrcVT.getSizeInBits() / 32);
24998 PermuteImm = getV4X86ShuffleImm(WordMask);
25002 // Attempt to match a combined unary shuffle mask against supported binary
25003 // shuffle instructions.
25004 // TODO: Investigate sharing more of this with shuffle lowering.
25005 static bool matchBinaryVectorShuffle(MVT SrcVT, ArrayRef<int> Mask,
25006 unsigned &Shuffle, MVT &ShuffleVT) {
25007 bool FloatDomain = SrcVT.isFloatingPoint();
25009 if (SrcVT.is128BitVector()) {
25010 if (isTargetShuffleEquivalent(Mask, {0, 0}) && FloatDomain) {
25011 Shuffle = X86ISD::MOVLHPS;
25012 ShuffleVT = MVT::v4f32;
25015 if (isTargetShuffleEquivalent(Mask, {1, 1}) && FloatDomain) {
25016 Shuffle = X86ISD::MOVHLPS;
25017 ShuffleVT = MVT::v4f32;
25020 if (isTargetShuffleEquivalent(Mask, {0, 0, 1, 1}) && FloatDomain) {
25021 Shuffle = X86ISD::UNPCKL;
25022 ShuffleVT = MVT::v4f32;
25025 if (isTargetShuffleEquivalent(Mask, {2, 2, 3, 3}) && FloatDomain) {
25026 Shuffle = X86ISD::UNPCKH;
25027 ShuffleVT = MVT::v4f32;
25030 if (isTargetShuffleEquivalent(Mask, {0, 0, 1, 1, 2, 2, 3, 3}) ||
25031 isTargetShuffleEquivalent(
25032 Mask, {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7})) {
25033 Shuffle = X86ISD::UNPCKL;
25034 ShuffleVT = Mask.size() == 8 ? MVT::v8i16 : MVT::v16i8;
25037 if (isTargetShuffleEquivalent(Mask, {4, 4, 5, 5, 6, 6, 7, 7}) ||
25038 isTargetShuffleEquivalent(Mask, {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13,
25039 13, 14, 14, 15, 15})) {
25040 Shuffle = X86ISD::UNPCKH;
25041 ShuffleVT = Mask.size() == 8 ? MVT::v8i16 : MVT::v16i8;
25049 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
25052 /// This is the leaf of the recursive combine below. When we have found some
25053 /// chain of single-use x86 shuffle instructions and accumulated the combined
25054 /// shuffle mask represented by them, this will try to pattern match that mask
25055 /// into either a single instruction if there is a special purpose instruction
25056 /// for this operation, or into a PSHUFB instruction which is a fully general
25057 /// instruction but should only be used to replace chains over a certain depth.
25058 static bool combineX86ShuffleChain(SDValue Input, SDValue Root,
25059 ArrayRef<int> BaseMask, int Depth,
25060 bool HasVariableMask, SelectionDAG &DAG,
25061 TargetLowering::DAGCombinerInfo &DCI,
25062 const X86Subtarget &Subtarget) {
25063 assert(!BaseMask.empty() && "Cannot combine an empty shuffle mask!");
25065 // Find the operand that enters the chain. Note that multiple uses are OK
25066 // here, we're not going to remove the operand we find.
25067 Input = peekThroughBitcasts(Input);
25069 MVT VT = Input.getSimpleValueType();
25070 MVT RootVT = Root.getSimpleValueType();
25075 unsigned NumBaseMaskElts = BaseMask.size();
25076 if (NumBaseMaskElts == 1) {
25077 assert(BaseMask[0] == 0 && "Invalid shuffle index found!");
25078 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
25083 unsigned RootSizeInBits = RootVT.getSizeInBits();
25084 unsigned BaseMaskEltSizeInBits = RootSizeInBits / NumBaseMaskElts;
25086 // Don't combine if we are a AVX512/EVEX target and the mask element size
25087 // is different from the root element size - this would prevent writemasks
25088 // from being reused.
25089 // TODO - this currently prevents all lane shuffles from occurring.
25090 // TODO - check for writemasks usage instead of always preventing combining.
25091 // TODO - attempt to narrow Mask back to writemask size.
25092 if (RootVT.getScalarSizeInBits() != BaseMaskEltSizeInBits &&
25093 (RootSizeInBits == 512 ||
25094 (Subtarget.hasVLX() && RootSizeInBits >= 128))) {
25098 // TODO - handle 128/256-bit lane shuffles of 512-bit vectors.
25100 // Handle 128-bit lane shuffles of 256-bit vectors.
25101 if (VT.is256BitVector() && NumBaseMaskElts == 2 &&
25102 !isSequentialOrUndefOrZeroInRange(BaseMask, 0, 2, 0)) {
25103 if (Depth == 1 && Root.getOpcode() == X86ISD::VPERM2X128)
25104 return false; // Nothing to do!
25105 MVT ShuffleVT = (VT.isFloatingPoint() || !Subtarget.hasAVX2() ? MVT::v4f64
25107 unsigned PermMask = 0;
25108 PermMask |= ((BaseMask[0] < 0 ? 0x8 : (BaseMask[0] & 1)) << 0);
25109 PermMask |= ((BaseMask[1] < 0 ? 0x8 : (BaseMask[1] & 1)) << 4);
25111 Res = DAG.getBitcast(ShuffleVT, Input);
25112 DCI.AddToWorklist(Res.getNode());
25113 Res = DAG.getNode(X86ISD::VPERM2X128, DL, ShuffleVT, Res,
25114 DAG.getUNDEF(ShuffleVT),
25115 DAG.getConstant(PermMask, DL, MVT::i8));
25116 DCI.AddToWorklist(Res.getNode());
25117 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Res),
25122 // For masks that have been widened to 128-bit elements or more,
25123 // narrow back down to 64-bit elements.
25124 SmallVector<int, 64> Mask;
25125 if (BaseMaskEltSizeInBits > 64) {
25126 assert((BaseMaskEltSizeInBits % 64) == 0 && "Illegal mask size");
25127 int MaskScale = BaseMaskEltSizeInBits / 64;
25128 scaleShuffleMask(MaskScale, BaseMask, Mask);
25130 Mask = SmallVector<int, 64>(BaseMask.begin(), BaseMask.end());
25133 unsigned NumMaskElts = Mask.size();
25134 unsigned MaskEltSizeInBits = RootSizeInBits / NumMaskElts;
25136 // Determine the effective mask value type.
25138 (VT.isFloatingPoint() || (VT.is256BitVector() && !Subtarget.hasAVX2())) &&
25139 (32 <= MaskEltSizeInBits);
25140 MVT MaskVT = FloatDomain ? MVT::getFloatingPointVT(MaskEltSizeInBits)
25141 : MVT::getIntegerVT(MaskEltSizeInBits);
25142 MaskVT = MVT::getVectorVT(MaskVT, NumMaskElts);
25144 // Attempt to match the mask against known shuffle patterns.
25146 unsigned Shuffle, PermuteImm;
25148 if (matchUnaryVectorShuffle(VT, Mask, Subtarget, Shuffle, ShuffleVT)) {
25149 if (Depth == 1 && Root.getOpcode() == Shuffle)
25150 return false; // Nothing to do!
25151 Res = DAG.getBitcast(ShuffleVT, Input);
25152 DCI.AddToWorklist(Res.getNode());
25153 Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res);
25154 DCI.AddToWorklist(Res.getNode());
25155 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Res),
25160 if (matchPermuteVectorShuffle(VT, Mask, Subtarget, Shuffle, ShuffleVT,
25162 if (Depth == 1 && Root.getOpcode() == Shuffle)
25163 return false; // Nothing to do!
25164 Res = DAG.getBitcast(ShuffleVT, Input);
25165 DCI.AddToWorklist(Res.getNode());
25166 Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res,
25167 DAG.getConstant(PermuteImm, DL, MVT::i8));
25168 DCI.AddToWorklist(Res.getNode());
25169 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Res),
25174 if (matchBinaryVectorShuffle(VT, Mask, Shuffle, ShuffleVT)) {
25175 if (Depth == 1 && Root.getOpcode() == Shuffle)
25176 return false; // Nothing to do!
25177 Res = DAG.getBitcast(ShuffleVT, Input);
25178 DCI.AddToWorklist(Res.getNode());
25179 Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res, Res);
25180 DCI.AddToWorklist(Res.getNode());
25181 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Res),
25186 // Attempt to blend with zero.
25187 if (NumMaskElts <= 8 &&
25188 ((Subtarget.hasSSE41() && VT.is128BitVector()) ||
25189 (Subtarget.hasAVX() && VT.is256BitVector()))) {
25190 // Convert VT to a type compatible with X86ISD::BLENDI.
25191 // TODO - add 16i16 support (requires lane duplication).
25192 MVT ShuffleVT = MaskVT;
25193 if (Subtarget.hasAVX2()) {
25194 if (ShuffleVT == MVT::v4i64)
25195 ShuffleVT = MVT::v8i32;
25196 else if (ShuffleVT == MVT::v2i64)
25197 ShuffleVT = MVT::v4i32;
25199 if (ShuffleVT == MVT::v2i64 || ShuffleVT == MVT::v4i32)
25200 ShuffleVT = MVT::v8i16;
25201 else if (ShuffleVT == MVT::v4i64)
25202 ShuffleVT = MVT::v4f64;
25203 else if (ShuffleVT == MVT::v8i32)
25204 ShuffleVT = MVT::v8f32;
25207 if (isSequentialOrUndefOrZeroInRange(Mask, /*Pos*/ 0, /*Size*/ NumMaskElts,
25209 NumMaskElts <= ShuffleVT.getVectorNumElements()) {
25210 unsigned BlendMask = 0;
25211 unsigned ShuffleSize = ShuffleVT.getVectorNumElements();
25212 unsigned MaskRatio = ShuffleSize / NumMaskElts;
25214 if (Depth == 1 && Root.getOpcode() == X86ISD::BLENDI)
25217 for (unsigned i = 0; i != ShuffleSize; ++i)
25218 if (Mask[i / MaskRatio] < 0)
25219 BlendMask |= 1u << i;
25221 SDValue Zero = getZeroVector(ShuffleVT, Subtarget, DAG, DL);
25222 Res = DAG.getBitcast(ShuffleVT, Input);
25223 DCI.AddToWorklist(Res.getNode());
25224 Res = DAG.getNode(X86ISD::BLENDI, DL, ShuffleVT, Res, Zero,
25225 DAG.getConstant(BlendMask, DL, MVT::i8));
25226 DCI.AddToWorklist(Res.getNode());
25227 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Res),
25233 // Attempt to combine to INSERTPS.
25234 if (Subtarget.hasSSE41() && NumMaskElts == 4 &&
25235 (VT == MVT::v2f64 || VT == MVT::v4f32)) {
25236 SmallBitVector Zeroable(4, false);
25237 for (unsigned i = 0; i != NumMaskElts; ++i)
25239 Zeroable[i] = true;
25241 unsigned InsertPSMask;
25242 SDValue V1 = Input, V2 = Input;
25243 if (Zeroable.any() && matchVectorShuffleAsInsertPS(V1, V2, InsertPSMask,
25244 Zeroable, Mask, DAG)) {
25245 if (Depth == 1 && Root.getOpcode() == X86ISD::INSERTPS)
25246 return false; // Nothing to do!
25247 V1 = DAG.getBitcast(MVT::v4f32, V1);
25248 DCI.AddToWorklist(V1.getNode());
25249 V2 = DAG.getBitcast(MVT::v4f32, V2);
25250 DCI.AddToWorklist(V2.getNode());
25251 Res = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
25252 DAG.getConstant(InsertPSMask, DL, MVT::i8));
25253 DCI.AddToWorklist(Res.getNode());
25254 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Res),
25260 // Don't try to re-form single instruction chains under any circumstances now
25261 // that we've done encoding canonicalization for them.
25265 if (is128BitLaneCrossingShuffleMask(MaskVT, Mask))
25268 bool MaskContainsZeros =
25269 llvm::any_of(Mask, [](int M) { return M == SM_SentinelZero; });
25271 // If we have a single input shuffle with different shuffle patterns in the
25272 // the 128-bit lanes use the variable mask to VPERMILPS.
25273 // TODO Combine other mask types at higher depths.
25274 if (HasVariableMask && !MaskContainsZeros &&
25275 ((MaskVT == MVT::v8f32 && Subtarget.hasAVX()) ||
25276 (MaskVT == MVT::v16f32 && Subtarget.hasAVX512()))) {
25277 SmallVector<SDValue, 16> VPermIdx;
25278 for (int M : Mask) {
25280 M < 0 ? DAG.getUNDEF(MVT::i32) : DAG.getConstant(M % 4, DL, MVT::i32);
25281 VPermIdx.push_back(Idx);
25283 MVT VPermMaskVT = MVT::getVectorVT(MVT::i32, NumMaskElts);
25284 SDValue VPermMask = DAG.getBuildVector(VPermMaskVT, DL, VPermIdx);
25285 DCI.AddToWorklist(VPermMask.getNode());
25286 Res = DAG.getBitcast(MaskVT, Input);
25287 DCI.AddToWorklist(Res.getNode());
25288 Res = DAG.getNode(X86ISD::VPERMILPV, DL, MaskVT, Res, VPermMask);
25289 DCI.AddToWorklist(Res.getNode());
25290 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Res),
25295 // If we have 3 or more shuffle instructions or a chain involving a variable
25296 // mask, we can replace them with a single PSHUFB instruction profitably.
25297 // Intel's manuals suggest only using PSHUFB if doing so replacing 5
25298 // instructions, but in practice PSHUFB tends to be *very* fast so we're
25299 // more aggressive.
25300 if ((Depth >= 3 || HasVariableMask) &&
25301 ((VT.is128BitVector() && Subtarget.hasSSSE3()) ||
25302 (VT.is256BitVector() && Subtarget.hasAVX2()) ||
25303 (VT.is512BitVector() && Subtarget.hasBWI()))) {
25304 SmallVector<SDValue, 16> PSHUFBMask;
25305 int NumBytes = VT.getSizeInBits() / 8;
25306 int Ratio = NumBytes / NumMaskElts;
25307 for (int i = 0; i < NumBytes; ++i) {
25308 int M = Mask[i / Ratio];
25309 if (M == SM_SentinelUndef) {
25310 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
25313 if (M == SM_SentinelZero) {
25314 PSHUFBMask.push_back(DAG.getConstant(255, DL, MVT::i8));
25317 M = Ratio * M + i % Ratio;
25318 assert ((M / 16) == (i / 16) && "Lane crossing detected");
25319 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
25321 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
25322 Res = DAG.getBitcast(ByteVT, Input);
25323 DCI.AddToWorklist(Res.getNode());
25324 SDValue PSHUFBMaskOp = DAG.getBuildVector(ByteVT, DL, PSHUFBMask);
25325 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
25326 Res = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Res, PSHUFBMaskOp);
25327 DCI.AddToWorklist(Res.getNode());
25328 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Res),
25333 // Failed to find any combines.
25337 /// \brief Fully generic combining of x86 shuffle instructions.
25339 /// This should be the last combine run over the x86 shuffle instructions. Once
25340 /// they have been fully optimized, this will recursively consider all chains
25341 /// of single-use shuffle instructions, build a generic model of the cumulative
25342 /// shuffle operation, and check for simpler instructions which implement this
25343 /// operation. We use this primarily for two purposes:
25345 /// 1) Collapse generic shuffles to specialized single instructions when
25346 /// equivalent. In most cases, this is just an encoding size win, but
25347 /// sometimes we will collapse multiple generic shuffles into a single
25348 /// special-purpose shuffle.
25349 /// 2) Look for sequences of shuffle instructions with 3 or more total
25350 /// instructions, and replace them with the slightly more expensive SSSE3
25351 /// PSHUFB instruction if available. We do this as the last combining step
25352 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
25353 /// a suitable short sequence of other instructions. The PHUFB will either
25354 /// use a register or have to read from memory and so is slightly (but only
25355 /// slightly) more expensive than the other shuffle instructions.
25357 /// Because this is inherently a quadratic operation (for each shuffle in
25358 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
25359 /// This should never be an issue in practice as the shuffle lowering doesn't
25360 /// produce sequences of more than 8 instructions.
25362 /// FIXME: We will currently miss some cases where the redundant shuffling
25363 /// would simplify under the threshold for PSHUFB formation because of
25364 /// combine-ordering. To fix this, we should do the redundant instruction
25365 /// combining in this recursive walk.
25366 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
25367 ArrayRef<int> RootMask,
25368 int Depth, bool HasVariableMask,
25370 TargetLowering::DAGCombinerInfo &DCI,
25371 const X86Subtarget &Subtarget) {
25372 // Bound the depth of our recursive combine because this is ultimately
25373 // quadratic in nature.
25377 // Directly rip through bitcasts to find the underlying operand.
25378 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
25379 Op = Op.getOperand(0);
25381 MVT VT = Op.getSimpleValueType();
25382 if (!VT.isVector())
25383 return false; // Bail if we hit a non-vector.
25385 assert(Root.getSimpleValueType().isVector() &&
25386 "Shuffles operate on vector types!");
25387 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
25388 "Can only combine shuffles of the same vector register size.");
25390 // Extract target shuffle mask and resolve sentinels and inputs.
25391 SDValue Input0, Input1;
25392 SmallVector<int, 16> OpMask;
25393 if (!resolveTargetShuffleInputs(Op, Input0, Input1, OpMask))
25396 assert(VT.getVectorNumElements() == OpMask.size() &&
25397 "Different mask size from vector size!");
25398 assert(((RootMask.size() > OpMask.size() &&
25399 RootMask.size() % OpMask.size() == 0) ||
25400 (OpMask.size() > RootMask.size() &&
25401 OpMask.size() % RootMask.size() == 0) ||
25402 OpMask.size() == RootMask.size()) &&
25403 "The smaller number of elements must divide the larger.");
25404 int MaskWidth = std::max<int>(OpMask.size(), RootMask.size());
25405 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
25406 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
25407 assert(((RootRatio == 1 && OpRatio == 1) ||
25408 (RootRatio == 1) != (OpRatio == 1)) &&
25409 "Must not have a ratio for both incoming and op masks!");
25411 SmallVector<int, 16> Mask;
25412 Mask.reserve(MaskWidth);
25414 // Merge this shuffle operation's mask into our accumulated mask. Note that
25415 // this shuffle's mask will be the first applied to the input, followed by the
25416 // root mask to get us all the way to the root value arrangement. The reason
25417 // for this order is that we are recursing up the operation chain.
25418 for (int i = 0; i < MaskWidth; ++i) {
25419 int RootIdx = i / RootRatio;
25420 if (RootMask[RootIdx] < 0) {
25421 // This is a zero or undef lane, we're done.
25422 Mask.push_back(RootMask[RootIdx]);
25426 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
25427 int OpIdx = RootMaskedIdx / OpRatio;
25428 if (OpMask[OpIdx] < 0) {
25429 // The incoming lanes are zero or undef, it doesn't matter which ones we
25431 Mask.push_back(OpMask[OpIdx]);
25435 // Ok, we have non-zero lanes, map them through.
25436 Mask.push_back(OpMask[OpIdx] * OpRatio +
25437 RootMaskedIdx % OpRatio);
25440 // Handle the all undef/zero cases early.
25441 if (llvm::all_of(Mask, [](int Idx) { return Idx == SM_SentinelUndef; })) {
25442 DCI.CombineTo(Root.getNode(), DAG.getUNDEF(Root.getValueType()));
25445 if (llvm::all_of(Mask, [](int Idx) { return Idx < 0; })) {
25446 // TODO - should we handle the mixed zero/undef case as well? Just returning
25447 // a zero mask will lose information on undef elements possibly reducing
25448 // future combine possibilities.
25449 DCI.CombineTo(Root.getNode(), getZeroVector(Root.getSimpleValueType(),
25450 Subtarget, DAG, SDLoc(Root)));
25454 int MaskSize = Mask.size();
25455 bool UseInput0 = std::any_of(Mask.begin(), Mask.end(),
25456 [MaskSize](int Idx) { return 0 <= Idx && Idx < MaskSize; });
25457 bool UseInput1 = std::any_of(Mask.begin(), Mask.end(),
25458 [MaskSize](int Idx) { return MaskSize <= Idx; });
25460 // At the moment we can only combine unary shuffle mask cases.
25461 if (UseInput0 && UseInput1)
25463 else if (UseInput1) {
25464 std::swap(Input0, Input1);
25465 ShuffleVectorSDNode::commuteMask(Mask);
25468 assert(Input0 && "Shuffle with no inputs detected");
25470 HasVariableMask |= isTargetShuffleVariableMask(Op.getOpcode());
25472 // See if we can recurse into Input0 (if it's a target shuffle).
25473 if (Op->isOnlyUserOf(Input0.getNode()) &&
25474 combineX86ShufflesRecursively(Input0, Root, Mask, Depth + 1,
25475 HasVariableMask, DAG, DCI, Subtarget))
25478 // Minor canonicalization of the accumulated shuffle mask to make it easier
25479 // to match below. All this does is detect masks with sequential pairs of
25480 // elements, and shrink them to the half-width mask. It does this in a loop
25481 // so it will reduce the size of the mask to the minimal width mask which
25482 // performs an equivalent shuffle.
25483 SmallVector<int, 16> WidenedMask;
25484 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
25485 Mask = std::move(WidenedMask);
25488 return combineX86ShuffleChain(Input0, Root, Mask, Depth, HasVariableMask, DAG,
25492 /// \brief Get the PSHUF-style mask from PSHUF node.
25494 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
25495 /// PSHUF-style masks that can be reused with such instructions.
25496 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
25497 MVT VT = N.getSimpleValueType();
25498 SmallVector<int, 4> Mask;
25499 SmallVector<SDValue, 2> Ops;
25502 getTargetShuffleMask(N.getNode(), VT, false, Ops, Mask, IsUnary);
25506 // If we have more than 128-bits, only the low 128-bits of shuffle mask
25507 // matter. Check that the upper masks are repeats and remove them.
25508 if (VT.getSizeInBits() > 128) {
25509 int LaneElts = 128 / VT.getScalarSizeInBits();
25511 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
25512 for (int j = 0; j < LaneElts; ++j)
25513 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
25514 "Mask doesn't repeat in high 128-bit lanes!");
25516 Mask.resize(LaneElts);
25519 switch (N.getOpcode()) {
25520 case X86ISD::PSHUFD:
25522 case X86ISD::PSHUFLW:
25525 case X86ISD::PSHUFHW:
25526 Mask.erase(Mask.begin(), Mask.begin() + 4);
25527 for (int &M : Mask)
25531 llvm_unreachable("No valid shuffle instruction found!");
25535 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
25537 /// We walk up the chain and look for a combinable shuffle, skipping over
25538 /// shuffles that we could hoist this shuffle's transformation past without
25539 /// altering anything.
25541 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
25543 TargetLowering::DAGCombinerInfo &DCI) {
25544 assert(N.getOpcode() == X86ISD::PSHUFD &&
25545 "Called with something other than an x86 128-bit half shuffle!");
25548 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
25549 // of the shuffles in the chain so that we can form a fresh chain to replace
25551 SmallVector<SDValue, 8> Chain;
25552 SDValue V = N.getOperand(0);
25553 for (; V.hasOneUse(); V = V.getOperand(0)) {
25554 switch (V.getOpcode()) {
25556 return SDValue(); // Nothing combined!
25559 // Skip bitcasts as we always know the type for the target specific
25563 case X86ISD::PSHUFD:
25564 // Found another dword shuffle.
25567 case X86ISD::PSHUFLW:
25568 // Check that the low words (being shuffled) are the identity in the
25569 // dword shuffle, and the high words are self-contained.
25570 if (Mask[0] != 0 || Mask[1] != 1 ||
25571 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
25574 Chain.push_back(V);
25577 case X86ISD::PSHUFHW:
25578 // Check that the high words (being shuffled) are the identity in the
25579 // dword shuffle, and the low words are self-contained.
25580 if (Mask[2] != 2 || Mask[3] != 3 ||
25581 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
25584 Chain.push_back(V);
25587 case X86ISD::UNPCKL:
25588 case X86ISD::UNPCKH:
25589 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
25590 // shuffle into a preceding word shuffle.
25591 if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
25592 V.getSimpleValueType().getVectorElementType() != MVT::i16)
25595 // Search for a half-shuffle which we can combine with.
25596 unsigned CombineOp =
25597 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
25598 if (V.getOperand(0) != V.getOperand(1) ||
25599 !V->isOnlyUserOf(V.getOperand(0).getNode()))
25601 Chain.push_back(V);
25602 V = V.getOperand(0);
25604 switch (V.getOpcode()) {
25606 return SDValue(); // Nothing to combine.
25608 case X86ISD::PSHUFLW:
25609 case X86ISD::PSHUFHW:
25610 if (V.getOpcode() == CombineOp)
25613 Chain.push_back(V);
25617 V = V.getOperand(0);
25621 } while (V.hasOneUse());
25624 // Break out of the loop if we break out of the switch.
25628 if (!V.hasOneUse())
25629 // We fell out of the loop without finding a viable combining instruction.
25632 // Merge this node's mask and our incoming mask.
25633 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
25634 for (int &M : Mask)
25636 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
25637 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
25639 // Rebuild the chain around this new shuffle.
25640 while (!Chain.empty()) {
25641 SDValue W = Chain.pop_back_val();
25643 if (V.getValueType() != W.getOperand(0).getValueType())
25644 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
25646 switch (W.getOpcode()) {
25648 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
25650 case X86ISD::UNPCKL:
25651 case X86ISD::UNPCKH:
25652 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
25655 case X86ISD::PSHUFD:
25656 case X86ISD::PSHUFLW:
25657 case X86ISD::PSHUFHW:
25658 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
25662 if (V.getValueType() != N.getValueType())
25663 V = DAG.getBitcast(N.getValueType(), V);
25665 // Return the new chain to replace N.
25669 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
25672 /// We walk up the chain, skipping shuffles of the other half and looking
25673 /// through shuffles which switch halves trying to find a shuffle of the same
25674 /// pair of dwords.
25675 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
25677 TargetLowering::DAGCombinerInfo &DCI) {
25679 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
25680 "Called with something other than an x86 128-bit half shuffle!");
25682 unsigned CombineOpcode = N.getOpcode();
25684 // Walk up a single-use chain looking for a combinable shuffle.
25685 SDValue V = N.getOperand(0);
25686 for (; V.hasOneUse(); V = V.getOperand(0)) {
25687 switch (V.getOpcode()) {
25689 return false; // Nothing combined!
25692 // Skip bitcasts as we always know the type for the target specific
25696 case X86ISD::PSHUFLW:
25697 case X86ISD::PSHUFHW:
25698 if (V.getOpcode() == CombineOpcode)
25701 // Other-half shuffles are no-ops.
25704 // Break out of the loop if we break out of the switch.
25708 if (!V.hasOneUse())
25709 // We fell out of the loop without finding a viable combining instruction.
25712 // Combine away the bottom node as its shuffle will be accumulated into
25713 // a preceding shuffle.
25714 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
25716 // Record the old value.
25719 // Merge this node's mask and our incoming mask (adjusted to account for all
25720 // the pshufd instructions encountered).
25721 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
25722 for (int &M : Mask)
25724 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
25725 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
25727 // Check that the shuffles didn't cancel each other out. If not, we need to
25728 // combine to the new one.
25730 // Replace the combinable shuffle with the combined one, updating all users
25731 // so that we re-evaluate the chain here.
25732 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
25737 /// \brief Try to combine x86 target specific shuffles.
25738 static SDValue combineTargetShuffle(SDValue N, SelectionDAG &DAG,
25739 TargetLowering::DAGCombinerInfo &DCI,
25740 const X86Subtarget &Subtarget) {
25742 MVT VT = N.getSimpleValueType();
25743 SmallVector<int, 4> Mask;
25745 switch (N.getOpcode()) {
25746 case X86ISD::PSHUFD:
25747 case X86ISD::PSHUFLW:
25748 case X86ISD::PSHUFHW:
25749 Mask = getPSHUFShuffleMask(N);
25750 assert(Mask.size() == 4);
25752 case X86ISD::UNPCKL: {
25753 // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
25754 // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
25755 // moves upper half elements into the lower half part. For example:
25757 // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
25759 // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
25761 // will be combined to:
25763 // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
25765 // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
25766 // happen due to advanced instructions.
25767 if (!VT.is128BitVector())
25770 auto Op0 = N.getOperand(0);
25771 auto Op1 = N.getOperand(1);
25772 if (Op0.isUndef() && Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
25773 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
25775 unsigned NumElts = VT.getVectorNumElements();
25776 SmallVector<int, 8> ExpectedMask(NumElts, -1);
25777 std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
25780 auto ShufOp = Op1.getOperand(0);
25781 if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
25782 return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
25786 case X86ISD::BLENDI: {
25787 SDValue V0 = N->getOperand(0);
25788 SDValue V1 = N->getOperand(1);
25789 assert(VT == V0.getSimpleValueType() && VT == V1.getSimpleValueType() &&
25790 "Unexpected input vector types");
25792 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25793 // operands and changing the mask to 1. This saves us a bunch of
25794 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25795 // x86InstrInfo knows how to commute this back after instruction selection
25796 // if it would help register allocation.
25798 // TODO: If optimizing for size or a processor that doesn't suffer from
25799 // partial register update stalls, this should be transformed into a MOVSD
25800 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25802 if (VT == MVT::v2f64)
25803 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25804 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25805 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25806 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25809 // Attempt to merge blend(insertps(x,y),zero).
25810 if (V0.getOpcode() == X86ISD::INSERTPS ||
25811 V1.getOpcode() == X86ISD::INSERTPS) {
25812 assert(VT == MVT::v4f32 && "INSERTPS ValueType must be MVT::v4f32");
25814 // Determine which elements are known to be zero.
25815 SmallVector<int, 8> TargetMask;
25816 SmallVector<SDValue, 2> BlendOps;
25817 if (!setTargetShuffleZeroElements(N, TargetMask, BlendOps))
25820 // Helper function to take inner insertps node and attempt to
25821 // merge the blend with zero into its zero mask.
25822 auto MergeInsertPSAndBlend = [&](SDValue V, int Offset) {
25823 if (V.getOpcode() != X86ISD::INSERTPS)
25825 SDValue Op0 = V.getOperand(0);
25826 SDValue Op1 = V.getOperand(1);
25827 SDValue Op2 = V.getOperand(2);
25828 unsigned InsertPSMask = cast<ConstantSDNode>(Op2)->getZExtValue();
25830 // Check each element of the blend node's target mask - must either
25831 // be zeroable (and update the zero mask) or selects the element from
25832 // the inner insertps node.
25833 for (int i = 0; i != 4; ++i)
25834 if (TargetMask[i] < 0)
25835 InsertPSMask |= (1u << i);
25836 else if (TargetMask[i] != (i + Offset))
25838 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, Op0, Op1,
25839 DAG.getConstant(InsertPSMask, DL, MVT::i8));
25842 if (SDValue V = MergeInsertPSAndBlend(V0, 0))
25844 if (SDValue V = MergeInsertPSAndBlend(V1, 4))
25849 case X86ISD::INSERTPS: {
25850 assert(VT == MVT::v4f32 && "INSERTPS ValueType must be MVT::v4f32");
25851 SDValue Op0 = N.getOperand(0);
25852 SDValue Op1 = N.getOperand(1);
25853 SDValue Op2 = N.getOperand(2);
25854 unsigned InsertPSMask = cast<ConstantSDNode>(Op2)->getZExtValue();
25855 unsigned SrcIdx = (InsertPSMask >> 6) & 0x3;
25856 unsigned DstIdx = (InsertPSMask >> 4) & 0x3;
25857 unsigned ZeroMask = InsertPSMask & 0xF;
25859 // If we zero out all elements from Op0 then we don't need to reference it.
25860 if (((ZeroMask | (1u << DstIdx)) == 0xF) && !Op0.isUndef())
25861 return DAG.getNode(X86ISD::INSERTPS, DL, VT, DAG.getUNDEF(VT), Op1,
25862 DAG.getConstant(InsertPSMask, DL, MVT::i8));
25864 // If we zero out the element from Op1 then we don't need to reference it.
25865 if ((ZeroMask & (1u << DstIdx)) && !Op1.isUndef())
25866 return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
25867 DAG.getConstant(InsertPSMask, DL, MVT::i8));
25869 // Attempt to merge insertps Op1 with an inner target shuffle node.
25870 SmallVector<int, 8> TargetMask1;
25871 SmallVector<SDValue, 2> Ops1;
25872 if (setTargetShuffleZeroElements(Op1, TargetMask1, Ops1)) {
25873 int M = TargetMask1[SrcIdx];
25874 if (isUndefOrZero(M)) {
25875 // Zero/UNDEF insertion - zero out element and remove dependency.
25876 InsertPSMask |= (1u << DstIdx);
25877 return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
25878 DAG.getConstant(InsertPSMask, DL, MVT::i8));
25880 // Update insertps mask srcidx and reference the source input directly.
25881 assert(0 <= M && M < 8 && "Shuffle index out of range");
25882 InsertPSMask = (InsertPSMask & 0x3f) | ((M & 0x3) << 6);
25883 Op1 = Ops1[M < 4 ? 0 : 1];
25884 return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
25885 DAG.getConstant(InsertPSMask, DL, MVT::i8));
25888 // Attempt to merge insertps Op0 with an inner target shuffle node.
25889 SmallVector<int, 8> TargetMask0;
25890 SmallVector<SDValue, 2> Ops0;
25891 if (!setTargetShuffleZeroElements(Op0, TargetMask0, Ops0))
25894 bool Updated = false;
25895 bool UseInput00 = false;
25896 bool UseInput01 = false;
25897 for (int i = 0; i != 4; ++i) {
25898 int M = TargetMask0[i];
25899 if ((InsertPSMask & (1u << i)) || (i == (int)DstIdx)) {
25900 // No change if element is already zero or the inserted element.
25902 } else if (isUndefOrZero(M)) {
25903 // If the target mask is undef/zero then we must zero the element.
25904 InsertPSMask |= (1u << i);
25909 // The input vector element must be inline.
25910 if (M != i && M != (i + 4))
25913 // Determine which inputs of the target shuffle we're using.
25914 UseInput00 |= (0 <= M && M < 4);
25915 UseInput01 |= (4 <= M);
25918 // If we're not using both inputs of the target shuffle then use the
25919 // referenced input directly.
25920 if (UseInput00 && !UseInput01) {
25923 } else if (!UseInput00 && UseInput01) {
25929 return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
25930 DAG.getConstant(InsertPSMask, DL, MVT::i8));
25938 // Nuke no-op shuffles that show up after combining.
25939 if (isNoopShuffleMask(Mask))
25940 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
25942 // Look for simplifications involving one or two shuffle instructions.
25943 SDValue V = N.getOperand(0);
25944 switch (N.getOpcode()) {
25947 case X86ISD::PSHUFLW:
25948 case X86ISD::PSHUFHW:
25949 assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
25951 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
25952 return SDValue(); // We combined away this shuffle, so we're done.
25954 // See if this reduces to a PSHUFD which is no more expensive and can
25955 // combine with more operations. Note that it has to at least flip the
25956 // dwords as otherwise it would have been removed as a no-op.
25957 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
25958 int DMask[] = {0, 1, 2, 3};
25959 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
25960 DMask[DOffset + 0] = DOffset + 1;
25961 DMask[DOffset + 1] = DOffset + 0;
25962 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
25963 V = DAG.getBitcast(DVT, V);
25964 DCI.AddToWorklist(V.getNode());
25965 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
25966 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
25967 DCI.AddToWorklist(V.getNode());
25968 return DAG.getBitcast(VT, V);
25971 // Look for shuffle patterns which can be implemented as a single unpack.
25972 // FIXME: This doesn't handle the location of the PSHUFD generically, and
25973 // only works when we have a PSHUFD followed by two half-shuffles.
25974 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
25975 (V.getOpcode() == X86ISD::PSHUFLW ||
25976 V.getOpcode() == X86ISD::PSHUFHW) &&
25977 V.getOpcode() != N.getOpcode() &&
25979 SDValue D = V.getOperand(0);
25980 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
25981 D = D.getOperand(0);
25982 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
25983 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
25984 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
25985 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
25986 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
25988 for (int i = 0; i < 4; ++i) {
25989 WordMask[i + NOffset] = Mask[i] + NOffset;
25990 WordMask[i + VOffset] = VMask[i] + VOffset;
25992 // Map the word mask through the DWord mask.
25994 for (int i = 0; i < 8; ++i)
25995 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
25996 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
25997 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
25998 // We can replace all three shuffles with an unpack.
25999 V = DAG.getBitcast(VT, D.getOperand(0));
26000 DCI.AddToWorklist(V.getNode());
26001 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
26010 case X86ISD::PSHUFD:
26011 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
26020 /// \brief Try to combine a shuffle into a target-specific add-sub node.
26022 /// We combine this directly on the abstract vector shuffle nodes so it is
26023 /// easier to generically match. We also insert dummy vector shuffle nodes for
26024 /// the operands which explicitly discard the lanes which are unused by this
26025 /// operation to try to flow through the rest of the combiner the fact that
26026 /// they're unused.
26027 static SDValue combineShuffleToAddSub(SDNode *N, const X86Subtarget &Subtarget,
26028 SelectionDAG &DAG) {
26030 EVT VT = N->getValueType(0);
26031 if ((!Subtarget.hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
26032 (!Subtarget.hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
26035 // We only handle target-independent shuffles.
26036 // FIXME: It would be easy and harmless to use the target shuffle mask
26037 // extraction tool to support more.
26038 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
26041 auto *SVN = cast<ShuffleVectorSDNode>(N);
26042 SmallVector<int, 8> Mask;
26043 for (int M : SVN->getMask())
26046 SDValue V1 = N->getOperand(0);
26047 SDValue V2 = N->getOperand(1);
26049 // We require the first shuffle operand to be the FSUB node, and the second to
26050 // be the FADD node.
26051 if (V1.getOpcode() == ISD::FADD && V2.getOpcode() == ISD::FSUB) {
26052 ShuffleVectorSDNode::commuteMask(Mask);
26054 } else if (V1.getOpcode() != ISD::FSUB || V2.getOpcode() != ISD::FADD)
26057 // If there are other uses of these operations we can't fold them.
26058 if (!V1->hasOneUse() || !V2->hasOneUse())
26061 // Ensure that both operations have the same operands. Note that we can
26062 // commute the FADD operands.
26063 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
26064 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
26065 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
26068 // We're looking for blends between FADD and FSUB nodes. We insist on these
26069 // nodes being lined up in a specific expected pattern.
26070 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
26071 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
26072 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
26075 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
26078 static SDValue combineShuffle(SDNode *N, SelectionDAG &DAG,
26079 TargetLowering::DAGCombinerInfo &DCI,
26080 const X86Subtarget &Subtarget) {
26082 EVT VT = N->getValueType(0);
26084 // Don't create instructions with illegal types after legalize types has run.
26085 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26086 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
26089 // If we have legalized the vector types, look for blends of FADD and FSUB
26090 // nodes that we can fuse into an ADDSUB node.
26091 if (TLI.isTypeLegal(VT))
26092 if (SDValue AddSub = combineShuffleToAddSub(N, Subtarget, DAG))
26095 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
26096 if (TLI.isTypeLegal(VT) && Subtarget.hasFp256() && VT.is256BitVector() &&
26097 N->getOpcode() == ISD::VECTOR_SHUFFLE)
26098 return combineShuffle256(N, DAG, DCI, Subtarget);
26100 // During Type Legalization, when promoting illegal vector types,
26101 // the backend might introduce new shuffle dag nodes and bitcasts.
26103 // This code performs the following transformation:
26104 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
26105 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
26107 // We do this only if both the bitcast and the BINOP dag nodes have
26108 // one use. Also, perform this transformation only if the new binary
26109 // operation is legal. This is to avoid introducing dag nodes that
26110 // potentially need to be further expanded (or custom lowered) into a
26111 // less optimal sequence of dag nodes.
26112 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
26113 N->getOpcode() == ISD::VECTOR_SHUFFLE &&
26114 N->getOperand(0).getOpcode() == ISD::BITCAST &&
26115 N->getOperand(1).isUndef() && N->getOperand(0).hasOneUse()) {
26116 SDValue N0 = N->getOperand(0);
26117 SDValue N1 = N->getOperand(1);
26119 SDValue BC0 = N0.getOperand(0);
26120 EVT SVT = BC0.getValueType();
26121 unsigned Opcode = BC0.getOpcode();
26122 unsigned NumElts = VT.getVectorNumElements();
26124 if (BC0.hasOneUse() && SVT.isVector() &&
26125 SVT.getVectorNumElements() * 2 == NumElts &&
26126 TLI.isOperationLegal(Opcode, VT)) {
26127 bool CanFold = false;
26139 unsigned SVTNumElts = SVT.getVectorNumElements();
26140 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
26141 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
26142 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
26143 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
26144 CanFold = SVOp->getMaskElt(i) < 0;
26147 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
26148 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
26149 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
26150 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, SVOp->getMask());
26155 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
26156 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
26157 // consecutive, non-overlapping, and in the right order.
26158 SmallVector<SDValue, 16> Elts;
26159 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
26160 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
26162 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
26165 if (isTargetShuffle(N->getOpcode())) {
26166 if (SDValue Shuffle =
26167 combineTargetShuffle(SDValue(N, 0), DAG, DCI, Subtarget))
26170 // Try recursively combining arbitrary sequences of x86 shuffle
26171 // instructions into higher-order shuffles. We do this after combining
26172 // specific PSHUF instruction sequences into their minimal form so that we
26173 // can evaluate how many specialized shuffle instructions are involved in
26174 // a particular chain.
26175 SmallVector<int, 1> NonceMask; // Just a placeholder.
26176 NonceMask.push_back(0);
26177 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
26178 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
26180 return SDValue(); // This routine will use CombineTo to replace N.
26186 /// Check if a vector extract from a target-specific shuffle of a load can be
26187 /// folded into a single element load.
26188 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
26189 /// shuffles have been custom lowered so we need to handle those here.
26190 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
26191 TargetLowering::DAGCombinerInfo &DCI) {
26192 if (DCI.isBeforeLegalizeOps())
26195 SDValue InVec = N->getOperand(0);
26196 SDValue EltNo = N->getOperand(1);
26197 EVT EltVT = N->getValueType(0);
26199 if (!isa<ConstantSDNode>(EltNo))
26202 EVT OriginalVT = InVec.getValueType();
26204 if (InVec.getOpcode() == ISD::BITCAST) {
26205 // Don't duplicate a load with other uses.
26206 if (!InVec.hasOneUse())
26208 EVT BCVT = InVec.getOperand(0).getValueType();
26209 if (!BCVT.isVector() ||
26210 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
26212 InVec = InVec.getOperand(0);
26215 EVT CurrentVT = InVec.getValueType();
26217 if (!isTargetShuffle(InVec.getOpcode()))
26220 // Don't duplicate a load with other uses.
26221 if (!InVec.hasOneUse())
26224 SmallVector<int, 16> ShuffleMask;
26225 SmallVector<SDValue, 2> ShuffleOps;
26227 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(), true,
26228 ShuffleOps, ShuffleMask, UnaryShuffle))
26231 // Select the input vector, guarding against out of range extract vector.
26232 unsigned NumElems = CurrentVT.getVectorNumElements();
26233 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
26234 int Idx = (Elt > (int)NumElems) ? SM_SentinelUndef : ShuffleMask[Elt];
26236 if (Idx == SM_SentinelZero)
26237 return EltVT.isInteger() ? DAG.getConstant(0, SDLoc(N), EltVT)
26238 : DAG.getConstantFP(+0.0, SDLoc(N), EltVT);
26239 if (Idx == SM_SentinelUndef)
26240 return DAG.getUNDEF(EltVT);
26242 assert(0 <= Idx && Idx < (int)(2 * NumElems) && "Shuffle index out of range");
26243 SDValue LdNode = (Idx < (int)NumElems) ? ShuffleOps[0]
26246 // If inputs to shuffle are the same for both ops, then allow 2 uses
26247 unsigned AllowedUses =
26248 (ShuffleOps.size() > 1 && ShuffleOps[0] == ShuffleOps[1]) ? 2 : 1;
26250 if (LdNode.getOpcode() == ISD::BITCAST) {
26251 // Don't duplicate a load with other uses.
26252 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
26255 AllowedUses = 1; // only allow 1 load use if we have a bitcast
26256 LdNode = LdNode.getOperand(0);
26259 if (!ISD::isNormalLoad(LdNode.getNode()))
26262 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
26264 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
26267 // If there's a bitcast before the shuffle, check if the load type and
26268 // alignment is valid.
26269 unsigned Align = LN0->getAlignment();
26270 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26271 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
26272 EltVT.getTypeForEVT(*DAG.getContext()));
26274 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
26277 // All checks match so transform back to vector_shuffle so that DAG combiner
26278 // can finish the job
26281 // Create shuffle node taking into account the case that its a unary shuffle
26282 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT) : ShuffleOps[1];
26283 Shuffle = DAG.getVectorShuffle(CurrentVT, dl, ShuffleOps[0], Shuffle,
26285 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
26286 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
26290 static SDValue combineBitcast(SDNode *N, SelectionDAG &DAG,
26291 const X86Subtarget &Subtarget) {
26292 SDValue N0 = N->getOperand(0);
26293 EVT VT = N->getValueType(0);
26295 // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
26296 // special and don't usually play with other vector types, it's better to
26297 // handle them early to be sure we emit efficient code by avoiding
26298 // store-load conversions.
26299 if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
26300 N0.getValueType() == MVT::v2i32 &&
26301 isNullConstant(N0.getOperand(1))) {
26302 SDValue N00 = N0->getOperand(0);
26303 if (N00.getValueType() == MVT::i32)
26304 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
26307 // Convert a bitcasted integer logic operation that has one bitcasted
26308 // floating-point operand and one constant operand into a floating-point
26309 // logic operation. This may create a load of the constant, but that is
26310 // cheaper than materializing the constant in an integer register and
26311 // transferring it to an SSE register or transferring the SSE operand to
26312 // integer register and back.
26314 switch (N0.getOpcode()) {
26315 case ISD::AND: FPOpcode = X86ISD::FAND; break;
26316 case ISD::OR: FPOpcode = X86ISD::FOR; break;
26317 case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
26318 default: return SDValue();
26320 if (((Subtarget.hasSSE1() && VT == MVT::f32) ||
26321 (Subtarget.hasSSE2() && VT == MVT::f64)) &&
26322 isa<ConstantSDNode>(N0.getOperand(1)) &&
26323 N0.getOperand(0).getOpcode() == ISD::BITCAST &&
26324 N0.getOperand(0).getOperand(0).getValueType() == VT) {
26325 SDValue N000 = N0.getOperand(0).getOperand(0);
26326 SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
26327 return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
26333 /// Detect vector gather/scatter index generation and convert it from being a
26334 /// bunch of shuffles and extracts into a somewhat faster sequence.
26335 /// For i686, the best sequence is apparently storing the value and loading
26336 /// scalars back, while for x64 we should use 64-bit extracts and shifts.
26337 static SDValue combineExtractVectorElt(SDNode *N, SelectionDAG &DAG,
26338 TargetLowering::DAGCombinerInfo &DCI) {
26339 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
26342 SDValue InputVector = N->getOperand(0);
26343 SDLoc dl(InputVector);
26344 // Detect mmx to i32 conversion through a v2i32 elt extract.
26345 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
26346 N->getValueType(0) == MVT::i32 &&
26347 InputVector.getValueType() == MVT::v2i32 &&
26348 isa<ConstantSDNode>(N->getOperand(1)) &&
26349 N->getConstantOperandVal(1) == 0) {
26350 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
26352 // The bitcast source is a direct mmx result.
26353 if (MMXSrc.getValueType() == MVT::x86mmx)
26354 return DAG.getNode(X86ISD::MMX_MOVD2W, dl, MVT::i32, MMXSrc);
26357 EVT VT = N->getValueType(0);
26359 if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
26360 InputVector.getOpcode() == ISD::BITCAST &&
26361 isa<ConstantSDNode>(InputVector.getOperand(0))) {
26362 uint64_t ExtractedElt =
26363 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
26364 uint64_t InputValue =
26365 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
26366 uint64_t Res = (InputValue >> ExtractedElt) & 1;
26367 return DAG.getConstant(Res, dl, MVT::i1);
26369 // Only operate on vectors of 4 elements, where the alternative shuffling
26370 // gets to be more expensive.
26371 if (InputVector.getValueType() != MVT::v4i32)
26374 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
26375 // single use which is a sign-extend or zero-extend, and all elements are
26377 SmallVector<SDNode *, 4> Uses;
26378 unsigned ExtractedElements = 0;
26379 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
26380 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
26381 if (UI.getUse().getResNo() != InputVector.getResNo())
26384 SDNode *Extract = *UI;
26385 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
26388 if (Extract->getValueType(0) != MVT::i32)
26390 if (!Extract->hasOneUse())
26392 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
26393 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
26395 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
26398 // Record which element was extracted.
26399 ExtractedElements |=
26400 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
26402 Uses.push_back(Extract);
26405 // If not all the elements were used, this may not be worthwhile.
26406 if (ExtractedElements != 15)
26409 // Ok, we've now decided to do the transformation.
26410 // If 64-bit shifts are legal, use the extract-shift sequence,
26411 // otherwise bounce the vector off the cache.
26412 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26415 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
26416 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
26417 auto &DL = DAG.getDataLayout();
26418 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
26419 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
26420 DAG.getConstant(0, dl, VecIdxTy));
26421 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
26422 DAG.getConstant(1, dl, VecIdxTy));
26424 SDValue ShAmt = DAG.getConstant(
26425 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
26426 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
26427 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
26428 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
26429 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
26430 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
26431 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
26433 // Store the value to a temporary stack slot.
26434 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
26435 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
26436 MachinePointerInfo());
26438 EVT ElementType = InputVector.getValueType().getVectorElementType();
26439 unsigned EltSize = ElementType.getSizeInBits() / 8;
26441 // Replace each use (extract) with a load of the appropriate element.
26442 for (unsigned i = 0; i < 4; ++i) {
26443 uint64_t Offset = EltSize * i;
26444 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
26445 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
26447 SDValue ScalarAddr =
26448 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
26450 // Load the scalar.
26452 DAG.getLoad(ElementType, dl, Ch, ScalarAddr, MachinePointerInfo());
26456 // Replace the extracts
26457 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
26458 UE = Uses.end(); UI != UE; ++UI) {
26459 SDNode *Extract = *UI;
26461 SDValue Idx = Extract->getOperand(1);
26462 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
26463 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
26466 // The replacement was made in place; don't return anything.
26470 /// Do target-specific dag combines on SELECT and VSELECT nodes.
26471 static SDValue combineSelect(SDNode *N, SelectionDAG &DAG,
26472 TargetLowering::DAGCombinerInfo &DCI,
26473 const X86Subtarget &Subtarget) {
26475 SDValue Cond = N->getOperand(0);
26476 // Get the LHS/RHS of the select.
26477 SDValue LHS = N->getOperand(1);
26478 SDValue RHS = N->getOperand(2);
26479 EVT VT = LHS.getValueType();
26480 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26482 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
26483 // instructions match the semantics of the common C idiom x<y?x:y but not
26484 // x<=y?x:y, because of how they handle negative zero (which can be
26485 // ignored in unsafe-math mode).
26486 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
26487 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
26488 VT != MVT::f80 && VT != MVT::f128 &&
26489 (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
26490 (Subtarget.hasSSE2() ||
26491 (Subtarget.hasSSE1() && VT.getScalarType() == MVT::f32))) {
26492 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
26494 unsigned Opcode = 0;
26495 // Check for x CC y ? x : y.
26496 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
26497 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
26501 // Converting this to a min would handle NaNs incorrectly, and swapping
26502 // the operands would cause it to handle comparisons between positive
26503 // and negative zero incorrectly.
26504 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
26505 if (!DAG.getTarget().Options.UnsafeFPMath &&
26506 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
26508 std::swap(LHS, RHS);
26510 Opcode = X86ISD::FMIN;
26513 // Converting this to a min would handle comparisons between positive
26514 // and negative zero incorrectly.
26515 if (!DAG.getTarget().Options.UnsafeFPMath &&
26516 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
26518 Opcode = X86ISD::FMIN;
26521 // Converting this to a min would handle both negative zeros and NaNs
26522 // incorrectly, but we can swap the operands to fix both.
26523 std::swap(LHS, RHS);
26527 Opcode = X86ISD::FMIN;
26531 // Converting this to a max would handle comparisons between positive
26532 // and negative zero incorrectly.
26533 if (!DAG.getTarget().Options.UnsafeFPMath &&
26534 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
26536 Opcode = X86ISD::FMAX;
26539 // Converting this to a max would handle NaNs incorrectly, and swapping
26540 // the operands would cause it to handle comparisons between positive
26541 // and negative zero incorrectly.
26542 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
26543 if (!DAG.getTarget().Options.UnsafeFPMath &&
26544 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
26546 std::swap(LHS, RHS);
26548 Opcode = X86ISD::FMAX;
26551 // Converting this to a max would handle both negative zeros and NaNs
26552 // incorrectly, but we can swap the operands to fix both.
26553 std::swap(LHS, RHS);
26557 Opcode = X86ISD::FMAX;
26560 // Check for x CC y ? y : x -- a min/max with reversed arms.
26561 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
26562 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
26566 // Converting this to a min would handle comparisons between positive
26567 // and negative zero incorrectly, and swapping the operands would
26568 // cause it to handle NaNs incorrectly.
26569 if (!DAG.getTarget().Options.UnsafeFPMath &&
26570 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
26571 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
26573 std::swap(LHS, RHS);
26575 Opcode = X86ISD::FMIN;
26578 // Converting this to a min would handle NaNs incorrectly.
26579 if (!DAG.getTarget().Options.UnsafeFPMath &&
26580 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
26582 Opcode = X86ISD::FMIN;
26585 // Converting this to a min would handle both negative zeros and NaNs
26586 // incorrectly, but we can swap the operands to fix both.
26587 std::swap(LHS, RHS);
26591 Opcode = X86ISD::FMIN;
26595 // Converting this to a max would handle NaNs incorrectly.
26596 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
26598 Opcode = X86ISD::FMAX;
26601 // Converting this to a max would handle comparisons between positive
26602 // and negative zero incorrectly, and swapping the operands would
26603 // cause it to handle NaNs incorrectly.
26604 if (!DAG.getTarget().Options.UnsafeFPMath &&
26605 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
26606 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
26608 std::swap(LHS, RHS);
26610 Opcode = X86ISD::FMAX;
26613 // Converting this to a max would handle both negative zeros and NaNs
26614 // incorrectly, but we can swap the operands to fix both.
26615 std::swap(LHS, RHS);
26619 Opcode = X86ISD::FMAX;
26625 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
26628 EVT CondVT = Cond.getValueType();
26629 if (Subtarget.hasAVX512() && VT.isVector() && CondVT.isVector() &&
26630 CondVT.getVectorElementType() == MVT::i1) {
26631 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
26632 // lowering on KNL. In this case we convert it to
26633 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
26634 // The same situation for all 128 and 256-bit vectors of i8 and i16.
26635 // Since SKX these selects have a proper lowering.
26636 EVT OpVT = LHS.getValueType();
26637 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
26638 (OpVT.getVectorElementType() == MVT::i8 ||
26639 OpVT.getVectorElementType() == MVT::i16) &&
26640 !(Subtarget.hasBWI() && Subtarget.hasVLX())) {
26641 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
26642 DCI.AddToWorklist(Cond.getNode());
26643 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
26646 // If this is a select between two integer constants, try to do some
26648 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
26649 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
26650 // Don't do this for crazy integer types.
26651 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
26652 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
26653 // so that TrueC (the true value) is larger than FalseC.
26654 bool NeedsCondInvert = false;
26656 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
26657 // Efficiently invertible.
26658 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
26659 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
26660 isa<ConstantSDNode>(Cond.getOperand(1))))) {
26661 NeedsCondInvert = true;
26662 std::swap(TrueC, FalseC);
26665 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
26666 if (FalseC->getAPIntValue() == 0 &&
26667 TrueC->getAPIntValue().isPowerOf2()) {
26668 if (NeedsCondInvert) // Invert the condition if needed.
26669 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
26670 DAG.getConstant(1, DL, Cond.getValueType()));
26672 // Zero extend the condition if needed.
26673 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
26675 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
26676 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
26677 DAG.getConstant(ShAmt, DL, MVT::i8));
26680 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
26681 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
26682 if (NeedsCondInvert) // Invert the condition if needed.
26683 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
26684 DAG.getConstant(1, DL, Cond.getValueType()));
26686 // Zero extend the condition if needed.
26687 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
26688 FalseC->getValueType(0), Cond);
26689 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
26690 SDValue(FalseC, 0));
26693 // Optimize cases that will turn into an LEA instruction. This requires
26694 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
26695 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
26696 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
26697 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
26699 bool isFastMultiplier = false;
26701 switch ((unsigned char)Diff) {
26703 case 1: // result = add base, cond
26704 case 2: // result = lea base( , cond*2)
26705 case 3: // result = lea base(cond, cond*2)
26706 case 4: // result = lea base( , cond*4)
26707 case 5: // result = lea base(cond, cond*4)
26708 case 8: // result = lea base( , cond*8)
26709 case 9: // result = lea base(cond, cond*8)
26710 isFastMultiplier = true;
26715 if (isFastMultiplier) {
26716 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
26717 if (NeedsCondInvert) // Invert the condition if needed.
26718 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
26719 DAG.getConstant(1, DL, Cond.getValueType()));
26721 // Zero extend the condition if needed.
26722 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
26724 // Scale the condition by the difference.
26726 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
26727 DAG.getConstant(Diff, DL,
26728 Cond.getValueType()));
26730 // Add the base if non-zero.
26731 if (FalseC->getAPIntValue() != 0)
26732 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
26733 SDValue(FalseC, 0));
26740 // Canonicalize max and min:
26741 // (x > y) ? x : y -> (x >= y) ? x : y
26742 // (x < y) ? x : y -> (x <= y) ? x : y
26743 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
26744 // the need for an extra compare
26745 // against zero. e.g.
26746 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
26748 // testl %edi, %edi
26750 // cmovgl %edi, %eax
26754 // cmovsl %eax, %edi
26755 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
26756 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
26757 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
26758 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
26763 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
26764 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
26765 Cond.getOperand(0), Cond.getOperand(1), NewCC);
26766 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
26771 // Early exit check
26772 if (!TLI.isTypeLegal(VT))
26775 // Match VSELECTs into subs with unsigned saturation.
26776 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
26777 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
26778 ((Subtarget.hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
26779 (Subtarget.hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
26780 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
26782 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
26783 // left side invert the predicate to simplify logic below.
26785 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
26787 CC = ISD::getSetCCInverse(CC, true);
26788 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
26792 if (Other.getNode() && Other->getNumOperands() == 2 &&
26793 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
26794 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
26795 SDValue CondRHS = Cond->getOperand(1);
26797 // Look for a general sub with unsigned saturation first.
26798 // x >= y ? x-y : 0 --> subus x, y
26799 // x > y ? x-y : 0 --> subus x, y
26800 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
26801 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
26802 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
26804 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
26805 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
26806 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
26807 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
26808 // If the RHS is a constant we have to reverse the const
26809 // canonicalization.
26810 // x > C-1 ? x+-C : 0 --> subus x, C
26811 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
26812 CondRHSConst->getAPIntValue() ==
26813 (-OpRHSConst->getAPIntValue() - 1))
26814 return DAG.getNode(
26815 X86ISD::SUBUS, DL, VT, OpLHS,
26816 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
26818 // Another special case: If C was a sign bit, the sub has been
26819 // canonicalized into a xor.
26820 // FIXME: Would it be better to use computeKnownBits to determine
26821 // whether it's safe to decanonicalize the xor?
26822 // x s< 0 ? x^C : 0 --> subus x, C
26823 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
26824 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
26825 OpRHSConst->getAPIntValue().isSignBit())
26826 // Note that we have to rebuild the RHS constant here to ensure we
26827 // don't rely on particular values of undef lanes.
26828 return DAG.getNode(
26829 X86ISD::SUBUS, DL, VT, OpLHS,
26830 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
26835 // Simplify vector selection if condition value type matches vselect
26837 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
26838 assert(Cond.getValueType().isVector() &&
26839 "vector select expects a vector selector!");
26841 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
26842 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
26844 // Try invert the condition if true value is not all 1s and false value
26846 if (!TValIsAllOnes && !FValIsAllZeros &&
26847 // Check if the selector will be produced by CMPP*/PCMP*
26848 Cond.getOpcode() == ISD::SETCC &&
26849 // Check if SETCC has already been promoted
26850 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
26852 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
26853 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
26855 if (TValIsAllZeros || FValIsAllOnes) {
26856 SDValue CC = Cond.getOperand(2);
26857 ISD::CondCode NewCC =
26858 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
26859 Cond.getOperand(0).getValueType().isInteger());
26860 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
26861 std::swap(LHS, RHS);
26862 TValIsAllOnes = FValIsAllOnes;
26863 FValIsAllZeros = TValIsAllZeros;
26867 if (TValIsAllOnes || FValIsAllZeros) {
26870 if (TValIsAllOnes && FValIsAllZeros)
26872 else if (TValIsAllOnes)
26874 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
26875 else if (FValIsAllZeros)
26876 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
26877 DAG.getBitcast(CondVT, LHS));
26879 return DAG.getBitcast(VT, Ret);
26883 // If this is a *dynamic* select (non-constant condition) and we can match
26884 // this node with one of the variable blend instructions, restructure the
26885 // condition so that the blends can use the high bit of each element and use
26886 // SimplifyDemandedBits to simplify the condition operand.
26887 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
26888 !DCI.isBeforeLegalize() &&
26889 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
26890 unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
26892 // Don't optimize vector selects that map to mask-registers.
26896 // We can only handle the cases where VSELECT is directly legal on the
26897 // subtarget. We custom lower VSELECT nodes with constant conditions and
26898 // this makes it hard to see whether a dynamic VSELECT will correctly
26899 // lower, so we both check the operation's status and explicitly handle the
26900 // cases where a *dynamic* blend will fail even though a constant-condition
26901 // blend could be custom lowered.
26902 // FIXME: We should find a better way to handle this class of problems.
26903 // Potentially, we should combine constant-condition vselect nodes
26904 // pre-legalization into shuffles and not mark as many types as custom
26906 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
26908 // FIXME: We don't support i16-element blends currently. We could and
26909 // should support them by making *all* the bits in the condition be set
26910 // rather than just the high bit and using an i8-element blend.
26911 if (VT.getVectorElementType() == MVT::i16)
26913 // Dynamic blending was only available from SSE4.1 onward.
26914 if (VT.is128BitVector() && !Subtarget.hasSSE41())
26916 // Byte blends are only available in AVX2
26917 if (VT == MVT::v32i8 && !Subtarget.hasAVX2())
26920 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
26921 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
26923 APInt KnownZero, KnownOne;
26924 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
26925 DCI.isBeforeLegalizeOps());
26926 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
26927 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
26929 // If we changed the computation somewhere in the DAG, this change
26930 // will affect all users of Cond.
26931 // Make sure it is fine and update all the nodes so that we do not
26932 // use the generic VSELECT anymore. Otherwise, we may perform
26933 // wrong optimizations as we messed up with the actual expectation
26934 // for the vector boolean values.
26935 if (Cond != TLO.Old) {
26936 // Check all uses of that condition operand to check whether it will be
26937 // consumed by non-BLEND instructions, which may depend on all bits are
26939 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
26941 if (I->getOpcode() != ISD::VSELECT)
26942 // TODO: Add other opcodes eventually lowered into BLEND.
26945 // Update all the users of the condition, before committing the change,
26946 // so that the VSELECT optimizations that expect the correct vector
26947 // boolean value will not be triggered.
26948 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
26950 DAG.ReplaceAllUsesOfValueWith(
26952 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
26953 Cond, I->getOperand(1), I->getOperand(2)));
26954 DCI.CommitTargetLoweringOpt(TLO);
26957 // At this point, only Cond is changed. Change the condition
26958 // just for N to keep the opportunity to optimize all other
26959 // users their own way.
26960 DAG.ReplaceAllUsesOfValueWith(
26962 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
26963 TLO.New, N->getOperand(1), N->getOperand(2)));
26972 /// (brcond/cmov/setcc .., (cmp (atomic_load_add x, 1), 0), COND_S)
26974 /// (brcond/cmov/setcc .., (LADD x, 1), COND_LE)
26975 /// i.e., reusing the EFLAGS produced by the LOCKed instruction.
26976 /// Note that this is only legal for some op/cc combinations.
26977 static SDValue combineSetCCAtomicArith(SDValue Cmp, X86::CondCode &CC,
26978 SelectionDAG &DAG) {
26979 // This combine only operates on CMP-like nodes.
26980 if (!(Cmp.getOpcode() == X86ISD::CMP ||
26981 (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
26984 // This only applies to variations of the common case:
26985 // (icmp slt x, 0) -> (icmp sle (add x, 1), 0)
26986 // (icmp sge x, 0) -> (icmp sgt (add x, 1), 0)
26987 // (icmp sle x, 0) -> (icmp slt (sub x, 1), 0)
26988 // (icmp sgt x, 0) -> (icmp sge (sub x, 1), 0)
26989 // Using the proper condcodes (see below), overflow is checked for.
26991 // FIXME: We can generalize both constraints:
26992 // - XOR/OR/AND (if they were made to survive AtomicExpand)
26994 // if the result is compared.
26996 SDValue CmpLHS = Cmp.getOperand(0);
26997 SDValue CmpRHS = Cmp.getOperand(1);
26999 if (!CmpLHS.hasOneUse())
27002 auto *CmpRHSC = dyn_cast<ConstantSDNode>(CmpRHS);
27003 if (!CmpRHSC || CmpRHSC->getZExtValue() != 0)
27006 const unsigned Opc = CmpLHS.getOpcode();
27008 if (Opc != ISD::ATOMIC_LOAD_ADD && Opc != ISD::ATOMIC_LOAD_SUB)
27011 SDValue OpRHS = CmpLHS.getOperand(2);
27012 auto *OpRHSC = dyn_cast<ConstantSDNode>(OpRHS);
27016 APInt Addend = OpRHSC->getAPIntValue();
27017 if (Opc == ISD::ATOMIC_LOAD_SUB)
27020 if (CC == X86::COND_S && Addend == 1)
27022 else if (CC == X86::COND_NS && Addend == 1)
27024 else if (CC == X86::COND_G && Addend == -1)
27026 else if (CC == X86::COND_LE && Addend == -1)
27031 SDValue LockOp = lowerAtomicArithWithLOCK(CmpLHS, DAG);
27032 DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0),
27033 DAG.getUNDEF(CmpLHS.getValueType()));
27034 DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
27038 // Check whether a boolean test is testing a boolean value generated by
27039 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
27042 // Simplify the following patterns:
27043 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
27044 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
27045 // to (Op EFLAGS Cond)
27047 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
27048 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
27049 // to (Op EFLAGS !Cond)
27051 // where Op could be BRCOND or CMOV.
27053 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
27054 // This combine only operates on CMP-like nodes.
27055 if (!(Cmp.getOpcode() == X86ISD::CMP ||
27056 (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
27059 // Quit if not used as a boolean value.
27060 if (CC != X86::COND_E && CC != X86::COND_NE)
27063 // Check CMP operands. One of them should be 0 or 1 and the other should be
27064 // an SetCC or extended from it.
27065 SDValue Op1 = Cmp.getOperand(0);
27066 SDValue Op2 = Cmp.getOperand(1);
27069 const ConstantSDNode* C = nullptr;
27070 bool needOppositeCond = (CC == X86::COND_E);
27071 bool checkAgainstTrue = false; // Is it a comparison against 1?
27073 if ((C = dyn_cast<ConstantSDNode>(Op1)))
27075 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
27077 else // Quit if all operands are not constants.
27080 if (C->getZExtValue() == 1) {
27081 needOppositeCond = !needOppositeCond;
27082 checkAgainstTrue = true;
27083 } else if (C->getZExtValue() != 0)
27084 // Quit if the constant is neither 0 or 1.
27087 bool truncatedToBoolWithAnd = false;
27088 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
27089 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
27090 SetCC.getOpcode() == ISD::TRUNCATE ||
27091 SetCC.getOpcode() == ISD::AssertZext ||
27092 SetCC.getOpcode() == ISD::AND) {
27093 if (SetCC.getOpcode() == ISD::AND) {
27095 if (isOneConstant(SetCC.getOperand(0)))
27097 if (isOneConstant(SetCC.getOperand(1)))
27101 SetCC = SetCC.getOperand(OpIdx);
27102 truncatedToBoolWithAnd = true;
27104 SetCC = SetCC.getOperand(0);
27107 switch (SetCC.getOpcode()) {
27108 case X86ISD::SETCC_CARRY:
27109 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
27110 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
27111 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
27112 // truncated to i1 using 'and'.
27113 if (checkAgainstTrue && !truncatedToBoolWithAnd)
27115 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
27116 "Invalid use of SETCC_CARRY!");
27118 case X86ISD::SETCC:
27119 // Set the condition code or opposite one if necessary.
27120 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
27121 if (needOppositeCond)
27122 CC = X86::GetOppositeBranchCondition(CC);
27123 return SetCC.getOperand(1);
27124 case X86ISD::CMOV: {
27125 // Check whether false/true value has canonical one, i.e. 0 or 1.
27126 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
27127 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
27128 // Quit if true value is not a constant.
27131 // Quit if false value is not a constant.
27133 SDValue Op = SetCC.getOperand(0);
27134 // Skip 'zext' or 'trunc' node.
27135 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
27136 Op.getOpcode() == ISD::TRUNCATE)
27137 Op = Op.getOperand(0);
27138 // A special case for rdrand/rdseed, where 0 is set if false cond is
27140 if ((Op.getOpcode() != X86ISD::RDRAND &&
27141 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
27144 // Quit if false value is not the constant 0 or 1.
27145 bool FValIsFalse = true;
27146 if (FVal && FVal->getZExtValue() != 0) {
27147 if (FVal->getZExtValue() != 1)
27149 // If FVal is 1, opposite cond is needed.
27150 needOppositeCond = !needOppositeCond;
27151 FValIsFalse = false;
27153 // Quit if TVal is not the constant opposite of FVal.
27154 if (FValIsFalse && TVal->getZExtValue() != 1)
27156 if (!FValIsFalse && TVal->getZExtValue() != 0)
27158 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
27159 if (needOppositeCond)
27160 CC = X86::GetOppositeBranchCondition(CC);
27161 return SetCC.getOperand(3);
27168 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
27170 /// (X86or (X86setcc) (X86setcc))
27171 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
27172 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
27173 X86::CondCode &CC1, SDValue &Flags,
27175 if (Cond->getOpcode() == X86ISD::CMP) {
27176 if (!isNullConstant(Cond->getOperand(1)))
27179 Cond = Cond->getOperand(0);
27184 SDValue SetCC0, SetCC1;
27185 switch (Cond->getOpcode()) {
27186 default: return false;
27193 SetCC0 = Cond->getOperand(0);
27194 SetCC1 = Cond->getOperand(1);
27198 // Make sure we have SETCC nodes, using the same flags value.
27199 if (SetCC0.getOpcode() != X86ISD::SETCC ||
27200 SetCC1.getOpcode() != X86ISD::SETCC ||
27201 SetCC0->getOperand(1) != SetCC1->getOperand(1))
27204 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
27205 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
27206 Flags = SetCC0->getOperand(1);
27210 /// Optimize an EFLAGS definition used according to the condition code \p CC
27211 /// into a simpler EFLAGS value, potentially returning a new \p CC and replacing
27212 /// uses of chain values.
27213 static SDValue combineSetCCEFLAGS(SDValue EFLAGS, X86::CondCode &CC,
27214 SelectionDAG &DAG) {
27215 if (SDValue R = checkBoolTestSetCCCombine(EFLAGS, CC))
27217 return combineSetCCAtomicArith(EFLAGS, CC, DAG);
27220 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
27221 static SDValue combineCMov(SDNode *N, SelectionDAG &DAG,
27222 TargetLowering::DAGCombinerInfo &DCI,
27223 const X86Subtarget &Subtarget) {
27226 // If the flag operand isn't dead, don't touch this CMOV.
27227 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
27230 SDValue FalseOp = N->getOperand(0);
27231 SDValue TrueOp = N->getOperand(1);
27232 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
27233 SDValue Cond = N->getOperand(3);
27235 if (CC == X86::COND_E || CC == X86::COND_NE) {
27236 switch (Cond.getOpcode()) {
27240 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
27241 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
27242 return (CC == X86::COND_E) ? FalseOp : TrueOp;
27246 // Try to simplify the EFLAGS and condition code operands.
27247 // We can't always do this as FCMOV only supports a subset of X86 cond.
27248 if (SDValue Flags = combineSetCCEFLAGS(Cond, CC, DAG)) {
27249 if (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC)) {
27250 SDValue Ops[] = {FalseOp, TrueOp, DAG.getConstant(CC, DL, MVT::i8),
27252 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
27256 // If this is a select between two integer constants, try to do some
27257 // optimizations. Note that the operands are ordered the opposite of SELECT
27259 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
27260 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
27261 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
27262 // larger than FalseC (the false value).
27263 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
27264 CC = X86::GetOppositeBranchCondition(CC);
27265 std::swap(TrueC, FalseC);
27266 std::swap(TrueOp, FalseOp);
27269 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
27270 // This is efficient for any integer data type (including i8/i16) and
27272 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
27273 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
27274 DAG.getConstant(CC, DL, MVT::i8), Cond);
27276 // Zero extend the condition if needed.
27277 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
27279 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
27280 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
27281 DAG.getConstant(ShAmt, DL, MVT::i8));
27282 if (N->getNumValues() == 2) // Dead flag value?
27283 return DCI.CombineTo(N, Cond, SDValue());
27287 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
27288 // for any integer data type, including i8/i16.
27289 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
27290 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
27291 DAG.getConstant(CC, DL, MVT::i8), Cond);
27293 // Zero extend the condition if needed.
27294 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
27295 FalseC->getValueType(0), Cond);
27296 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
27297 SDValue(FalseC, 0));
27299 if (N->getNumValues() == 2) // Dead flag value?
27300 return DCI.CombineTo(N, Cond, SDValue());
27304 // Optimize cases that will turn into an LEA instruction. This requires
27305 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
27306 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
27307 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
27308 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
27310 bool isFastMultiplier = false;
27312 switch ((unsigned char)Diff) {
27314 case 1: // result = add base, cond
27315 case 2: // result = lea base( , cond*2)
27316 case 3: // result = lea base(cond, cond*2)
27317 case 4: // result = lea base( , cond*4)
27318 case 5: // result = lea base(cond, cond*4)
27319 case 8: // result = lea base( , cond*8)
27320 case 9: // result = lea base(cond, cond*8)
27321 isFastMultiplier = true;
27326 if (isFastMultiplier) {
27327 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
27328 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
27329 DAG.getConstant(CC, DL, MVT::i8), Cond);
27330 // Zero extend the condition if needed.
27331 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
27333 // Scale the condition by the difference.
27335 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
27336 DAG.getConstant(Diff, DL, Cond.getValueType()));
27338 // Add the base if non-zero.
27339 if (FalseC->getAPIntValue() != 0)
27340 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
27341 SDValue(FalseC, 0));
27342 if (N->getNumValues() == 2) // Dead flag value?
27343 return DCI.CombineTo(N, Cond, SDValue());
27350 // Handle these cases:
27351 // (select (x != c), e, c) -> select (x != c), e, x),
27352 // (select (x == c), c, e) -> select (x == c), x, e)
27353 // where the c is an integer constant, and the "select" is the combination
27354 // of CMOV and CMP.
27356 // The rationale for this change is that the conditional-move from a constant
27357 // needs two instructions, however, conditional-move from a register needs
27358 // only one instruction.
27360 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
27361 // some instruction-combining opportunities. This opt needs to be
27362 // postponed as late as possible.
27364 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
27365 // the DCI.xxxx conditions are provided to postpone the optimization as
27366 // late as possible.
27368 ConstantSDNode *CmpAgainst = nullptr;
27369 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
27370 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
27371 !isa<ConstantSDNode>(Cond.getOperand(0))) {
27373 if (CC == X86::COND_NE &&
27374 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
27375 CC = X86::GetOppositeBranchCondition(CC);
27376 std::swap(TrueOp, FalseOp);
27379 if (CC == X86::COND_E &&
27380 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
27381 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
27382 DAG.getConstant(CC, DL, MVT::i8), Cond };
27383 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
27388 // Fold and/or of setcc's to double CMOV:
27389 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
27390 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
27392 // This combine lets us generate:
27393 // cmovcc1 (jcc1 if we don't have CMOV)
27399 // cmovne (jne if we don't have CMOV)
27400 // When we can't use the CMOV instruction, it might increase branch
27402 // When we can use CMOV, or when there is no mispredict, this improves
27403 // throughput and reduces register pressure.
27405 if (CC == X86::COND_NE) {
27407 X86::CondCode CC0, CC1;
27409 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
27411 std::swap(FalseOp, TrueOp);
27412 CC0 = X86::GetOppositeBranchCondition(CC0);
27413 CC1 = X86::GetOppositeBranchCondition(CC1);
27416 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
27418 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
27419 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
27420 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
27421 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
27429 /// Different mul shrinking modes.
27430 enum ShrinkMode { MULS8, MULU8, MULS16, MULU16 };
27432 static bool canReduceVMulWidth(SDNode *N, SelectionDAG &DAG, ShrinkMode &Mode) {
27433 EVT VT = N->getOperand(0).getValueType();
27434 if (VT.getScalarSizeInBits() != 32)
27437 assert(N->getNumOperands() == 2 && "NumOperands of Mul are 2");
27438 unsigned SignBits[2] = {1, 1};
27439 bool IsPositive[2] = {false, false};
27440 for (unsigned i = 0; i < 2; i++) {
27441 SDValue Opd = N->getOperand(i);
27443 // DAG.ComputeNumSignBits return 1 for ISD::ANY_EXTEND, so we need to
27444 // compute signbits for it separately.
27445 if (Opd.getOpcode() == ISD::ANY_EXTEND) {
27446 // For anyextend, it is safe to assume an appropriate number of leading
27448 if (Opd.getOperand(0).getValueType().getVectorElementType() == MVT::i8)
27450 else if (Opd.getOperand(0).getValueType().getVectorElementType() ==
27455 IsPositive[i] = true;
27456 } else if (Opd.getOpcode() == ISD::BUILD_VECTOR) {
27457 // All the operands of BUILD_VECTOR need to be int constant.
27458 // Find the smallest value range which all the operands belong to.
27460 IsPositive[i] = true;
27461 for (const SDValue &SubOp : Opd.getNode()->op_values()) {
27462 if (SubOp.isUndef())
27464 auto *CN = dyn_cast<ConstantSDNode>(SubOp);
27467 APInt IntVal = CN->getAPIntValue();
27468 if (IntVal.isNegative())
27469 IsPositive[i] = false;
27470 SignBits[i] = std::min(SignBits[i], IntVal.getNumSignBits());
27473 SignBits[i] = DAG.ComputeNumSignBits(Opd);
27474 if (Opd.getOpcode() == ISD::ZERO_EXTEND)
27475 IsPositive[i] = true;
27479 bool AllPositive = IsPositive[0] && IsPositive[1];
27480 unsigned MinSignBits = std::min(SignBits[0], SignBits[1]);
27481 // When ranges are from -128 ~ 127, use MULS8 mode.
27482 if (MinSignBits >= 25)
27484 // When ranges are from 0 ~ 255, use MULU8 mode.
27485 else if (AllPositive && MinSignBits >= 24)
27487 // When ranges are from -32768 ~ 32767, use MULS16 mode.
27488 else if (MinSignBits >= 17)
27490 // When ranges are from 0 ~ 65535, use MULU16 mode.
27491 else if (AllPositive && MinSignBits >= 16)
27498 /// When the operands of vector mul are extended from smaller size values,
27499 /// like i8 and i16, the type of mul may be shrinked to generate more
27500 /// efficient code. Two typical patterns are handled:
27502 /// %2 = sext/zext <N x i8> %1 to <N x i32>
27503 /// %4 = sext/zext <N x i8> %3 to <N x i32>
27504 // or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
27505 /// %5 = mul <N x i32> %2, %4
27508 /// %2 = zext/sext <N x i16> %1 to <N x i32>
27509 /// %4 = zext/sext <N x i16> %3 to <N x i32>
27510 /// or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
27511 /// %5 = mul <N x i32> %2, %4
27513 /// There are four mul shrinking modes:
27514 /// If %2 == sext32(trunc8(%2)), i.e., the scalar value range of %2 is
27515 /// -128 to 128, and the scalar value range of %4 is also -128 to 128,
27516 /// generate pmullw+sext32 for it (MULS8 mode).
27517 /// If %2 == zext32(trunc8(%2)), i.e., the scalar value range of %2 is
27518 /// 0 to 255, and the scalar value range of %4 is also 0 to 255,
27519 /// generate pmullw+zext32 for it (MULU8 mode).
27520 /// If %2 == sext32(trunc16(%2)), i.e., the scalar value range of %2 is
27521 /// -32768 to 32767, and the scalar value range of %4 is also -32768 to 32767,
27522 /// generate pmullw+pmulhw for it (MULS16 mode).
27523 /// If %2 == zext32(trunc16(%2)), i.e., the scalar value range of %2 is
27524 /// 0 to 65535, and the scalar value range of %4 is also 0 to 65535,
27525 /// generate pmullw+pmulhuw for it (MULU16 mode).
27526 static SDValue reduceVMULWidth(SDNode *N, SelectionDAG &DAG,
27527 const X86Subtarget &Subtarget) {
27528 // pmulld is supported since SSE41. It is better to use pmulld
27529 // instead of pmullw+pmulhw.
27530 // pmullw/pmulhw are not supported by SSE.
27531 if (Subtarget.hasSSE41() || !Subtarget.hasSSE2())
27535 if (!canReduceVMulWidth(N, DAG, Mode))
27539 SDValue N0 = N->getOperand(0);
27540 SDValue N1 = N->getOperand(1);
27541 EVT VT = N->getOperand(0).getValueType();
27542 unsigned RegSize = 128;
27543 MVT OpsVT = MVT::getVectorVT(MVT::i16, RegSize / 16);
27545 EVT::getVectorVT(*DAG.getContext(), MVT::i16, VT.getVectorNumElements());
27546 // Shrink the operands of mul.
27547 SDValue NewN0 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N0);
27548 SDValue NewN1 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N1);
27550 if (VT.getVectorNumElements() >= OpsVT.getVectorNumElements()) {
27551 // Generate the lower part of mul: pmullw. For MULU8/MULS8, only the
27552 // lower part is needed.
27553 SDValue MulLo = DAG.getNode(ISD::MUL, DL, ReducedVT, NewN0, NewN1);
27554 if (Mode == MULU8 || Mode == MULS8) {
27555 return DAG.getNode((Mode == MULU8) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND,
27558 MVT ResVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
27559 // Generate the higher part of mul: pmulhw/pmulhuw. For MULU16/MULS16,
27560 // the higher part is also needed.
27561 SDValue MulHi = DAG.getNode(Mode == MULS16 ? ISD::MULHS : ISD::MULHU, DL,
27562 ReducedVT, NewN0, NewN1);
27564 // Repack the lower part and higher part result of mul into a wider
27566 // Generate shuffle functioning as punpcklwd.
27567 SmallVector<int, 16> ShuffleMask(VT.getVectorNumElements());
27568 for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++) {
27569 ShuffleMask[2 * i] = i;
27570 ShuffleMask[2 * i + 1] = i + VT.getVectorNumElements();
27573 DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
27574 ResLo = DAG.getNode(ISD::BITCAST, DL, ResVT, ResLo);
27575 // Generate shuffle functioning as punpckhwd.
27576 for (unsigned i = 0; i < VT.getVectorNumElements() / 2; i++) {
27577 ShuffleMask[2 * i] = i + VT.getVectorNumElements() / 2;
27578 ShuffleMask[2 * i + 1] = i + VT.getVectorNumElements() * 3 / 2;
27581 DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
27582 ResHi = DAG.getNode(ISD::BITCAST, DL, ResVT, ResHi);
27583 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ResLo, ResHi);
27586 // When VT.getVectorNumElements() < OpsVT.getVectorNumElements(), we want
27587 // to legalize the mul explicitly because implicit legalization for type
27588 // <4 x i16> to <4 x i32> sometimes involves unnecessary unpack
27589 // instructions which will not exist when we explicitly legalize it by
27590 // extending <4 x i16> to <8 x i16> (concatenating the <4 x i16> val with
27591 // <4 x i16> undef).
27593 // Legalize the operands of mul.
27594 SmallVector<SDValue, 16> Ops(RegSize / ReducedVT.getSizeInBits(),
27595 DAG.getUNDEF(ReducedVT));
27597 NewN0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, OpsVT, Ops);
27599 NewN1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, OpsVT, Ops);
27601 if (Mode == MULU8 || Mode == MULS8) {
27602 // Generate lower part of mul: pmullw. For MULU8/MULS8, only the lower
27604 SDValue Mul = DAG.getNode(ISD::MUL, DL, OpsVT, NewN0, NewN1);
27606 // convert the type of mul result to VT.
27607 MVT ResVT = MVT::getVectorVT(MVT::i32, RegSize / 32);
27608 SDValue Res = DAG.getNode(Mode == MULU8 ? ISD::ZERO_EXTEND_VECTOR_INREG
27609 : ISD::SIGN_EXTEND_VECTOR_INREG,
27611 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
27612 DAG.getIntPtrConstant(0, DL));
27614 // Generate the lower and higher part of mul: pmulhw/pmulhuw. For
27615 // MULU16/MULS16, both parts are needed.
27616 SDValue MulLo = DAG.getNode(ISD::MUL, DL, OpsVT, NewN0, NewN1);
27617 SDValue MulHi = DAG.getNode(Mode == MULS16 ? ISD::MULHS : ISD::MULHU, DL,
27618 OpsVT, NewN0, NewN1);
27620 // Repack the lower part and higher part result of mul into a wider
27621 // result. Make sure the type of mul result is VT.
27622 MVT ResVT = MVT::getVectorVT(MVT::i32, RegSize / 32);
27623 SDValue Res = DAG.getNode(X86ISD::UNPCKL, DL, OpsVT, MulLo, MulHi);
27624 Res = DAG.getNode(ISD::BITCAST, DL, ResVT, Res);
27625 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
27626 DAG.getIntPtrConstant(0, DL));
27631 /// Optimize a single multiply with constant into two operations in order to
27632 /// implement it with two cheaper instructions, e.g. LEA + SHL, LEA + LEA.
27633 static SDValue combineMul(SDNode *N, SelectionDAG &DAG,
27634 TargetLowering::DAGCombinerInfo &DCI,
27635 const X86Subtarget &Subtarget) {
27636 EVT VT = N->getValueType(0);
27637 if (DCI.isBeforeLegalize() && VT.isVector())
27638 return reduceVMULWidth(N, DAG, Subtarget);
27640 // An imul is usually smaller than the alternative sequence.
27641 if (DAG.getMachineFunction().getFunction()->optForMinSize())
27644 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
27647 if (VT != MVT::i64 && VT != MVT::i32)
27650 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
27653 uint64_t MulAmt = C->getZExtValue();
27654 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
27657 uint64_t MulAmt1 = 0;
27658 uint64_t MulAmt2 = 0;
27659 if ((MulAmt % 9) == 0) {
27661 MulAmt2 = MulAmt / 9;
27662 } else if ((MulAmt % 5) == 0) {
27664 MulAmt2 = MulAmt / 5;
27665 } else if ((MulAmt % 3) == 0) {
27667 MulAmt2 = MulAmt / 3;
27673 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
27675 if (isPowerOf2_64(MulAmt2) &&
27676 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
27677 // If second multiplifer is pow2, issue it first. We want the multiply by
27678 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
27680 std::swap(MulAmt1, MulAmt2);
27682 if (isPowerOf2_64(MulAmt1))
27683 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
27684 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
27686 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
27687 DAG.getConstant(MulAmt1, DL, VT));
27689 if (isPowerOf2_64(MulAmt2))
27690 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
27691 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
27693 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
27694 DAG.getConstant(MulAmt2, DL, VT));
27698 assert(MulAmt != 0 && MulAmt != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX)
27699 && "Both cases that could cause potential overflows should have "
27700 "already been handled.");
27701 if (isPowerOf2_64(MulAmt - 1))
27702 // (mul x, 2^N + 1) => (add (shl x, N), x)
27703 NewMul = DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
27704 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
27705 DAG.getConstant(Log2_64(MulAmt - 1), DL,
27708 else if (isPowerOf2_64(MulAmt + 1))
27709 // (mul x, 2^N - 1) => (sub (shl x, N), x)
27710 NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getNode(ISD::SHL, DL, VT,
27712 DAG.getConstant(Log2_64(MulAmt + 1),
27713 DL, MVT::i8)), N->getOperand(0));
27717 // Do not add new nodes to DAG combiner worklist.
27718 DCI.CombineTo(N, NewMul, false);
27723 static SDValue combineShiftLeft(SDNode *N, SelectionDAG &DAG) {
27724 SDValue N0 = N->getOperand(0);
27725 SDValue N1 = N->getOperand(1);
27726 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
27727 EVT VT = N0.getValueType();
27729 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
27730 // since the result of setcc_c is all zero's or all ones.
27731 if (VT.isInteger() && !VT.isVector() &&
27732 N1C && N0.getOpcode() == ISD::AND &&
27733 N0.getOperand(1).getOpcode() == ISD::Constant) {
27734 SDValue N00 = N0.getOperand(0);
27735 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
27736 const APInt &ShAmt = N1C->getAPIntValue();
27737 Mask = Mask.shl(ShAmt);
27738 bool MaskOK = false;
27739 // We can handle cases concerning bit-widening nodes containing setcc_c if
27740 // we carefully interrogate the mask to make sure we are semantics
27742 // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
27743 // of the underlying setcc_c operation if the setcc_c was zero extended.
27744 // Consider the following example:
27745 // zext(setcc_c) -> i32 0x0000FFFF
27746 // c1 -> i32 0x0000FFFF
27747 // c2 -> i32 0x00000001
27748 // (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
27749 // (and setcc_c, (c1 << c2)) -> i32 0x0000FFFE
27750 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27752 } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
27753 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
27755 } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
27756 N00.getOpcode() == ISD::ANY_EXTEND) &&
27757 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
27758 MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
27760 if (MaskOK && Mask != 0) {
27762 return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
27766 // Hardware support for vector shifts is sparse which makes us scalarize the
27767 // vector operations in many cases. Also, on sandybridge ADD is faster than
27769 // (shl V, 1) -> add V,V
27770 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
27771 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
27772 assert(N0.getValueType().isVector() && "Invalid vector shift type");
27773 // We shift all of the values by one. In many cases we do not have
27774 // hardware support for this operation. This is better expressed as an ADD
27776 if (N1SplatC->getAPIntValue() == 1)
27777 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
27783 static SDValue combineShiftRightAlgebraic(SDNode *N, SelectionDAG &DAG) {
27784 SDValue N0 = N->getOperand(0);
27785 SDValue N1 = N->getOperand(1);
27786 EVT VT = N0.getValueType();
27787 unsigned Size = VT.getSizeInBits();
27789 // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
27790 // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
27791 // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
27792 // depending on sign of (SarConst - [56,48,32,24,16])
27794 // sexts in X86 are MOVs. The MOVs have the same code size
27795 // as above SHIFTs (only SHIFT on 1 has lower code size).
27796 // However the MOVs have 2 advantages to a SHIFT:
27797 // 1. MOVs can write to a register that differs from source
27798 // 2. MOVs accept memory operands
27800 if (!VT.isInteger() || VT.isVector() || N1.getOpcode() != ISD::Constant ||
27801 N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
27802 N0.getOperand(1).getOpcode() != ISD::Constant)
27805 SDValue N00 = N0.getOperand(0);
27806 SDValue N01 = N0.getOperand(1);
27807 APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
27808 APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
27809 EVT CVT = N1.getValueType();
27811 if (SarConst.isNegative())
27814 for (MVT SVT : MVT::integer_valuetypes()) {
27815 unsigned ShiftSize = SVT.getSizeInBits();
27816 // skipping types without corresponding sext/zext and
27817 // ShlConst that is not one of [56,48,32,24,16]
27818 if (ShiftSize < 8 || ShiftSize > 64 || ShlConst != Size - ShiftSize)
27822 DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
27823 SarConst = SarConst - (Size - ShiftSize);
27826 else if (SarConst.isNegative())
27827 return DAG.getNode(ISD::SHL, DL, VT, NN,
27828 DAG.getConstant(-SarConst, DL, CVT));
27830 return DAG.getNode(ISD::SRA, DL, VT, NN,
27831 DAG.getConstant(SarConst, DL, CVT));
27836 /// \brief Returns a vector of 0s if the node in input is a vector logical
27837 /// shift by a constant amount which is known to be bigger than or equal
27838 /// to the vector element size in bits.
27839 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
27840 const X86Subtarget &Subtarget) {
27841 EVT VT = N->getValueType(0);
27843 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
27844 (!Subtarget.hasInt256() ||
27845 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
27848 SDValue Amt = N->getOperand(1);
27850 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
27851 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
27852 const APInt &ShiftAmt = AmtSplat->getAPIntValue();
27853 unsigned MaxAmount =
27854 VT.getSimpleVT().getVectorElementType().getSizeInBits();
27856 // SSE2/AVX2 logical shifts always return a vector of 0s
27857 // if the shift amount is bigger than or equal to
27858 // the element size. The constant shift amount will be
27859 // encoded as a 8-bit immediate.
27860 if (ShiftAmt.trunc(8).uge(MaxAmount))
27861 return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, DL);
27867 static SDValue combineShift(SDNode* N, SelectionDAG &DAG,
27868 TargetLowering::DAGCombinerInfo &DCI,
27869 const X86Subtarget &Subtarget) {
27870 if (N->getOpcode() == ISD::SHL)
27871 if (SDValue V = combineShiftLeft(N, DAG))
27874 if (N->getOpcode() == ISD::SRA)
27875 if (SDValue V = combineShiftRightAlgebraic(N, DAG))
27878 // Try to fold this logical shift into a zero vector.
27879 if (N->getOpcode() != ISD::SRA)
27880 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
27886 /// Recognize the distinctive (AND (setcc ...) (setcc ..)) where both setccs
27887 /// reference the same FP CMP, and rewrite for CMPEQSS and friends. Likewise for
27888 /// OR -> CMPNEQSS.
27889 static SDValue combineCompareEqual(SDNode *N, SelectionDAG &DAG,
27890 TargetLowering::DAGCombinerInfo &DCI,
27891 const X86Subtarget &Subtarget) {
27894 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
27895 // we're requiring SSE2 for both.
27896 if (Subtarget.hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
27897 SDValue N0 = N->getOperand(0);
27898 SDValue N1 = N->getOperand(1);
27899 SDValue CMP0 = N0->getOperand(1);
27900 SDValue CMP1 = N1->getOperand(1);
27903 // The SETCCs should both refer to the same CMP.
27904 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
27907 SDValue CMP00 = CMP0->getOperand(0);
27908 SDValue CMP01 = CMP0->getOperand(1);
27909 EVT VT = CMP00.getValueType();
27911 if (VT == MVT::f32 || VT == MVT::f64) {
27912 bool ExpectingFlags = false;
27913 // Check for any users that want flags:
27914 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
27915 !ExpectingFlags && UI != UE; ++UI)
27916 switch (UI->getOpcode()) {
27921 ExpectingFlags = true;
27923 case ISD::CopyToReg:
27924 case ISD::SIGN_EXTEND:
27925 case ISD::ZERO_EXTEND:
27926 case ISD::ANY_EXTEND:
27930 if (!ExpectingFlags) {
27931 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
27932 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
27934 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
27935 X86::CondCode tmp = cc0;
27940 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
27941 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
27942 // FIXME: need symbolic constants for these magic numbers.
27943 // See X86ATTInstPrinter.cpp:printSSECC().
27944 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
27945 if (Subtarget.hasAVX512()) {
27946 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
27948 DAG.getConstant(x86cc, DL, MVT::i8));
27949 if (N->getValueType(0) != MVT::i1)
27950 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
27954 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
27955 CMP00.getValueType(), CMP00, CMP01,
27956 DAG.getConstant(x86cc, DL,
27959 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
27960 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
27962 if (is64BitFP && !Subtarget.is64Bit()) {
27963 // On a 32-bit target, we cannot bitcast the 64-bit float to a
27964 // 64-bit integer, since that's not a legal type. Since
27965 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
27966 // bits, but can do this little dance to extract the lowest 32 bits
27967 // and work with those going forward.
27968 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
27970 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
27971 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
27972 Vector32, DAG.getIntPtrConstant(0, DL));
27976 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
27977 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
27978 DAG.getConstant(1, DL, IntVT));
27979 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
27981 return OneBitOfTruth;
27989 /// Try to fold: (and (xor X, -1), Y) -> (andnp X, Y).
27990 static SDValue combineANDXORWithAllOnesIntoANDNP(SDNode *N, SelectionDAG &DAG) {
27991 assert(N->getOpcode() == ISD::AND);
27993 EVT VT = N->getValueType(0);
27994 SDValue N0 = N->getOperand(0);
27995 SDValue N1 = N->getOperand(1);
27998 if (VT != MVT::v2i64 && VT != MVT::v4i64 &&
27999 VT != MVT::v8i64 && VT != MVT::v16i32 &&
28000 VT != MVT::v4i32 && VT != MVT::v8i32) // Legal with VLX
28003 // Canonicalize XOR to the left.
28004 if (N1.getOpcode() == ISD::XOR)
28007 if (N0.getOpcode() != ISD::XOR)
28010 SDValue N00 = N0->getOperand(0);
28011 SDValue N01 = N0->getOperand(1);
28013 N01 = peekThroughBitcasts(N01);
28015 // Either match a direct AllOnes for 128, 256, and 512-bit vectors, or an
28016 // insert_subvector building a 256-bit AllOnes vector.
28017 if (!ISD::isBuildVectorAllOnes(N01.getNode())) {
28018 if (!VT.is256BitVector() || N01->getOpcode() != ISD::INSERT_SUBVECTOR)
28021 SDValue V1 = N01->getOperand(0);
28022 SDValue V2 = N01->getOperand(1);
28023 if (V1.getOpcode() != ISD::INSERT_SUBVECTOR ||
28024 !V1.getOperand(0).isUndef() ||
28025 !ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) ||
28026 !ISD::isBuildVectorAllOnes(V2.getNode()))
28029 return DAG.getNode(X86ISD::ANDNP, DL, VT, N00, N1);
28032 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
28033 // register. In most cases we actually compare or select YMM-sized registers
28034 // and mixing the two types creates horrible code. This method optimizes
28035 // some of the transition sequences.
28036 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
28037 TargetLowering::DAGCombinerInfo &DCI,
28038 const X86Subtarget &Subtarget) {
28039 EVT VT = N->getValueType(0);
28040 if (!VT.is256BitVector())
28043 assert((N->getOpcode() == ISD::ANY_EXTEND ||
28044 N->getOpcode() == ISD::ZERO_EXTEND ||
28045 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
28047 SDValue Narrow = N->getOperand(0);
28048 EVT NarrowVT = Narrow->getValueType(0);
28049 if (!NarrowVT.is128BitVector())
28052 if (Narrow->getOpcode() != ISD::XOR &&
28053 Narrow->getOpcode() != ISD::AND &&
28054 Narrow->getOpcode() != ISD::OR)
28057 SDValue N0 = Narrow->getOperand(0);
28058 SDValue N1 = Narrow->getOperand(1);
28061 // The Left side has to be a trunc.
28062 if (N0.getOpcode() != ISD::TRUNCATE)
28065 // The type of the truncated inputs.
28066 EVT WideVT = N0->getOperand(0)->getValueType(0);
28070 // The right side has to be a 'trunc' or a constant vector.
28071 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
28072 ConstantSDNode *RHSConstSplat = nullptr;
28073 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
28074 RHSConstSplat = RHSBV->getConstantSplatNode();
28075 if (!RHSTrunc && !RHSConstSplat)
28078 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28080 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
28083 // Set N0 and N1 to hold the inputs to the new wide operation.
28084 N0 = N0->getOperand(0);
28085 if (RHSConstSplat) {
28086 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
28087 SDValue(RHSConstSplat, 0));
28088 N1 = DAG.getSplatBuildVector(WideVT, DL, N1);
28089 } else if (RHSTrunc) {
28090 N1 = N1->getOperand(0);
28093 // Generate the wide operation.
28094 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
28095 unsigned Opcode = N->getOpcode();
28097 case ISD::ANY_EXTEND:
28099 case ISD::ZERO_EXTEND: {
28100 unsigned InBits = NarrowVT.getScalarSizeInBits();
28101 APInt Mask = APInt::getAllOnesValue(InBits);
28102 Mask = Mask.zext(VT.getScalarSizeInBits());
28103 return DAG.getNode(ISD::AND, DL, VT,
28104 Op, DAG.getConstant(Mask, DL, VT));
28106 case ISD::SIGN_EXTEND:
28107 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
28108 Op, DAG.getValueType(NarrowVT));
28110 llvm_unreachable("Unexpected opcode");
28114 static SDValue combineVectorZext(SDNode *N, SelectionDAG &DAG,
28115 TargetLowering::DAGCombinerInfo &DCI,
28116 const X86Subtarget &Subtarget) {
28117 SDValue N0 = N->getOperand(0);
28118 SDValue N1 = N->getOperand(1);
28121 // A vector zext_in_reg may be represented as a shuffle,
28122 // feeding into a bitcast (this represents anyext) feeding into
28123 // an and with a mask.
28124 // We'd like to try to combine that into a shuffle with zero
28125 // plus a bitcast, removing the and.
28126 if (N0.getOpcode() != ISD::BITCAST ||
28127 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
28130 // The other side of the AND should be a splat of 2^C, where C
28131 // is the number of bits in the source type.
28132 N1 = peekThroughBitcasts(N1);
28133 if (N1.getOpcode() != ISD::BUILD_VECTOR)
28135 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
28137 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
28138 EVT SrcType = Shuffle->getValueType(0);
28140 // We expect a single-source shuffle
28141 if (!Shuffle->getOperand(1)->isUndef())
28144 unsigned SrcSize = SrcType.getScalarSizeInBits();
28145 unsigned NumElems = SrcType.getVectorNumElements();
28147 APInt SplatValue, SplatUndef;
28148 unsigned SplatBitSize;
28150 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
28151 SplatBitSize, HasAnyUndefs))
28154 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
28155 // Make sure the splat matches the mask we expect
28156 if (SplatBitSize > ResSize ||
28157 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
28160 // Make sure the input and output size make sense
28161 if (SrcSize >= ResSize || ResSize % SrcSize)
28164 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
28165 // The number of u's between each two values depends on the ratio between
28166 // the source and dest type.
28167 unsigned ZextRatio = ResSize / SrcSize;
28168 bool IsZext = true;
28169 for (unsigned i = 0; i != NumElems; ++i) {
28170 if (i % ZextRatio) {
28171 if (Shuffle->getMaskElt(i) > 0) {
28177 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
28178 // Expected element number
28188 // Ok, perform the transformation - replace the shuffle with
28189 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
28190 // (instead of undef) where the k elements come from the zero vector.
28191 SmallVector<int, 8> Mask;
28192 for (unsigned i = 0; i != NumElems; ++i)
28194 Mask.push_back(NumElems);
28196 Mask.push_back(i / ZextRatio);
28198 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
28199 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
28200 return DAG.getBitcast(N0.getValueType(), NewShuffle);
28203 /// If both input operands of a logic op are being cast from floating point
28204 /// types, try to convert this into a floating point logic node to avoid
28205 /// unnecessary moves from SSE to integer registers.
28206 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
28207 const X86Subtarget &Subtarget) {
28208 unsigned FPOpcode = ISD::DELETED_NODE;
28209 if (N->getOpcode() == ISD::AND)
28210 FPOpcode = X86ISD::FAND;
28211 else if (N->getOpcode() == ISD::OR)
28212 FPOpcode = X86ISD::FOR;
28213 else if (N->getOpcode() == ISD::XOR)
28214 FPOpcode = X86ISD::FXOR;
28216 assert(FPOpcode != ISD::DELETED_NODE &&
28217 "Unexpected input node for FP logic conversion");
28219 EVT VT = N->getValueType(0);
28220 SDValue N0 = N->getOperand(0);
28221 SDValue N1 = N->getOperand(1);
28223 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
28224 ((Subtarget.hasSSE1() && VT == MVT::i32) ||
28225 (Subtarget.hasSSE2() && VT == MVT::i64))) {
28226 SDValue N00 = N0.getOperand(0);
28227 SDValue N10 = N1.getOperand(0);
28228 EVT N00Type = N00.getValueType();
28229 EVT N10Type = N10.getValueType();
28230 if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
28231 SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
28232 return DAG.getBitcast(VT, FPLogic);
28238 /// If this is a PCMPEQ or PCMPGT result that is bitwise-anded with 1 (this is
28239 /// the x86 lowering of a SETCC + ZEXT), replace the 'and' with a shift-right to
28240 /// eliminate loading the vector constant mask value. This relies on the fact
28241 /// that a PCMP always creates an all-ones or all-zeros bitmask per element.
28242 static SDValue combinePCMPAnd1(SDNode *N, SelectionDAG &DAG) {
28243 SDValue Op0 = peekThroughBitcasts(N->getOperand(0));
28244 SDValue Op1 = peekThroughBitcasts(N->getOperand(1));
28246 // TODO: Use AssertSext to mark any nodes that have the property of producing
28247 // all-ones or all-zeros. Then check for that node rather than particular
28249 if (Op0.getOpcode() != X86ISD::PCMPEQ && Op0.getOpcode() != X86ISD::PCMPGT)
28252 // The existence of the PCMP node guarantees that we have the required SSE2 or
28253 // AVX2 for a shift of this vector type, but there is no vector shift by
28254 // immediate for a vector with byte elements (PSRLB). 512-bit vectors use the
28255 // masked compare nodes, so they should not make it here.
28256 EVT VT0 = Op0.getValueType();
28257 EVT VT1 = Op1.getValueType();
28258 unsigned EltBitWidth = VT0.getScalarType().getSizeInBits();
28259 if (VT0 != VT1 || EltBitWidth == 8)
28262 assert(VT0.getSizeInBits() == 128 || VT0.getSizeInBits() == 256);
28265 if (!ISD::isConstantSplatVector(Op1.getNode(), SplatVal) || SplatVal != 1)
28269 SDValue ShAmt = DAG.getConstant(EltBitWidth - 1, DL, MVT::i8);
28270 SDValue Shift = DAG.getNode(X86ISD::VSRLI, DL, VT0, Op0, ShAmt);
28271 return DAG.getBitcast(N->getValueType(0), Shift);
28274 static SDValue combineAnd(SDNode *N, SelectionDAG &DAG,
28275 TargetLowering::DAGCombinerInfo &DCI,
28276 const X86Subtarget &Subtarget) {
28277 if (DCI.isBeforeLegalizeOps())
28280 if (SDValue Zext = combineVectorZext(N, DAG, DCI, Subtarget))
28283 if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
28286 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
28289 if (SDValue R = combineANDXORWithAllOnesIntoANDNP(N, DAG))
28292 if (SDValue ShiftRight = combinePCMPAnd1(N, DAG))
28295 EVT VT = N->getValueType(0);
28296 SDValue N0 = N->getOperand(0);
28297 SDValue N1 = N->getOperand(1);
28300 // Create BEXTR instructions
28301 // BEXTR is ((X >> imm) & (2**size-1))
28302 if (VT != MVT::i32 && VT != MVT::i64)
28305 if (!Subtarget.hasBMI() && !Subtarget.hasTBM())
28307 if (N0.getOpcode() != ISD::SRA && N0.getOpcode() != ISD::SRL)
28310 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
28311 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
28312 if (MaskNode && ShiftNode) {
28313 uint64_t Mask = MaskNode->getZExtValue();
28314 uint64_t Shift = ShiftNode->getZExtValue();
28315 if (isMask_64(Mask)) {
28316 uint64_t MaskSize = countPopulation(Mask);
28317 if (Shift + MaskSize <= VT.getSizeInBits())
28318 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
28319 DAG.getConstant(Shift | (MaskSize << 8), DL,
28327 // (or (and (m, y), (pandn m, x)))
28329 // (vselect m, x, y)
28330 // As a special case, try to fold:
28331 // (or (and (m, (sub 0, x)), (pandn m, x)))
28333 // (sub (xor X, M), M)
28334 static SDValue combineLogicBlendIntoPBLENDV(SDNode *N, SelectionDAG &DAG,
28335 const X86Subtarget &Subtarget) {
28336 assert(N->getOpcode() == ISD::OR);
28338 SDValue N0 = N->getOperand(0);
28339 SDValue N1 = N->getOperand(1);
28340 EVT VT = N->getValueType(0);
28342 if (!((VT == MVT::v2i64) || (VT == MVT::v4i64 && Subtarget.hasInt256())))
28344 assert(Subtarget.hasSSE2() && "Unexpected i64 vector without SSE2!");
28346 // Canonicalize pandn to RHS
28347 if (N0.getOpcode() == X86ISD::ANDNP)
28350 if (N0.getOpcode() != ISD::AND || N1.getOpcode() != X86ISD::ANDNP)
28353 SDValue Mask = N1.getOperand(0);
28354 SDValue X = N1.getOperand(1);
28356 if (N0.getOperand(0) == Mask)
28357 Y = N0.getOperand(1);
28358 if (N0.getOperand(1) == Mask)
28359 Y = N0.getOperand(0);
28361 // Check to see if the mask appeared in both the AND and ANDNP.
28365 // Validate that X, Y, and Mask are bitcasts, and see through them.
28366 Mask = peekThroughBitcasts(Mask);
28367 X = peekThroughBitcasts(X);
28368 Y = peekThroughBitcasts(Y);
28370 EVT MaskVT = Mask.getValueType();
28372 // Validate that the Mask operand is a vector sra node.
28373 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
28374 // there is no psrai.b
28375 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
28376 unsigned SraAmt = ~0;
28377 if (Mask.getOpcode() == ISD::SRA) {
28378 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
28379 if (auto *AmtConst = AmtBV->getConstantSplatNode())
28380 SraAmt = AmtConst->getZExtValue();
28381 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
28382 SDValue SraC = Mask.getOperand(1);
28383 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
28385 if ((SraAmt + 1) != EltBits)
28391 // (or (and (M, (sub 0, X)), (pandn M, X)))
28392 // which is a special case of vselect:
28393 // (vselect M, (sub 0, X), X)
28395 // http://graphics.stanford.edu/~seander/bithacks.html#ConditionalNegate
28396 // We know that, if fNegate is 0 or 1:
28397 // (fNegate ? -v : v) == ((v ^ -fNegate) + fNegate)
28399 // Here, we have a mask, M (all 1s or 0), and, similarly, we know that:
28400 // ((M & 1) ? -X : X) == ((X ^ -(M & 1)) + (M & 1))
28401 // ( M ? -X : X) == ((X ^ M ) + (M & 1))
28402 // This lets us transform our vselect to:
28403 // (add (xor X, M), (and M, 1))
28405 // (sub (xor X, M), M)
28406 if (X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
28407 auto IsNegV = [](SDNode *N, SDValue V) {
28408 return N->getOpcode() == ISD::SUB && N->getOperand(1) == V &&
28409 ISD::isBuildVectorAllZeros(N->getOperand(0).getNode());
28412 if (IsNegV(Y.getNode(), X))
28414 else if (IsNegV(X.getNode(), Y))
28418 assert(EltBits == 8 || EltBits == 16 || EltBits == 32);
28419 SDValue SubOp1 = DAG.getNode(ISD::XOR, DL, MaskVT, V, Mask);
28420 SDValue SubOp2 = Mask;
28422 // If the negate was on the false side of the select, then
28423 // the operands of the SUB need to be swapped. PR 27251.
28424 // This is because the pattern being matched above is
28425 // (vselect M, (sub (0, X), X) -> (sub (xor X, M), M)
28426 // but if the pattern matched was
28427 // (vselect M, X, (sub (0, X))), that is really negation of the pattern
28428 // above, -(vselect M, (sub 0, X), X), and therefore the replacement
28429 // pattern also needs to be a negation of the replacement pattern above.
28430 // And -(sub X, Y) is just sub (Y, X), so swapping the operands of the
28431 // sub accomplishes the negation of the replacement pattern.
28433 std::swap(SubOp1, SubOp2);
28435 return DAG.getBitcast(VT,
28436 DAG.getNode(ISD::SUB, DL, MaskVT, SubOp1, SubOp2));
28440 // PBLENDVB is only available on SSE 4.1.
28441 if (!Subtarget.hasSSE41())
28444 MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
28446 X = DAG.getBitcast(BlendVT, X);
28447 Y = DAG.getBitcast(BlendVT, Y);
28448 Mask = DAG.getBitcast(BlendVT, Mask);
28449 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
28450 return DAG.getBitcast(VT, Mask);
28453 static SDValue combineOr(SDNode *N, SelectionDAG &DAG,
28454 TargetLowering::DAGCombinerInfo &DCI,
28455 const X86Subtarget &Subtarget) {
28456 if (DCI.isBeforeLegalizeOps())
28459 if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
28462 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
28465 if (SDValue R = combineLogicBlendIntoPBLENDV(N, DAG, Subtarget))
28468 SDValue N0 = N->getOperand(0);
28469 SDValue N1 = N->getOperand(1);
28470 EVT VT = N->getValueType(0);
28472 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
28475 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
28476 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
28478 // SHLD/SHRD instructions have lower register pressure, but on some
28479 // platforms they have higher latency than the equivalent
28480 // series of shifts/or that would otherwise be generated.
28481 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
28482 // have higher latencies and we are not optimizing for size.
28483 if (!OptForSize && Subtarget.isSHLDSlow())
28486 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
28488 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
28490 if (!N0.hasOneUse() || !N1.hasOneUse())
28493 SDValue ShAmt0 = N0.getOperand(1);
28494 if (ShAmt0.getValueType() != MVT::i8)
28496 SDValue ShAmt1 = N1.getOperand(1);
28497 if (ShAmt1.getValueType() != MVT::i8)
28499 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
28500 ShAmt0 = ShAmt0.getOperand(0);
28501 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
28502 ShAmt1 = ShAmt1.getOperand(0);
28505 unsigned Opc = X86ISD::SHLD;
28506 SDValue Op0 = N0.getOperand(0);
28507 SDValue Op1 = N1.getOperand(0);
28508 if (ShAmt0.getOpcode() == ISD::SUB) {
28509 Opc = X86ISD::SHRD;
28510 std::swap(Op0, Op1);
28511 std::swap(ShAmt0, ShAmt1);
28514 unsigned Bits = VT.getSizeInBits();
28515 if (ShAmt1.getOpcode() == ISD::SUB) {
28516 SDValue Sum = ShAmt1.getOperand(0);
28517 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
28518 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
28519 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
28520 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
28521 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
28522 return DAG.getNode(Opc, DL, VT,
28524 DAG.getNode(ISD::TRUNCATE, DL,
28527 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
28528 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
28530 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
28531 return DAG.getNode(Opc, DL, VT,
28532 N0.getOperand(0), N1.getOperand(0),
28533 DAG.getNode(ISD::TRUNCATE, DL,
28540 // Generate NEG and CMOV for integer abs.
28541 static SDValue combineIntegerAbs(SDNode *N, SelectionDAG &DAG) {
28542 EVT VT = N->getValueType(0);
28544 // Since X86 does not have CMOV for 8-bit integer, we don't convert
28545 // 8-bit integer abs to NEG and CMOV.
28546 if (VT.isInteger() && VT.getSizeInBits() == 8)
28549 SDValue N0 = N->getOperand(0);
28550 SDValue N1 = N->getOperand(1);
28553 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
28554 // and change it to SUB and CMOV.
28555 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
28556 N0.getOpcode() == ISD::ADD &&
28557 N0.getOperand(1) == N1 &&
28558 N1.getOpcode() == ISD::SRA &&
28559 N1.getOperand(0) == N0.getOperand(0))
28560 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
28561 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
28562 // Generate SUB & CMOV.
28563 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
28564 DAG.getConstant(0, DL, VT), N0.getOperand(0));
28566 SDValue Ops[] = { N0.getOperand(0), Neg,
28567 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
28568 SDValue(Neg.getNode(), 1) };
28569 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
28574 /// Try to turn tests against the signbit in the form of:
28575 /// XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
28578 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
28579 // This is only worth doing if the output type is i8 or i1.
28580 EVT ResultType = N->getValueType(0);
28581 if (ResultType != MVT::i8 && ResultType != MVT::i1)
28584 SDValue N0 = N->getOperand(0);
28585 SDValue N1 = N->getOperand(1);
28587 // We should be performing an xor against a truncated shift.
28588 if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
28591 // Make sure we are performing an xor against one.
28592 if (!isOneConstant(N1))
28595 // SetCC on x86 zero extends so only act on this if it's a logical shift.
28596 SDValue Shift = N0.getOperand(0);
28597 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
28600 // Make sure we are truncating from one of i16, i32 or i64.
28601 EVT ShiftTy = Shift.getValueType();
28602 if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
28605 // Make sure the shift amount extracts the sign bit.
28606 if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
28607 Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
28610 // Create a greater-than comparison against -1.
28611 // N.B. Using SETGE against 0 works but we want a canonical looking
28612 // comparison, using SETGT matches up with what TranslateX86CC.
28614 SDValue ShiftOp = Shift.getOperand(0);
28615 EVT ShiftOpTy = ShiftOp.getValueType();
28616 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28617 EVT SetCCResultType = TLI.getSetCCResultType(DAG.getDataLayout(),
28618 *DAG.getContext(), ResultType);
28619 SDValue Cond = DAG.getSetCC(DL, SetCCResultType, ShiftOp,
28620 DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
28621 if (SetCCResultType != ResultType)
28622 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, ResultType, Cond);
28626 /// Turn vector tests of the signbit in the form of:
28627 /// xor (sra X, elt_size(X)-1), -1
28631 /// This should be called before type legalization because the pattern may not
28632 /// persist after that.
28633 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
28634 const X86Subtarget &Subtarget) {
28635 EVT VT = N->getValueType(0);
28636 if (!VT.isSimple())
28639 switch (VT.getSimpleVT().SimpleTy) {
28640 default: return SDValue();
28643 case MVT::v4i32: if (!Subtarget.hasSSE2()) return SDValue(); break;
28644 case MVT::v2i64: if (!Subtarget.hasSSE42()) return SDValue(); break;
28648 case MVT::v4i64: if (!Subtarget.hasAVX2()) return SDValue(); break;
28651 // There must be a shift right algebraic before the xor, and the xor must be a
28652 // 'not' operation.
28653 SDValue Shift = N->getOperand(0);
28654 SDValue Ones = N->getOperand(1);
28655 if (Shift.getOpcode() != ISD::SRA || !Shift.hasOneUse() ||
28656 !ISD::isBuildVectorAllOnes(Ones.getNode()))
28659 // The shift should be smearing the sign bit across each vector element.
28660 auto *ShiftBV = dyn_cast<BuildVectorSDNode>(Shift.getOperand(1));
28664 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
28665 auto *ShiftAmt = ShiftBV->getConstantSplatNode();
28666 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
28669 // Create a greater-than comparison against -1. We don't use the more obvious
28670 // greater-than-or-equal-to-zero because SSE/AVX don't have that instruction.
28671 return DAG.getNode(X86ISD::PCMPGT, SDLoc(N), VT, Shift.getOperand(0), Ones);
28674 static SDValue combineXor(SDNode *N, SelectionDAG &DAG,
28675 TargetLowering::DAGCombinerInfo &DCI,
28676 const X86Subtarget &Subtarget) {
28677 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
28680 if (DCI.isBeforeLegalizeOps())
28683 if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
28686 if (Subtarget.hasCMov())
28687 if (SDValue RV = combineIntegerAbs(N, DAG))
28690 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
28696 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
28697 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
28698 /// X86ISD::AVG instruction.
28699 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
28700 const X86Subtarget &Subtarget,
28702 if (!VT.isVector() || !VT.isSimple())
28704 EVT InVT = In.getValueType();
28705 unsigned NumElems = VT.getVectorNumElements();
28707 EVT ScalarVT = VT.getVectorElementType();
28708 if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
28709 isPowerOf2_32(NumElems)))
28712 // InScalarVT is the intermediate type in AVG pattern and it should be greater
28713 // than the original input type (i8/i16).
28714 EVT InScalarVT = InVT.getVectorElementType();
28715 if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
28718 if (!Subtarget.hasSSE2())
28720 if (Subtarget.hasAVX512()) {
28721 if (VT.getSizeInBits() > 512)
28723 } else if (Subtarget.hasAVX2()) {
28724 if (VT.getSizeInBits() > 256)
28727 if (VT.getSizeInBits() > 128)
28731 // Detect the following pattern:
28733 // %1 = zext <N x i8> %a to <N x i32>
28734 // %2 = zext <N x i8> %b to <N x i32>
28735 // %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
28736 // %4 = add nuw nsw <N x i32> %3, %2
28737 // %5 = lshr <N x i32> %N, <i32 1 x N>
28738 // %6 = trunc <N x i32> %5 to <N x i8>
28740 // In AVX512, the last instruction can also be a trunc store.
28742 if (In.getOpcode() != ISD::SRL)
28745 // A lambda checking the given SDValue is a constant vector and each element
28746 // is in the range [Min, Max].
28747 auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
28748 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
28749 if (!BV || !BV->isConstant())
28751 for (unsigned i = 0, e = V.getNumOperands(); i < e; i++) {
28752 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(i));
28755 uint64_t Val = C->getZExtValue();
28756 if (Val < Min || Val > Max)
28762 // Check if each element of the vector is left-shifted by one.
28763 auto LHS = In.getOperand(0);
28764 auto RHS = In.getOperand(1);
28765 if (!IsConstVectorInRange(RHS, 1, 1))
28767 if (LHS.getOpcode() != ISD::ADD)
28770 // Detect a pattern of a + b + 1 where the order doesn't matter.
28771 SDValue Operands[3];
28772 Operands[0] = LHS.getOperand(0);
28773 Operands[1] = LHS.getOperand(1);
28775 // Take care of the case when one of the operands is a constant vector whose
28776 // element is in the range [1, 256].
28777 if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
28778 Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
28779 Operands[0].getOperand(0).getValueType() == VT) {
28780 // The pattern is detected. Subtract one from the constant vector, then
28781 // demote it and emit X86ISD::AVG instruction.
28782 SDValue VecOnes = DAG.getConstant(1, DL, InVT);
28783 Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], VecOnes);
28784 Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
28785 return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
28789 if (Operands[0].getOpcode() == ISD::ADD)
28790 std::swap(Operands[0], Operands[1]);
28791 else if (Operands[1].getOpcode() != ISD::ADD)
28793 Operands[2] = Operands[1].getOperand(0);
28794 Operands[1] = Operands[1].getOperand(1);
28796 // Now we have three operands of two additions. Check that one of them is a
28797 // constant vector with ones, and the other two are promoted from i8/i16.
28798 for (int i = 0; i < 3; ++i) {
28799 if (!IsConstVectorInRange(Operands[i], 1, 1))
28801 std::swap(Operands[i], Operands[2]);
28803 // Check if Operands[0] and Operands[1] are results of type promotion.
28804 for (int j = 0; j < 2; ++j)
28805 if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
28806 Operands[j].getOperand(0).getValueType() != VT)
28809 // The pattern is detected, emit X86ISD::AVG instruction.
28810 return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
28811 Operands[1].getOperand(0));
28817 static SDValue combineLoad(SDNode *N, SelectionDAG &DAG,
28818 TargetLowering::DAGCombinerInfo &DCI,
28819 const X86Subtarget &Subtarget) {
28820 LoadSDNode *Ld = cast<LoadSDNode>(N);
28821 EVT RegVT = Ld->getValueType(0);
28822 EVT MemVT = Ld->getMemoryVT();
28824 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28826 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
28827 // into two 16-byte operations.
28828 ISD::LoadExtType Ext = Ld->getExtensionType();
28830 unsigned AddressSpace = Ld->getAddressSpace();
28831 unsigned Alignment = Ld->getAlignment();
28832 if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
28833 Ext == ISD::NON_EXTLOAD &&
28834 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
28835 AddressSpace, Alignment, &Fast) && !Fast) {
28836 unsigned NumElems = RegVT.getVectorNumElements();
28840 SDValue Ptr = Ld->getBasePtr();
28842 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
28845 DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
28846 Alignment, Ld->getMemOperand()->getFlags());
28848 Ptr = DAG.getMemBasePlusOffset(Ptr, 16, dl);
28850 DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
28851 std::min(16U, Alignment), Ld->getMemOperand()->getFlags());
28852 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
28854 Load2.getValue(1));
28856 SDValue NewVec = DAG.getUNDEF(RegVT);
28857 NewVec = insert128BitVector(NewVec, Load1, 0, DAG, dl);
28858 NewVec = insert128BitVector(NewVec, Load2, NumElems / 2, DAG, dl);
28859 return DCI.CombineTo(N, NewVec, TF, true);
28865 /// If V is a build vector of boolean constants and exactly one of those
28866 /// constants is true, return the operand index of that true element.
28867 /// Otherwise, return -1.
28868 static int getOneTrueElt(SDValue V) {
28869 // This needs to be a build vector of booleans.
28870 // TODO: Checking for the i1 type matches the IR definition for the mask,
28871 // but the mask check could be loosened to i8 or other types. That might
28872 // also require checking more than 'allOnesValue'; eg, the x86 HW
28873 // instructions only require that the MSB is set for each mask element.
28874 // The ISD::MSTORE comments/definition do not specify how the mask operand
28876 auto *BV = dyn_cast<BuildVectorSDNode>(V);
28877 if (!BV || BV->getValueType(0).getVectorElementType() != MVT::i1)
28880 int TrueIndex = -1;
28881 unsigned NumElts = BV->getValueType(0).getVectorNumElements();
28882 for (unsigned i = 0; i < NumElts; ++i) {
28883 const SDValue &Op = BV->getOperand(i);
28886 auto *ConstNode = dyn_cast<ConstantSDNode>(Op);
28889 if (ConstNode->getAPIntValue().isAllOnesValue()) {
28890 // If we already found a one, this is too many.
28891 if (TrueIndex >= 0)
28899 /// Given a masked memory load/store operation, return true if it has one mask
28900 /// bit set. If it has one mask bit set, then also return the memory address of
28901 /// the scalar element to load/store, the vector index to insert/extract that
28902 /// scalar element, and the alignment for the scalar memory access.
28903 static bool getParamsForOneTrueMaskedElt(MaskedLoadStoreSDNode *MaskedOp,
28904 SelectionDAG &DAG, SDValue &Addr,
28905 SDValue &Index, unsigned &Alignment) {
28906 int TrueMaskElt = getOneTrueElt(MaskedOp->getMask());
28907 if (TrueMaskElt < 0)
28910 // Get the address of the one scalar element that is specified by the mask
28911 // using the appropriate offset from the base pointer.
28912 EVT EltVT = MaskedOp->getMemoryVT().getVectorElementType();
28913 Addr = MaskedOp->getBasePtr();
28914 if (TrueMaskElt != 0) {
28915 unsigned Offset = TrueMaskElt * EltVT.getStoreSize();
28916 Addr = DAG.getMemBasePlusOffset(Addr, Offset, SDLoc(MaskedOp));
28919 Index = DAG.getIntPtrConstant(TrueMaskElt, SDLoc(MaskedOp));
28920 Alignment = MinAlign(MaskedOp->getAlignment(), EltVT.getStoreSize());
28924 /// If exactly one element of the mask is set for a non-extending masked load,
28925 /// it is a scalar load and vector insert.
28926 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
28927 /// mask have already been optimized in IR, so we don't bother with those here.
28929 reduceMaskedLoadToScalarLoad(MaskedLoadSDNode *ML, SelectionDAG &DAG,
28930 TargetLowering::DAGCombinerInfo &DCI) {
28931 // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
28932 // However, some target hooks may need to be added to know when the transform
28933 // is profitable. Endianness would also have to be considered.
28935 SDValue Addr, VecIndex;
28936 unsigned Alignment;
28937 if (!getParamsForOneTrueMaskedElt(ML, DAG, Addr, VecIndex, Alignment))
28940 // Load the one scalar element that is specified by the mask using the
28941 // appropriate offset from the base pointer.
28943 EVT VT = ML->getValueType(0);
28944 EVT EltVT = VT.getVectorElementType();
28946 DAG.getLoad(EltVT, DL, ML->getChain(), Addr, ML->getPointerInfo(),
28947 Alignment, ML->getMemOperand()->getFlags());
28949 // Insert the loaded element into the appropriate place in the vector.
28950 SDValue Insert = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, ML->getSrc0(),
28952 return DCI.CombineTo(ML, Insert, Load.getValue(1), true);
28956 combineMaskedLoadConstantMask(MaskedLoadSDNode *ML, SelectionDAG &DAG,
28957 TargetLowering::DAGCombinerInfo &DCI) {
28958 if (!ISD::isBuildVectorOfConstantSDNodes(ML->getMask().getNode()))
28962 EVT VT = ML->getValueType(0);
28964 // If we are loading the first and last elements of a vector, it is safe and
28965 // always faster to load the whole vector. Replace the masked load with a
28966 // vector load and select.
28967 unsigned NumElts = VT.getVectorNumElements();
28968 BuildVectorSDNode *MaskBV = cast<BuildVectorSDNode>(ML->getMask());
28969 bool LoadFirstElt = !isNullConstant(MaskBV->getOperand(0));
28970 bool LoadLastElt = !isNullConstant(MaskBV->getOperand(NumElts - 1));
28971 if (LoadFirstElt && LoadLastElt) {
28972 SDValue VecLd = DAG.getLoad(VT, DL, ML->getChain(), ML->getBasePtr(),
28973 ML->getMemOperand());
28974 SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), VecLd, ML->getSrc0());
28975 return DCI.CombineTo(ML, Blend, VecLd.getValue(1), true);
28978 // Convert a masked load with a constant mask into a masked load and a select.
28979 // This allows the select operation to use a faster kind of select instruction
28980 // (for example, vblendvps -> vblendps).
28982 // Don't try this if the pass-through operand is already undefined. That would
28983 // cause an infinite loop because that's what we're about to create.
28984 if (ML->getSrc0().isUndef())
28987 // The new masked load has an undef pass-through operand. The select uses the
28988 // original pass-through operand.
28989 SDValue NewML = DAG.getMaskedLoad(VT, DL, ML->getChain(), ML->getBasePtr(),
28990 ML->getMask(), DAG.getUNDEF(VT),
28991 ML->getMemoryVT(), ML->getMemOperand(),
28992 ML->getExtensionType());
28993 SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), NewML, ML->getSrc0());
28995 return DCI.CombineTo(ML, Blend, NewML.getValue(1), true);
28998 static SDValue combineMaskedLoad(SDNode *N, SelectionDAG &DAG,
28999 TargetLowering::DAGCombinerInfo &DCI,
29000 const X86Subtarget &Subtarget) {
29001 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
29002 if (Mld->getExtensionType() == ISD::NON_EXTLOAD) {
29003 if (SDValue ScalarLoad = reduceMaskedLoadToScalarLoad(Mld, DAG, DCI))
29005 // TODO: Do some AVX512 subsets benefit from this transform?
29006 if (!Subtarget.hasAVX512())
29007 if (SDValue Blend = combineMaskedLoadConstantMask(Mld, DAG, DCI))
29011 if (Mld->getExtensionType() != ISD::SEXTLOAD)
29014 // Resolve extending loads.
29015 EVT VT = Mld->getValueType(0);
29016 unsigned NumElems = VT.getVectorNumElements();
29017 EVT LdVT = Mld->getMemoryVT();
29020 assert(LdVT != VT && "Cannot extend to the same type");
29021 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
29022 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
29023 // From/To sizes and ElemCount must be pow of two.
29024 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
29025 "Unexpected size for extending masked load");
29027 unsigned SizeRatio = ToSz / FromSz;
29028 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
29030 // Create a type on which we perform the shuffle.
29031 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
29032 LdVT.getScalarType(), NumElems*SizeRatio);
29033 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
29035 // Convert Src0 value.
29036 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
29037 if (!Mld->getSrc0().isUndef()) {
29038 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
29039 for (unsigned i = 0; i != NumElems; ++i)
29040 ShuffleVec[i] = i * SizeRatio;
29042 // Can't shuffle using an illegal type.
29043 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
29044 "WideVecVT should be legal");
29045 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
29046 DAG.getUNDEF(WideVecVT), ShuffleVec);
29048 // Prepare the new mask.
29050 SDValue Mask = Mld->getMask();
29051 if (Mask.getValueType() == VT) {
29052 // Mask and original value have the same type.
29053 NewMask = DAG.getBitcast(WideVecVT, Mask);
29054 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
29055 for (unsigned i = 0; i != NumElems; ++i)
29056 ShuffleVec[i] = i * SizeRatio;
29057 for (unsigned i = NumElems; i != NumElems * SizeRatio; ++i)
29058 ShuffleVec[i] = NumElems * SizeRatio;
29059 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
29060 DAG.getConstant(0, dl, WideVecVT),
29063 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
29064 unsigned WidenNumElts = NumElems*SizeRatio;
29065 unsigned MaskNumElts = VT.getVectorNumElements();
29066 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
29069 unsigned NumConcat = WidenNumElts / MaskNumElts;
29070 SmallVector<SDValue, 16> Ops(NumConcat);
29071 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
29073 for (unsigned i = 1; i != NumConcat; ++i)
29076 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
29079 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
29080 Mld->getBasePtr(), NewMask, WideSrc0,
29081 Mld->getMemoryVT(), Mld->getMemOperand(),
29083 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
29084 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
29087 /// If exactly one element of the mask is set for a non-truncating masked store,
29088 /// it is a vector extract and scalar store.
29089 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
29090 /// mask have already been optimized in IR, so we don't bother with those here.
29091 static SDValue reduceMaskedStoreToScalarStore(MaskedStoreSDNode *MS,
29092 SelectionDAG &DAG) {
29093 // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
29094 // However, some target hooks may need to be added to know when the transform
29095 // is profitable. Endianness would also have to be considered.
29097 SDValue Addr, VecIndex;
29098 unsigned Alignment;
29099 if (!getParamsForOneTrueMaskedElt(MS, DAG, Addr, VecIndex, Alignment))
29102 // Extract the one scalar element that is actually being stored.
29104 EVT VT = MS->getValue().getValueType();
29105 EVT EltVT = VT.getVectorElementType();
29106 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT,
29107 MS->getValue(), VecIndex);
29109 // Store that element at the appropriate offset from the base pointer.
29110 return DAG.getStore(MS->getChain(), DL, Extract, Addr, MS->getPointerInfo(),
29111 Alignment, MS->getMemOperand()->getFlags());
29114 static SDValue combineMaskedStore(SDNode *N, SelectionDAG &DAG,
29115 const X86Subtarget &Subtarget) {
29116 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
29117 if (!Mst->isTruncatingStore())
29118 return reduceMaskedStoreToScalarStore(Mst, DAG);
29120 // Resolve truncating stores.
29121 EVT VT = Mst->getValue().getValueType();
29122 unsigned NumElems = VT.getVectorNumElements();
29123 EVT StVT = Mst->getMemoryVT();
29126 assert(StVT != VT && "Cannot truncate to the same type");
29127 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
29128 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
29130 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
29132 // The truncating store is legal in some cases. For example
29133 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
29134 // are designated for truncate store.
29135 // In this case we don't need any further transformations.
29136 if (TLI.isTruncStoreLegal(VT, StVT))
29139 // From/To sizes and ElemCount must be pow of two.
29140 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
29141 "Unexpected size for truncating masked store");
29142 // We are going to use the original vector elt for storing.
29143 // Accumulated smaller vector elements must be a multiple of the store size.
29144 assert (((NumElems * FromSz) % ToSz) == 0 &&
29145 "Unexpected ratio for truncating masked store");
29147 unsigned SizeRatio = FromSz / ToSz;
29148 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
29150 // Create a type on which we perform the shuffle.
29151 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
29152 StVT.getScalarType(), NumElems*SizeRatio);
29154 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
29156 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
29157 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
29158 for (unsigned i = 0; i != NumElems; ++i)
29159 ShuffleVec[i] = i * SizeRatio;
29161 // Can't shuffle using an illegal type.
29162 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
29163 "WideVecVT should be legal");
29165 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
29166 DAG.getUNDEF(WideVecVT),
29170 SDValue Mask = Mst->getMask();
29171 if (Mask.getValueType() == VT) {
29172 // Mask and original value have the same type.
29173 NewMask = DAG.getBitcast(WideVecVT, Mask);
29174 for (unsigned i = 0; i != NumElems; ++i)
29175 ShuffleVec[i] = i * SizeRatio;
29176 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
29177 ShuffleVec[i] = NumElems*SizeRatio;
29178 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
29179 DAG.getConstant(0, dl, WideVecVT),
29182 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
29183 unsigned WidenNumElts = NumElems*SizeRatio;
29184 unsigned MaskNumElts = VT.getVectorNumElements();
29185 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
29188 unsigned NumConcat = WidenNumElts / MaskNumElts;
29189 SmallVector<SDValue, 16> Ops(NumConcat);
29190 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
29192 for (unsigned i = 1; i != NumConcat; ++i)
29195 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
29198 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal,
29199 Mst->getBasePtr(), NewMask, StVT,
29200 Mst->getMemOperand(), false);
29203 static SDValue combineStore(SDNode *N, SelectionDAG &DAG,
29204 const X86Subtarget &Subtarget) {
29205 StoreSDNode *St = cast<StoreSDNode>(N);
29206 EVT VT = St->getValue().getValueType();
29207 EVT StVT = St->getMemoryVT();
29209 SDValue StoredVal = St->getOperand(1);
29210 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
29212 // If we are saving a concatenation of two XMM registers and 32-byte stores
29213 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
29215 unsigned AddressSpace = St->getAddressSpace();
29216 unsigned Alignment = St->getAlignment();
29217 if (VT.is256BitVector() && StVT == VT &&
29218 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
29219 AddressSpace, Alignment, &Fast) &&
29221 unsigned NumElems = VT.getVectorNumElements();
29225 SDValue Value0 = extract128BitVector(StoredVal, 0, DAG, dl);
29226 SDValue Value1 = extract128BitVector(StoredVal, NumElems / 2, DAG, dl);
29228 SDValue Ptr0 = St->getBasePtr();
29229 SDValue Ptr1 = DAG.getMemBasePlusOffset(Ptr0, 16, dl);
29232 DAG.getStore(St->getChain(), dl, Value0, Ptr0, St->getPointerInfo(),
29233 Alignment, St->getMemOperand()->getFlags());
29235 DAG.getStore(St->getChain(), dl, Value1, Ptr1, St->getPointerInfo(),
29236 std::min(16U, Alignment), St->getMemOperand()->getFlags());
29237 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
29240 // Optimize trunc store (of multiple scalars) to shuffle and store.
29241 // First, pack all of the elements in one place. Next, store to memory
29242 // in fewer chunks.
29243 if (St->isTruncatingStore() && VT.isVector()) {
29244 // Check if we can detect an AVG pattern from the truncation. If yes,
29245 // replace the trunc store by a normal store with the result of X86ISD::AVG
29247 if (SDValue Avg = detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG,
29249 return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
29250 St->getPointerInfo(), St->getAlignment(),
29251 St->getMemOperand()->getFlags());
29253 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
29254 unsigned NumElems = VT.getVectorNumElements();
29255 assert(StVT != VT && "Cannot truncate to the same type");
29256 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
29257 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
29259 // The truncating store is legal in some cases. For example
29260 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
29261 // are designated for truncate store.
29262 // In this case we don't need any further transformations.
29263 if (TLI.isTruncStoreLegalOrCustom(VT, StVT))
29266 // From, To sizes and ElemCount must be pow of two
29267 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
29268 // We are going to use the original vector elt for storing.
29269 // Accumulated smaller vector elements must be a multiple of the store size.
29270 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
29272 unsigned SizeRatio = FromSz / ToSz;
29274 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
29276 // Create a type on which we perform the shuffle
29277 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
29278 StVT.getScalarType(), NumElems*SizeRatio);
29280 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
29282 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
29283 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
29284 for (unsigned i = 0; i != NumElems; ++i)
29285 ShuffleVec[i] = i * SizeRatio;
29287 // Can't shuffle using an illegal type.
29288 if (!TLI.isTypeLegal(WideVecVT))
29291 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
29292 DAG.getUNDEF(WideVecVT),
29294 // At this point all of the data is stored at the bottom of the
29295 // register. We now need to save it to mem.
29297 // Find the largest store unit
29298 MVT StoreType = MVT::i8;
29299 for (MVT Tp : MVT::integer_valuetypes()) {
29300 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
29304 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
29305 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
29306 (64 <= NumElems * ToSz))
29307 StoreType = MVT::f64;
29309 // Bitcast the original vector into a vector of store-size units
29310 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
29311 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
29312 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
29313 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
29314 SmallVector<SDValue, 8> Chains;
29315 SDValue Ptr = St->getBasePtr();
29317 // Perform one or more big stores into memory.
29318 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
29319 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
29320 StoreType, ShuffWide,
29321 DAG.getIntPtrConstant(i, dl));
29323 DAG.getStore(St->getChain(), dl, SubVec, Ptr, St->getPointerInfo(),
29324 St->getAlignment(), St->getMemOperand()->getFlags());
29325 Ptr = DAG.getMemBasePlusOffset(Ptr, StoreType.getStoreSize(), dl);
29326 Chains.push_back(Ch);
29329 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
29332 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
29333 // the FP state in cases where an emms may be missing.
29334 // A preferable solution to the general problem is to figure out the right
29335 // places to insert EMMS. This qualifies as a quick hack.
29337 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
29338 if (VT.getSizeInBits() != 64)
29341 const Function *F = DAG.getMachineFunction().getFunction();
29342 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
29344 !Subtarget.useSoftFloat() && !NoImplicitFloatOps && Subtarget.hasSSE2();
29345 if ((VT.isVector() ||
29346 (VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit())) &&
29347 isa<LoadSDNode>(St->getValue()) &&
29348 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
29349 St->getChain().hasOneUse() && !St->isVolatile()) {
29350 SDNode* LdVal = St->getValue().getNode();
29351 LoadSDNode *Ld = nullptr;
29352 int TokenFactorIndex = -1;
29353 SmallVector<SDValue, 8> Ops;
29354 SDNode* ChainVal = St->getChain().getNode();
29355 // Must be a store of a load. We currently handle two cases: the load
29356 // is a direct child, and it's under an intervening TokenFactor. It is
29357 // possible to dig deeper under nested TokenFactors.
29358 if (ChainVal == LdVal)
29359 Ld = cast<LoadSDNode>(St->getChain());
29360 else if (St->getValue().hasOneUse() &&
29361 ChainVal->getOpcode() == ISD::TokenFactor) {
29362 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
29363 if (ChainVal->getOperand(i).getNode() == LdVal) {
29364 TokenFactorIndex = i;
29365 Ld = cast<LoadSDNode>(St->getValue());
29367 Ops.push_back(ChainVal->getOperand(i));
29371 if (!Ld || !ISD::isNormalLoad(Ld))
29374 // If this is not the MMX case, i.e. we are just turning i64 load/store
29375 // into f64 load/store, avoid the transformation if there are multiple
29376 // uses of the loaded value.
29377 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
29382 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
29383 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
29385 if (Subtarget.is64Bit() || F64IsLegal) {
29386 MVT LdVT = Subtarget.is64Bit() ? MVT::i64 : MVT::f64;
29387 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
29388 Ld->getPointerInfo(), Ld->getAlignment(),
29389 Ld->getMemOperand()->getFlags());
29390 SDValue NewChain = NewLd.getValue(1);
29391 if (TokenFactorIndex >= 0) {
29392 Ops.push_back(NewChain);
29393 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
29395 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
29396 St->getPointerInfo(), St->getAlignment(),
29397 St->getMemOperand()->getFlags());
29400 // Otherwise, lower to two pairs of 32-bit loads / stores.
29401 SDValue LoAddr = Ld->getBasePtr();
29402 SDValue HiAddr = DAG.getMemBasePlusOffset(LoAddr, 4, LdDL);
29404 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
29405 Ld->getPointerInfo(), Ld->getAlignment(),
29406 Ld->getMemOperand()->getFlags());
29407 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
29408 Ld->getPointerInfo().getWithOffset(4),
29409 MinAlign(Ld->getAlignment(), 4),
29410 Ld->getMemOperand()->getFlags());
29412 SDValue NewChain = LoLd.getValue(1);
29413 if (TokenFactorIndex >= 0) {
29414 Ops.push_back(LoLd);
29415 Ops.push_back(HiLd);
29416 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
29419 LoAddr = St->getBasePtr();
29420 HiAddr = DAG.getMemBasePlusOffset(LoAddr, 4, StDL);
29423 DAG.getStore(NewChain, StDL, LoLd, LoAddr, St->getPointerInfo(),
29424 St->getAlignment(), St->getMemOperand()->getFlags());
29425 SDValue HiSt = DAG.getStore(
29426 NewChain, StDL, HiLd, HiAddr, St->getPointerInfo().getWithOffset(4),
29427 MinAlign(St->getAlignment(), 4), St->getMemOperand()->getFlags());
29428 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
29431 // This is similar to the above case, but here we handle a scalar 64-bit
29432 // integer store that is extracted from a vector on a 32-bit target.
29433 // If we have SSE2, then we can treat it like a floating-point double
29434 // to get past legalization. The execution dependencies fixup pass will
29435 // choose the optimal machine instruction for the store if this really is
29436 // an integer or v2f32 rather than an f64.
29437 if (VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit() &&
29438 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
29439 SDValue OldExtract = St->getOperand(1);
29440 SDValue ExtOp0 = OldExtract.getOperand(0);
29441 unsigned VecSize = ExtOp0.getValueSizeInBits();
29442 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
29443 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
29444 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
29445 BitCast, OldExtract.getOperand(1));
29446 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
29447 St->getPointerInfo(), St->getAlignment(),
29448 St->getMemOperand()->getFlags());
29454 /// Return 'true' if this vector operation is "horizontal"
29455 /// and return the operands for the horizontal operation in LHS and RHS. A
29456 /// horizontal operation performs the binary operation on successive elements
29457 /// of its first operand, then on successive elements of its second operand,
29458 /// returning the resulting values in a vector. For example, if
29459 /// A = < float a0, float a1, float a2, float a3 >
29461 /// B = < float b0, float b1, float b2, float b3 >
29462 /// then the result of doing a horizontal operation on A and B is
29463 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
29464 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
29465 /// A horizontal-op B, for some already available A and B, and if so then LHS is
29466 /// set to A, RHS to B, and the routine returns 'true'.
29467 /// Note that the binary operation should have the property that if one of the
29468 /// operands is UNDEF then the result is UNDEF.
29469 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
29470 // Look for the following pattern: if
29471 // A = < float a0, float a1, float a2, float a3 >
29472 // B = < float b0, float b1, float b2, float b3 >
29474 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
29475 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
29476 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
29477 // which is A horizontal-op B.
29479 // At least one of the operands should be a vector shuffle.
29480 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
29481 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
29484 MVT VT = LHS.getSimpleValueType();
29486 assert((VT.is128BitVector() || VT.is256BitVector()) &&
29487 "Unsupported vector type for horizontal add/sub");
29489 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
29490 // operate independently on 128-bit lanes.
29491 unsigned NumElts = VT.getVectorNumElements();
29492 unsigned NumLanes = VT.getSizeInBits()/128;
29493 unsigned NumLaneElts = NumElts / NumLanes;
29494 assert((NumLaneElts % 2 == 0) &&
29495 "Vector type should have an even number of elements in each lane");
29496 unsigned HalfLaneElts = NumLaneElts/2;
29498 // View LHS in the form
29499 // LHS = VECTOR_SHUFFLE A, B, LMask
29500 // If LHS is not a shuffle then pretend it is the shuffle
29501 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
29502 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
29505 SmallVector<int, 16> LMask(NumElts);
29506 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
29507 if (!LHS.getOperand(0).isUndef())
29508 A = LHS.getOperand(0);
29509 if (!LHS.getOperand(1).isUndef())
29510 B = LHS.getOperand(1);
29511 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
29512 std::copy(Mask.begin(), Mask.end(), LMask.begin());
29514 if (!LHS.isUndef())
29516 for (unsigned i = 0; i != NumElts; ++i)
29520 // Likewise, view RHS in the form
29521 // RHS = VECTOR_SHUFFLE C, D, RMask
29523 SmallVector<int, 16> RMask(NumElts);
29524 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
29525 if (!RHS.getOperand(0).isUndef())
29526 C = RHS.getOperand(0);
29527 if (!RHS.getOperand(1).isUndef())
29528 D = RHS.getOperand(1);
29529 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
29530 std::copy(Mask.begin(), Mask.end(), RMask.begin());
29532 if (!RHS.isUndef())
29534 for (unsigned i = 0; i != NumElts; ++i)
29538 // Check that the shuffles are both shuffling the same vectors.
29539 if (!(A == C && B == D) && !(A == D && B == C))
29542 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
29543 if (!A.getNode() && !B.getNode())
29546 // If A and B occur in reverse order in RHS, then "swap" them (which means
29547 // rewriting the mask).
29549 ShuffleVectorSDNode::commuteMask(RMask);
29551 // At this point LHS and RHS are equivalent to
29552 // LHS = VECTOR_SHUFFLE A, B, LMask
29553 // RHS = VECTOR_SHUFFLE A, B, RMask
29554 // Check that the masks correspond to performing a horizontal operation.
29555 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
29556 for (unsigned i = 0; i != NumLaneElts; ++i) {
29557 int LIdx = LMask[i+l], RIdx = RMask[i+l];
29559 // Ignore any UNDEF components.
29560 if (LIdx < 0 || RIdx < 0 ||
29561 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
29562 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
29565 // Check that successive elements are being operated on. If not, this is
29566 // not a horizontal operation.
29567 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
29568 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
29569 if (!(LIdx == Index && RIdx == Index + 1) &&
29570 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
29575 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
29576 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
29580 /// Do target-specific dag combines on floating-point adds/subs.
29581 static SDValue combineFaddFsub(SDNode *N, SelectionDAG &DAG,
29582 const X86Subtarget &Subtarget) {
29583 EVT VT = N->getValueType(0);
29584 SDValue LHS = N->getOperand(0);
29585 SDValue RHS = N->getOperand(1);
29586 bool IsFadd = N->getOpcode() == ISD::FADD;
29587 assert((IsFadd || N->getOpcode() == ISD::FSUB) && "Wrong opcode");
29589 // Try to synthesize horizontal add/sub from adds/subs of shuffles.
29590 if (((Subtarget.hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
29591 (Subtarget.hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
29592 isHorizontalBinOp(LHS, RHS, IsFadd)) {
29593 auto NewOpcode = IsFadd ? X86ISD::FHADD : X86ISD::FHSUB;
29594 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
29599 /// Truncate a group of v4i32 into v16i8/v8i16 using X86ISD::PACKUS.
29601 combineVectorTruncationWithPACKUS(SDNode *N, SelectionDAG &DAG,
29602 SmallVector<SDValue, 8> &Regs) {
29603 assert(Regs.size() > 0 && (Regs[0].getValueType() == MVT::v4i32 ||
29604 Regs[0].getValueType() == MVT::v2i64));
29605 EVT OutVT = N->getValueType(0);
29606 EVT OutSVT = OutVT.getVectorElementType();
29607 EVT InVT = Regs[0].getValueType();
29608 EVT InSVT = InVT.getVectorElementType();
29611 // First, use mask to unset all bits that won't appear in the result.
29612 assert((OutSVT == MVT::i8 || OutSVT == MVT::i16) &&
29613 "OutSVT can only be either i8 or i16.");
29615 APInt::getLowBitsSet(InSVT.getSizeInBits(), OutSVT.getSizeInBits());
29616 SDValue MaskVal = DAG.getConstant(Mask, DL, InVT);
29617 for (auto &Reg : Regs)
29618 Reg = DAG.getNode(ISD::AND, DL, InVT, MaskVal, Reg);
29620 MVT UnpackedVT, PackedVT;
29621 if (OutSVT == MVT::i8) {
29622 UnpackedVT = MVT::v8i16;
29623 PackedVT = MVT::v16i8;
29625 UnpackedVT = MVT::v4i32;
29626 PackedVT = MVT::v8i16;
29629 // In each iteration, truncate the type by a half size.
29630 auto RegNum = Regs.size();
29631 for (unsigned j = 1, e = InSVT.getSizeInBits() / OutSVT.getSizeInBits();
29632 j < e; j *= 2, RegNum /= 2) {
29633 for (unsigned i = 0; i < RegNum; i++)
29634 Regs[i] = DAG.getBitcast(UnpackedVT, Regs[i]);
29635 for (unsigned i = 0; i < RegNum / 2; i++)
29636 Regs[i] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[i * 2],
29640 // If the type of the result is v8i8, we need do one more X86ISD::PACKUS, and
29641 // then extract a subvector as the result since v8i8 is not a legal type.
29642 if (OutVT == MVT::v8i8) {
29643 Regs[0] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[0], Regs[0]);
29644 Regs[0] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, Regs[0],
29645 DAG.getIntPtrConstant(0, DL));
29647 } else if (RegNum > 1) {
29648 Regs.resize(RegNum);
29649 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
29654 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
29656 combineVectorTruncationWithPACKSS(SDNode *N, SelectionDAG &DAG,
29657 SmallVector<SDValue, 8> &Regs) {
29658 assert(Regs.size() > 0 && Regs[0].getValueType() == MVT::v4i32);
29659 EVT OutVT = N->getValueType(0);
29662 // Shift left by 16 bits, then arithmetic-shift right by 16 bits.
29663 SDValue ShAmt = DAG.getConstant(16, DL, MVT::i32);
29664 for (auto &Reg : Regs) {
29665 Reg = getTargetVShiftNode(X86ISD::VSHLI, DL, MVT::v4i32, Reg, ShAmt, DAG);
29666 Reg = getTargetVShiftNode(X86ISD::VSRAI, DL, MVT::v4i32, Reg, ShAmt, DAG);
29669 for (unsigned i = 0, e = Regs.size() / 2; i < e; i++)
29670 Regs[i] = DAG.getNode(X86ISD::PACKSS, DL, MVT::v8i16, Regs[i * 2],
29673 if (Regs.size() > 2) {
29674 Regs.resize(Regs.size() / 2);
29675 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
29680 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
29681 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
29682 /// legalization the truncation will be translated into a BUILD_VECTOR with each
29683 /// element that is extracted from a vector and then truncated, and it is
29684 /// diffcult to do this optimization based on them.
29685 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
29686 const X86Subtarget &Subtarget) {
29687 EVT OutVT = N->getValueType(0);
29688 if (!OutVT.isVector())
29691 SDValue In = N->getOperand(0);
29692 if (!In.getValueType().isSimple())
29695 EVT InVT = In.getValueType();
29696 unsigned NumElems = OutVT.getVectorNumElements();
29698 // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
29699 // SSE2, and we need to take care of it specially.
29700 // AVX512 provides vpmovdb.
29701 if (!Subtarget.hasSSE2() || Subtarget.hasAVX2())
29704 EVT OutSVT = OutVT.getVectorElementType();
29705 EVT InSVT = InVT.getVectorElementType();
29706 if (!((InSVT == MVT::i32 || InSVT == MVT::i64) &&
29707 (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
29711 // SSSE3's pshufb results in less instructions in the cases below.
29712 if (Subtarget.hasSSSE3() && NumElems == 8 &&
29713 ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
29714 (InSVT == MVT::i32 && OutSVT == MVT::i16)))
29719 // Split a long vector into vectors of legal type.
29720 unsigned RegNum = InVT.getSizeInBits() / 128;
29721 SmallVector<SDValue, 8> SubVec(RegNum);
29722 unsigned NumSubRegElts = 128 / InSVT.getSizeInBits();
29723 EVT SubRegVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubRegElts);
29725 for (unsigned i = 0; i < RegNum; i++)
29726 SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubRegVT, In,
29727 DAG.getIntPtrConstant(i * NumSubRegElts, DL));
29729 // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PACKUS
29730 // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
29731 // truncate 2 x v4i32 to v8i16.
29732 if (Subtarget.hasSSE41() || OutSVT == MVT::i8)
29733 return combineVectorTruncationWithPACKUS(N, DAG, SubVec);
29734 else if (InSVT == MVT::i32)
29735 return combineVectorTruncationWithPACKSS(N, DAG, SubVec);
29740 static SDValue combineTruncate(SDNode *N, SelectionDAG &DAG,
29741 const X86Subtarget &Subtarget) {
29742 EVT VT = N->getValueType(0);
29743 SDValue Src = N->getOperand(0);
29746 // Try to detect AVG pattern first.
29747 if (SDValue Avg = detectAVGPattern(Src, VT, DAG, Subtarget, DL))
29750 // The bitcast source is a direct mmx result.
29751 // Detect bitcasts between i32 to x86mmx
29752 if (Src.getOpcode() == ISD::BITCAST && VT == MVT::i32) {
29753 SDValue BCSrc = Src.getOperand(0);
29754 if (BCSrc.getValueType() == MVT::x86mmx)
29755 return DAG.getNode(X86ISD::MMX_MOVD2W, DL, MVT::i32, BCSrc);
29758 return combineVectorTruncation(N, DAG, Subtarget);
29761 /// Do target-specific dag combines on floating point negations.
29762 static SDValue combineFneg(SDNode *N, SelectionDAG &DAG,
29763 const X86Subtarget &Subtarget) {
29764 EVT VT = N->getValueType(0);
29765 EVT SVT = VT.getScalarType();
29766 SDValue Arg = N->getOperand(0);
29769 // Let legalize expand this if it isn't a legal type yet.
29770 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
29773 // If we're negating a FMUL node on a target with FMA, then we can avoid the
29774 // use of a constant by performing (-0 - A*B) instead.
29775 // FIXME: Check rounding control flags as well once it becomes available.
29776 if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
29777 Arg->getFlags()->hasNoSignedZeros() && Subtarget.hasAnyFMA()) {
29778 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
29779 return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
29780 Arg.getOperand(1), Zero);
29783 // If we're negating a FMA node, then we can adjust the
29784 // instruction to include the extra negation.
29785 if (Arg.hasOneUse()) {
29786 switch (Arg.getOpcode()) {
29787 case X86ISD::FMADD:
29788 return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
29789 Arg.getOperand(1), Arg.getOperand(2));
29790 case X86ISD::FMSUB:
29791 return DAG.getNode(X86ISD::FNMADD, DL, VT, Arg.getOperand(0),
29792 Arg.getOperand(1), Arg.getOperand(2));
29793 case X86ISD::FNMADD:
29794 return DAG.getNode(X86ISD::FMSUB, DL, VT, Arg.getOperand(0),
29795 Arg.getOperand(1), Arg.getOperand(2));
29796 case X86ISD::FNMSUB:
29797 return DAG.getNode(X86ISD::FMADD, DL, VT, Arg.getOperand(0),
29798 Arg.getOperand(1), Arg.getOperand(2));
29804 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
29805 const X86Subtarget &Subtarget) {
29806 EVT VT = N->getValueType(0);
29807 if (VT.is512BitVector() && !Subtarget.hasDQI()) {
29808 // VXORPS, VORPS, VANDPS, VANDNPS are supported only under DQ extention.
29809 // These logic operations may be executed in the integer domain.
29811 MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
29812 MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
29814 SDValue Op0 = DAG.getBitcast(IntVT, N->getOperand(0));
29815 SDValue Op1 = DAG.getBitcast(IntVT, N->getOperand(1));
29816 unsigned IntOpcode = 0;
29817 switch (N->getOpcode()) {
29818 default: llvm_unreachable("Unexpected FP logic op");
29819 case X86ISD::FOR: IntOpcode = ISD::OR; break;
29820 case X86ISD::FXOR: IntOpcode = ISD::XOR; break;
29821 case X86ISD::FAND: IntOpcode = ISD::AND; break;
29822 case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
29824 SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
29825 return DAG.getBitcast(VT, IntOp);
29829 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
29830 static SDValue combineFOr(SDNode *N, SelectionDAG &DAG,
29831 const X86Subtarget &Subtarget) {
29832 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
29834 // F[X]OR(0.0, x) -> x
29835 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
29836 if (C->getValueAPF().isPosZero())
29837 return N->getOperand(1);
29839 // F[X]OR(x, 0.0) -> x
29840 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
29841 if (C->getValueAPF().isPosZero())
29842 return N->getOperand(0);
29844 return lowerX86FPLogicOp(N, DAG, Subtarget);
29847 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
29848 static SDValue combineFMinFMax(SDNode *N, SelectionDAG &DAG) {
29849 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
29851 // Only perform optimizations if UnsafeMath is used.
29852 if (!DAG.getTarget().Options.UnsafeFPMath)
29855 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
29856 // into FMINC and FMAXC, which are Commutative operations.
29857 unsigned NewOp = 0;
29858 switch (N->getOpcode()) {
29859 default: llvm_unreachable("unknown opcode");
29860 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
29861 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
29864 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
29865 N->getOperand(0), N->getOperand(1));
29868 static SDValue combineFMinNumFMaxNum(SDNode *N, SelectionDAG &DAG,
29869 const X86Subtarget &Subtarget) {
29870 if (Subtarget.useSoftFloat())
29873 // TODO: Check for global or instruction-level "nnan". In that case, we
29874 // should be able to lower to FMAX/FMIN alone.
29875 // TODO: If an operand is already known to be a NaN or not a NaN, this
29876 // should be an optional swap and FMAX/FMIN.
29878 EVT VT = N->getValueType(0);
29879 if (!((Subtarget.hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
29880 (Subtarget.hasSSE2() && (VT == MVT::f64 || VT == MVT::v2f64)) ||
29881 (Subtarget.hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))))
29884 // This takes at least 3 instructions, so favor a library call when operating
29885 // on a scalar and minimizing code size.
29886 if (!VT.isVector() && DAG.getMachineFunction().getFunction()->optForMinSize())
29889 SDValue Op0 = N->getOperand(0);
29890 SDValue Op1 = N->getOperand(1);
29892 EVT SetCCType = DAG.getTargetLoweringInfo().getSetCCResultType(
29893 DAG.getDataLayout(), *DAG.getContext(), VT);
29895 // There are 4 possibilities involving NaN inputs, and these are the required
29899 // ----------------
29900 // Num | Max | Op0 |
29901 // Op0 ----------------
29902 // NaN | Op1 | NaN |
29903 // ----------------
29905 // The SSE FP max/min instructions were not designed for this case, but rather
29907 // Min = Op1 < Op0 ? Op1 : Op0
29908 // Max = Op1 > Op0 ? Op1 : Op0
29910 // So they always return Op0 if either input is a NaN. However, we can still
29911 // use those instructions for fmaxnum by selecting away a NaN input.
29913 // If either operand is NaN, the 2nd source operand (Op0) is passed through.
29914 auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
29915 SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
29916 SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType , Op0, Op0, ISD::SETUO);
29918 // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
29919 // are NaN, the NaN value of Op1 is the result.
29920 auto SelectOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
29921 return DAG.getNode(SelectOpcode, DL, VT, IsOp0Nan, Op1, MinOrMax);
29924 /// Do target-specific dag combines on X86ISD::FAND nodes.
29925 static SDValue combineFAnd(SDNode *N, SelectionDAG &DAG,
29926 const X86Subtarget &Subtarget) {
29927 // FAND(0.0, x) -> 0.0
29928 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
29929 if (C->getValueAPF().isPosZero())
29930 return N->getOperand(0);
29932 // FAND(x, 0.0) -> 0.0
29933 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
29934 if (C->getValueAPF().isPosZero())
29935 return N->getOperand(1);
29937 return lowerX86FPLogicOp(N, DAG, Subtarget);
29940 /// Do target-specific dag combines on X86ISD::FANDN nodes
29941 static SDValue combineFAndn(SDNode *N, SelectionDAG &DAG,
29942 const X86Subtarget &Subtarget) {
29943 // FANDN(0.0, x) -> x
29944 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
29945 if (C->getValueAPF().isPosZero())
29946 return N->getOperand(1);
29948 // FANDN(x, 0.0) -> 0.0
29949 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
29950 if (C->getValueAPF().isPosZero())
29951 return N->getOperand(1);
29953 return lowerX86FPLogicOp(N, DAG, Subtarget);
29956 static SDValue combineBT(SDNode *N, SelectionDAG &DAG,
29957 TargetLowering::DAGCombinerInfo &DCI) {
29958 // BT ignores high bits in the bit index operand.
29959 SDValue Op1 = N->getOperand(1);
29960 if (Op1.hasOneUse()) {
29961 unsigned BitWidth = Op1.getValueSizeInBits();
29962 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
29963 APInt KnownZero, KnownOne;
29964 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
29965 !DCI.isBeforeLegalizeOps());
29966 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
29967 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
29968 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
29969 DCI.CommitTargetLoweringOpt(TLO);
29974 static SDValue combineVZextMovl(SDNode *N, SelectionDAG &DAG) {
29975 SDValue Op = peekThroughBitcasts(N->getOperand(0));
29976 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
29977 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
29978 VT.getVectorElementType().getSizeInBits() ==
29979 OpVT.getVectorElementType().getSizeInBits()) {
29980 return DAG.getBitcast(VT, Op);
29985 static SDValue combineSignExtendInReg(SDNode *N, SelectionDAG &DAG,
29986 const X86Subtarget &Subtarget) {
29987 EVT VT = N->getValueType(0);
29988 if (!VT.isVector())
29991 SDValue N0 = N->getOperand(0);
29992 SDValue N1 = N->getOperand(1);
29993 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
29996 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
29997 // both SSE and AVX2 since there is no sign-extended shift right
29998 // operation on a vector with 64-bit elements.
29999 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
30000 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
30001 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
30002 N0.getOpcode() == ISD::SIGN_EXTEND)) {
30003 SDValue N00 = N0.getOperand(0);
30005 // EXTLOAD has a better solution on AVX2,
30006 // it may be replaced with X86ISD::VSEXT node.
30007 if (N00.getOpcode() == ISD::LOAD && Subtarget.hasInt256())
30008 if (!ISD::isNormalLoad(N00.getNode()))
30011 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
30012 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
30014 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
30020 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
30021 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
30022 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
30023 /// eliminate extend, add, and shift instructions.
30024 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
30025 const X86Subtarget &Subtarget) {
30026 // TODO: This should be valid for other integer types.
30027 EVT VT = Sext->getValueType(0);
30028 if (VT != MVT::i64)
30031 // We need an 'add nsw' feeding into the 'sext'.
30032 SDValue Add = Sext->getOperand(0);
30033 if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
30036 // Having a constant operand to the 'add' ensures that we are not increasing
30037 // the instruction count because the constant is extended for free below.
30038 // A constant operand can also become the displacement field of an LEA.
30039 auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
30043 // Don't make the 'add' bigger if there's no hope of combining it with some
30044 // other 'add' or 'shl' instruction.
30045 // TODO: It may be profitable to generate simpler LEA instructions in place
30046 // of single 'add' instructions, but the cost model for selecting an LEA
30047 // currently has a high threshold.
30048 bool HasLEAPotential = false;
30049 for (auto *User : Sext->uses()) {
30050 if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
30051 HasLEAPotential = true;
30055 if (!HasLEAPotential)
30058 // Everything looks good, so pull the 'sext' ahead of the 'add'.
30059 int64_t AddConstant = AddOp1->getSExtValue();
30060 SDValue AddOp0 = Add.getOperand(0);
30061 SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
30062 SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
30064 // The wider add is guaranteed to not wrap because both operands are
30067 Flags.setNoSignedWrap(true);
30068 return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
30071 /// (i8,i32 {s/z}ext ({s/u}divrem (i8 x, i8 y)) ->
30072 /// (i8,i32 ({s/u}divrem_sext_hreg (i8 x, i8 y)
30073 /// This exposes the {s/z}ext to the sdivrem lowering, so that it directly
30074 /// extends from AH (which we otherwise need to do contortions to access).
30075 static SDValue getDivRem8(SDNode *N, SelectionDAG &DAG) {
30076 SDValue N0 = N->getOperand(0);
30077 auto OpcodeN = N->getOpcode();
30078 auto OpcodeN0 = N0.getOpcode();
30079 if (!((OpcodeN == ISD::SIGN_EXTEND && OpcodeN0 == ISD::SDIVREM) ||
30080 (OpcodeN == ISD::ZERO_EXTEND && OpcodeN0 == ISD::UDIVREM)))
30083 EVT VT = N->getValueType(0);
30084 EVT InVT = N0.getValueType();
30085 if (N0.getResNo() != 1 || InVT != MVT::i8 || VT != MVT::i32)
30088 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
30089 auto DivRemOpcode = OpcodeN0 == ISD::SDIVREM ? X86ISD::SDIVREM8_SEXT_HREG
30090 : X86ISD::UDIVREM8_ZEXT_HREG;
30091 SDValue R = DAG.getNode(DivRemOpcode, SDLoc(N), NodeTys, N0.getOperand(0),
30093 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
30094 return R.getValue(1);
30097 /// Convert a SEXT or ZEXT of a vector to a SIGN_EXTEND_VECTOR_INREG or
30098 /// ZERO_EXTEND_VECTOR_INREG, this requires the splitting (or concatenating
30099 /// with UNDEFs) of the input to vectors of the same size as the target type
30100 /// which then extends the lowest elements.
30101 static SDValue combineToExtendVectorInReg(SDNode *N, SelectionDAG &DAG,
30102 TargetLowering::DAGCombinerInfo &DCI,
30103 const X86Subtarget &Subtarget) {
30104 unsigned Opcode = N->getOpcode();
30105 if (Opcode != ISD::SIGN_EXTEND && Opcode != ISD::ZERO_EXTEND)
30107 if (!DCI.isBeforeLegalizeOps())
30109 if (!Subtarget.hasSSE2())
30112 SDValue N0 = N->getOperand(0);
30113 EVT VT = N->getValueType(0);
30114 EVT SVT = VT.getScalarType();
30115 EVT InVT = N0.getValueType();
30116 EVT InSVT = InVT.getScalarType();
30118 // Input type must be a vector and we must be extending legal integer types.
30119 if (!VT.isVector())
30121 if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16)
30123 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
30126 // On AVX2+ targets, if the input/output types are both legal then we will be
30127 // able to use SIGN_EXTEND/ZERO_EXTEND directly.
30128 if (Subtarget.hasInt256() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
30129 DAG.getTargetLoweringInfo().isTypeLegal(InVT))
30134 auto ExtendVecSize = [&DAG](const SDLoc &DL, SDValue N, unsigned Size) {
30135 EVT InVT = N.getValueType();
30136 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
30137 Size / InVT.getScalarSizeInBits());
30138 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
30139 DAG.getUNDEF(InVT));
30141 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
30144 // If target-size is less than 128-bits, extend to a type that would extend
30145 // to 128 bits, extend that and extract the original target vector.
30146 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits())) {
30147 unsigned Scale = 128 / VT.getSizeInBits();
30149 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
30150 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
30151 SDValue SExt = DAG.getNode(Opcode, DL, ExVT, Ex);
30152 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
30153 DAG.getIntPtrConstant(0, DL));
30156 // If target-size is 128-bits (or 256-bits on AVX2 target), then convert to
30157 // ISD::*_EXTEND_VECTOR_INREG which ensures lowering to X86ISD::V*EXT.
30158 // Also use this if we don't have SSE41 to allow the legalizer do its job.
30159 if (!Subtarget.hasSSE41() || VT.is128BitVector() ||
30160 (VT.is256BitVector() && Subtarget.hasInt256())) {
30161 SDValue ExOp = ExtendVecSize(DL, N0, VT.getSizeInBits());
30162 return Opcode == ISD::SIGN_EXTEND
30163 ? DAG.getSignExtendVectorInReg(ExOp, DL, VT)
30164 : DAG.getZeroExtendVectorInReg(ExOp, DL, VT);
30167 // On pre-AVX2 targets, split into 128-bit nodes of
30168 // ISD::*_EXTEND_VECTOR_INREG.
30169 if (!Subtarget.hasInt256() && !(VT.getSizeInBits() % 128)) {
30170 unsigned NumVecs = VT.getSizeInBits() / 128;
30171 unsigned NumSubElts = 128 / SVT.getSizeInBits();
30172 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
30173 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
30175 SmallVector<SDValue, 8> Opnds;
30176 for (unsigned i = 0, Offset = 0; i != NumVecs; ++i, Offset += NumSubElts) {
30177 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
30178 DAG.getIntPtrConstant(Offset, DL));
30179 SrcVec = ExtendVecSize(DL, SrcVec, 128);
30180 SrcVec = Opcode == ISD::SIGN_EXTEND
30181 ? DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT)
30182 : DAG.getZeroExtendVectorInReg(SrcVec, DL, SubVT);
30183 Opnds.push_back(SrcVec);
30185 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
30191 static SDValue combineSext(SDNode *N, SelectionDAG &DAG,
30192 TargetLowering::DAGCombinerInfo &DCI,
30193 const X86Subtarget &Subtarget) {
30194 SDValue N0 = N->getOperand(0);
30195 EVT VT = N->getValueType(0);
30196 EVT InVT = N0.getValueType();
30199 if (SDValue DivRem8 = getDivRem8(N, DAG))
30202 if (!DCI.isBeforeLegalizeOps()) {
30203 if (InVT == MVT::i1) {
30204 SDValue Zero = DAG.getConstant(0, DL, VT);
30206 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
30207 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
30212 if (SDValue V = combineToExtendVectorInReg(N, DAG, DCI, Subtarget))
30215 if (Subtarget.hasAVX() && VT.is256BitVector())
30216 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
30219 if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
30225 static SDValue combineFMA(SDNode *N, SelectionDAG &DAG,
30226 const X86Subtarget &Subtarget) {
30228 EVT VT = N->getValueType(0);
30230 // Let legalize expand this if it isn't a legal type yet.
30231 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
30234 EVT ScalarVT = VT.getScalarType();
30235 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget.hasAnyFMA())
30238 SDValue A = N->getOperand(0);
30239 SDValue B = N->getOperand(1);
30240 SDValue C = N->getOperand(2);
30242 bool NegA = (A.getOpcode() == ISD::FNEG);
30243 bool NegB = (B.getOpcode() == ISD::FNEG);
30244 bool NegC = (C.getOpcode() == ISD::FNEG);
30246 // Negative multiplication when NegA xor NegB
30247 bool NegMul = (NegA != NegB);
30249 A = A.getOperand(0);
30251 B = B.getOperand(0);
30253 C = C.getOperand(0);
30257 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
30259 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
30261 return DAG.getNode(Opcode, dl, VT, A, B, C);
30264 static SDValue combineZext(SDNode *N, SelectionDAG &DAG,
30265 TargetLowering::DAGCombinerInfo &DCI,
30266 const X86Subtarget &Subtarget) {
30267 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
30268 // (and (i32 x86isd::setcc_carry), 1)
30269 // This eliminates the zext. This transformation is necessary because
30270 // ISD::SETCC is always legalized to i8.
30272 SDValue N0 = N->getOperand(0);
30273 EVT VT = N->getValueType(0);
30275 if (N0.getOpcode() == ISD::AND &&
30277 N0.getOperand(0).hasOneUse()) {
30278 SDValue N00 = N0.getOperand(0);
30279 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
30280 if (!isOneConstant(N0.getOperand(1)))
30282 return DAG.getNode(ISD::AND, dl, VT,
30283 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
30284 N00.getOperand(0), N00.getOperand(1)),
30285 DAG.getConstant(1, dl, VT));
30289 if (N0.getOpcode() == ISD::TRUNCATE &&
30291 N0.getOperand(0).hasOneUse()) {
30292 SDValue N00 = N0.getOperand(0);
30293 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
30294 return DAG.getNode(ISD::AND, dl, VT,
30295 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
30296 N00.getOperand(0), N00.getOperand(1)),
30297 DAG.getConstant(1, dl, VT));
30301 if (SDValue V = combineToExtendVectorInReg(N, DAG, DCI, Subtarget))
30304 if (VT.is256BitVector())
30305 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
30308 if (SDValue DivRem8 = getDivRem8(N, DAG))
30314 /// Optimize x == -y --> x+y == 0
30315 /// x != -y --> x+y != 0
30316 static SDValue combineSetCC(SDNode *N, SelectionDAG &DAG,
30317 const X86Subtarget &Subtarget) {
30318 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
30319 SDValue LHS = N->getOperand(0);
30320 SDValue RHS = N->getOperand(1);
30321 EVT VT = N->getValueType(0);
30324 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
30325 if (isNullConstant(LHS.getOperand(0)) && LHS.hasOneUse()) {
30326 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
30327 LHS.getOperand(1));
30328 return DAG.getSetCC(DL, N->getValueType(0), addV,
30329 DAG.getConstant(0, DL, addV.getValueType()), CC);
30331 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
30332 if (isNullConstant(RHS.getOperand(0)) && RHS.hasOneUse()) {
30333 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
30334 RHS.getOperand(1));
30335 return DAG.getSetCC(DL, N->getValueType(0), addV,
30336 DAG.getConstant(0, DL, addV.getValueType()), CC);
30339 if (VT.getScalarType() == MVT::i1 &&
30340 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
30342 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
30343 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
30344 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
30346 if (!IsSEXT0 || !IsVZero1) {
30347 // Swap the operands and update the condition code.
30348 std::swap(LHS, RHS);
30349 CC = ISD::getSetCCSwappedOperands(CC);
30351 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
30352 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
30353 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
30356 if (IsSEXT0 && IsVZero1) {
30357 assert(VT == LHS.getOperand(0).getValueType() &&
30358 "Uexpected operand type");
30359 if (CC == ISD::SETGT)
30360 return DAG.getConstant(0, DL, VT);
30361 if (CC == ISD::SETLE)
30362 return DAG.getConstant(1, DL, VT);
30363 if (CC == ISD::SETEQ || CC == ISD::SETGE)
30364 return DAG.getNOT(DL, LHS.getOperand(0), VT);
30366 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
30367 "Unexpected condition code!");
30368 return LHS.getOperand(0);
30372 // For an SSE1-only target, lower a comparison of v4f32 to X86ISD::CMPP early
30373 // to avoid scalarization via legalization because v4i32 is not a legal type.
30374 if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32 &&
30375 LHS.getValueType() == MVT::v4f32)
30376 return LowerVSETCC(SDValue(N, 0), Subtarget, DAG);
30381 static SDValue combineGatherScatter(SDNode *N, SelectionDAG &DAG) {
30383 // Gather and Scatter instructions use k-registers for masks. The type of
30384 // the masks is v*i1. So the mask will be truncated anyway.
30385 // The SIGN_EXTEND_INREG my be dropped.
30386 SDValue Mask = N->getOperand(2);
30387 if (Mask.getOpcode() == ISD::SIGN_EXTEND_INREG) {
30388 SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
30389 NewOps[2] = Mask.getOperand(0);
30390 DAG.UpdateNodeOperands(N, NewOps);
30395 // Helper function of performSETCCCombine. It is to materialize "setb reg"
30396 // as "sbb reg,reg", since it can be extended without zext and produces
30397 // an all-ones bit which is more useful than 0/1 in some cases.
30398 static SDValue MaterializeSETB(const SDLoc &DL, SDValue EFLAGS,
30399 SelectionDAG &DAG, MVT VT) {
30401 return DAG.getNode(ISD::AND, DL, VT,
30402 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
30403 DAG.getConstant(X86::COND_B, DL, MVT::i8),
30405 DAG.getConstant(1, DL, VT));
30406 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
30407 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
30408 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
30409 DAG.getConstant(X86::COND_B, DL, MVT::i8),
30413 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
30414 static SDValue combineX86SetCC(SDNode *N, SelectionDAG &DAG,
30415 TargetLowering::DAGCombinerInfo &DCI,
30416 const X86Subtarget &Subtarget) {
30418 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
30419 SDValue EFLAGS = N->getOperand(1);
30421 if (CC == X86::COND_A) {
30422 // Try to convert COND_A into COND_B in an attempt to facilitate
30423 // materializing "setb reg".
30425 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
30426 // cannot take an immediate as its first operand.
30428 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
30429 EFLAGS.getValueType().isInteger() &&
30430 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
30431 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
30432 EFLAGS.getNode()->getVTList(),
30433 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
30434 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
30435 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
30439 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
30440 // a zext and produces an all-ones bit which is more useful than 0/1 in some
30442 if (CC == X86::COND_B)
30443 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
30445 // Try to simplify the EFLAGS and condition code operands.
30446 if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG)) {
30447 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
30448 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
30454 /// Optimize branch condition evaluation.
30455 static SDValue combineBrCond(SDNode *N, SelectionDAG &DAG,
30456 TargetLowering::DAGCombinerInfo &DCI,
30457 const X86Subtarget &Subtarget) {
30459 SDValue EFLAGS = N->getOperand(3);
30460 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
30462 // Try to simplify the EFLAGS and condition code operands.
30463 // Make sure to not keep references to operands, as combineSetCCEFLAGS can
30464 // RAUW them under us.
30465 if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG)) {
30466 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
30467 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), N->getOperand(0),
30468 N->getOperand(1), Cond, Flags);
30474 static SDValue combineVectorCompareAndMaskUnaryOp(SDNode *N,
30475 SelectionDAG &DAG) {
30476 // Take advantage of vector comparisons producing 0 or -1 in each lane to
30477 // optimize away operation when it's from a constant.
30479 // The general transformation is:
30480 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
30481 // AND(VECTOR_CMP(x,y), constant2)
30482 // constant2 = UNARYOP(constant)
30484 // Early exit if this isn't a vector operation, the operand of the
30485 // unary operation isn't a bitwise AND, or if the sizes of the operations
30486 // aren't the same.
30487 EVT VT = N->getValueType(0);
30488 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
30489 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
30490 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
30493 // Now check that the other operand of the AND is a constant. We could
30494 // make the transformation for non-constant splats as well, but it's unclear
30495 // that would be a benefit as it would not eliminate any operations, just
30496 // perform one more step in scalar code before moving to the vector unit.
30497 if (BuildVectorSDNode *BV =
30498 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
30499 // Bail out if the vector isn't a constant.
30500 if (!BV->isConstant())
30503 // Everything checks out. Build up the new and improved node.
30505 EVT IntVT = BV->getValueType(0);
30506 // Create a new constant of the appropriate type for the transformed
30508 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
30509 // The AND node needs bitcasts to/from an integer vector type around it.
30510 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
30511 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
30512 N->getOperand(0)->getOperand(0), MaskConst);
30513 SDValue Res = DAG.getBitcast(VT, NewAnd);
30520 static SDValue combineUIntToFP(SDNode *N, SelectionDAG &DAG,
30521 const X86Subtarget &Subtarget) {
30522 SDValue Op0 = N->getOperand(0);
30523 EVT VT = N->getValueType(0);
30524 EVT InVT = Op0.getValueType();
30525 EVT InSVT = InVT.getScalarType();
30526 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
30528 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
30529 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
30530 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
30532 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
30533 InVT.getVectorNumElements());
30534 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
30536 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
30537 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
30539 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
30545 static SDValue combineSIntToFP(SDNode *N, SelectionDAG &DAG,
30546 const X86Subtarget &Subtarget) {
30547 // First try to optimize away the conversion entirely when it's
30548 // conditionally from a constant. Vectors only.
30549 if (SDValue Res = combineVectorCompareAndMaskUnaryOp(N, DAG))
30552 // Now move on to more general possibilities.
30553 SDValue Op0 = N->getOperand(0);
30554 EVT VT = N->getValueType(0);
30555 EVT InVT = Op0.getValueType();
30556 EVT InSVT = InVT.getScalarType();
30558 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
30559 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
30560 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
30562 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
30563 InVT.getVectorNumElements());
30564 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
30565 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
30568 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
30569 // a 32-bit target where SSE doesn't support i64->FP operations.
30570 if (!Subtarget.useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
30571 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
30572 EVT LdVT = Ld->getValueType(0);
30574 // This transformation is not supported if the result type is f16 or f128.
30575 if (VT == MVT::f16 || VT == MVT::f128)
30578 if (!Ld->isVolatile() && !VT.isVector() &&
30579 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
30580 !Subtarget.is64Bit() && LdVT == MVT::i64) {
30581 SDValue FILDChain = Subtarget.getTargetLowering()->BuildFILD(
30582 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
30583 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
30590 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
30591 static SDValue combineADC(SDNode *N, SelectionDAG &DAG,
30592 X86TargetLowering::DAGCombinerInfo &DCI) {
30593 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
30594 // the result is either zero or one (depending on the input carry bit).
30595 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
30596 if (X86::isZeroNode(N->getOperand(0)) &&
30597 X86::isZeroNode(N->getOperand(1)) &&
30598 // We don't have a good way to replace an EFLAGS use, so only do this when
30600 SDValue(N, 1).use_empty()) {
30602 EVT VT = N->getValueType(0);
30603 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
30604 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
30605 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
30606 DAG.getConstant(X86::COND_B, DL,
30609 DAG.getConstant(1, DL, VT));
30610 return DCI.CombineTo(N, Res1, CarryOut);
30616 /// fold (add Y, (sete X, 0)) -> adc 0, Y
30617 /// (add Y, (setne X, 0)) -> sbb -1, Y
30618 /// (sub (sete X, 0), Y) -> sbb 0, Y
30619 /// (sub (setne X, 0), Y) -> adc -1, Y
30620 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
30623 // Look through ZExts.
30624 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
30625 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
30628 SDValue SetCC = Ext.getOperand(0);
30629 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
30632 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
30633 if (CC != X86::COND_E && CC != X86::COND_NE)
30636 SDValue Cmp = SetCC.getOperand(1);
30637 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
30638 !X86::isZeroNode(Cmp.getOperand(1)) ||
30639 !Cmp.getOperand(0).getValueType().isInteger())
30642 SDValue CmpOp0 = Cmp.getOperand(0);
30643 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
30644 DAG.getConstant(1, DL, CmpOp0.getValueType()));
30646 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
30647 if (CC == X86::COND_NE)
30648 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
30649 DL, OtherVal.getValueType(), OtherVal,
30650 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
30652 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
30653 DL, OtherVal.getValueType(), OtherVal,
30654 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
30657 static SDValue detectSADPattern(SDNode *N, SelectionDAG &DAG,
30658 const X86Subtarget &Subtarget) {
30660 EVT VT = N->getValueType(0);
30661 SDValue Op0 = N->getOperand(0);
30662 SDValue Op1 = N->getOperand(1);
30664 if (!VT.isVector() || !VT.isSimple() ||
30665 !(VT.getVectorElementType() == MVT::i32))
30668 unsigned RegSize = 128;
30669 if (Subtarget.hasBWI())
30671 else if (Subtarget.hasAVX2())
30674 // We only handle v16i32 for SSE2 / v32i32 for AVX2 / v64i32 for AVX512.
30675 if (VT.getSizeInBits() / 4 > RegSize)
30678 // Detect the following pattern:
30680 // 1: %2 = zext <N x i8> %0 to <N x i32>
30681 // 2: %3 = zext <N x i8> %1 to <N x i32>
30682 // 3: %4 = sub nsw <N x i32> %2, %3
30683 // 4: %5 = icmp sgt <N x i32> %4, [0 x N] or [-1 x N]
30684 // 5: %6 = sub nsw <N x i32> zeroinitializer, %4
30685 // 6: %7 = select <N x i1> %5, <N x i32> %4, <N x i32> %6
30686 // 7: %8 = add nsw <N x i32> %7, %vec.phi
30688 // The last instruction must be a reduction add. The instructions 3-6 forms an
30689 // ABSDIFF pattern.
30691 // The two operands of reduction add are from PHI and a select-op as in line 7
30693 SDValue SelectOp, Phi;
30694 if (Op0.getOpcode() == ISD::VSELECT) {
30697 } else if (Op1.getOpcode() == ISD::VSELECT) {
30703 // Check the condition of the select instruction is greater-than.
30704 SDValue SetCC = SelectOp->getOperand(0);
30705 if (SetCC.getOpcode() != ISD::SETCC)
30707 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
30708 if (CC != ISD::SETGT)
30711 Op0 = SelectOp->getOperand(1);
30712 Op1 = SelectOp->getOperand(2);
30714 // The second operand of SelectOp Op1 is the negation of the first operand
30715 // Op0, which is implemented as 0 - Op0.
30716 if (!(Op1.getOpcode() == ISD::SUB &&
30717 ISD::isBuildVectorAllZeros(Op1.getOperand(0).getNode()) &&
30718 Op1.getOperand(1) == Op0))
30721 // The first operand of SetCC is the first operand of SelectOp, which is the
30722 // difference between two input vectors.
30723 if (SetCC.getOperand(0) != Op0)
30726 // The second operand of > comparison can be either -1 or 0.
30727 if (!(ISD::isBuildVectorAllZeros(SetCC.getOperand(1).getNode()) ||
30728 ISD::isBuildVectorAllOnes(SetCC.getOperand(1).getNode())))
30731 // The first operand of SelectOp is the difference between two input vectors.
30732 if (Op0.getOpcode() != ISD::SUB)
30735 Op1 = Op0.getOperand(1);
30736 Op0 = Op0.getOperand(0);
30738 // Check if the operands of the diff are zero-extended from vectors of i8.
30739 if (Op0.getOpcode() != ISD::ZERO_EXTEND ||
30740 Op0.getOperand(0).getValueType().getVectorElementType() != MVT::i8 ||
30741 Op1.getOpcode() != ISD::ZERO_EXTEND ||
30742 Op1.getOperand(0).getValueType().getVectorElementType() != MVT::i8)
30745 // SAD pattern detected. Now build a SAD instruction and an addition for
30746 // reduction. Note that the number of elments of the result of SAD is less
30747 // than the number of elements of its input. Therefore, we could only update
30748 // part of elements in the reduction vector.
30750 // Legalize the type of the inputs of PSADBW.
30751 EVT InVT = Op0.getOperand(0).getValueType();
30752 if (InVT.getSizeInBits() <= 128)
30754 else if (InVT.getSizeInBits() <= 256)
30757 unsigned NumConcat = RegSize / InVT.getSizeInBits();
30758 SmallVector<SDValue, 16> Ops(NumConcat, DAG.getConstant(0, DL, InVT));
30759 Ops[0] = Op0.getOperand(0);
30760 MVT ExtendedVT = MVT::getVectorVT(MVT::i8, RegSize / 8);
30761 Op0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
30762 Ops[0] = Op1.getOperand(0);
30763 Op1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
30765 // The output of PSADBW is a vector of i64.
30766 MVT SadVT = MVT::getVectorVT(MVT::i64, RegSize / 64);
30767 SDValue Sad = DAG.getNode(X86ISD::PSADBW, DL, SadVT, Op0, Op1);
30769 // We need to turn the vector of i64 into a vector of i32.
30770 // If the reduction vector is at least as wide as the psadbw result, just
30771 // bitcast. If it's narrower, truncate - the high i32 of each i64 is zero
30773 MVT ResVT = MVT::getVectorVT(MVT::i32, RegSize / 32);
30774 if (VT.getSizeInBits() >= ResVT.getSizeInBits())
30775 Sad = DAG.getNode(ISD::BITCAST, DL, ResVT, Sad);
30777 Sad = DAG.getNode(ISD::TRUNCATE, DL, VT, Sad);
30779 if (VT.getSizeInBits() > ResVT.getSizeInBits()) {
30780 // Update part of elements of the reduction vector. This is done by first
30781 // extracting a sub-vector from it, updating this sub-vector, and inserting
30783 SDValue SubPhi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResVT, Phi,
30784 DAG.getIntPtrConstant(0, DL));
30785 SDValue Res = DAG.getNode(ISD::ADD, DL, ResVT, Sad, SubPhi);
30786 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Phi, Res,
30787 DAG.getIntPtrConstant(0, DL));
30789 return DAG.getNode(ISD::ADD, DL, VT, Sad, Phi);
30792 static SDValue combineAdd(SDNode *N, SelectionDAG &DAG,
30793 const X86Subtarget &Subtarget) {
30794 const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
30795 if (Flags->hasVectorReduction()) {
30796 if (SDValue Sad = detectSADPattern(N, DAG, Subtarget))
30799 EVT VT = N->getValueType(0);
30800 SDValue Op0 = N->getOperand(0);
30801 SDValue Op1 = N->getOperand(1);
30803 // Try to synthesize horizontal adds from adds of shuffles.
30804 if (((Subtarget.hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
30805 (Subtarget.hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
30806 isHorizontalBinOp(Op0, Op1, true))
30807 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
30809 return OptimizeConditionalInDecrement(N, DAG);
30812 static SDValue combineSub(SDNode *N, SelectionDAG &DAG,
30813 const X86Subtarget &Subtarget) {
30814 SDValue Op0 = N->getOperand(0);
30815 SDValue Op1 = N->getOperand(1);
30817 // X86 can't encode an immediate LHS of a sub. See if we can push the
30818 // negation into a preceding instruction.
30819 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
30820 // If the RHS of the sub is a XOR with one use and a constant, invert the
30821 // immediate. Then add one to the LHS of the sub so we can turn
30822 // X-Y -> X+~Y+1, saving one register.
30823 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
30824 isa<ConstantSDNode>(Op1.getOperand(1))) {
30825 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
30826 EVT VT = Op0.getValueType();
30827 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
30829 DAG.getConstant(~XorC, SDLoc(Op1), VT));
30830 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
30831 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
30835 // Try to synthesize horizontal adds from adds of shuffles.
30836 EVT VT = N->getValueType(0);
30837 if (((Subtarget.hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
30838 (Subtarget.hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
30839 isHorizontalBinOp(Op0, Op1, true))
30840 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
30842 return OptimizeConditionalInDecrement(N, DAG);
30845 static SDValue combineVZext(SDNode *N, SelectionDAG &DAG,
30846 TargetLowering::DAGCombinerInfo &DCI,
30847 const X86Subtarget &Subtarget) {
30849 MVT VT = N->getSimpleValueType(0);
30850 MVT SVT = VT.getVectorElementType();
30851 SDValue Op = N->getOperand(0);
30852 MVT OpVT = Op.getSimpleValueType();
30853 MVT OpEltVT = OpVT.getVectorElementType();
30854 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
30856 // Perform any constant folding.
30857 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
30858 SmallVector<SDValue, 4> Vals;
30859 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
30860 SDValue OpElt = Op.getOperand(i);
30861 if (OpElt.getOpcode() == ISD::UNDEF) {
30862 Vals.push_back(DAG.getUNDEF(SVT));
30865 APInt Cst = cast<ConstantSDNode>(OpElt.getNode())->getAPIntValue();
30866 assert(Cst.getBitWidth() == OpEltVT.getSizeInBits());
30867 Cst = Cst.zextOrTrunc(SVT.getSizeInBits());
30868 Vals.push_back(DAG.getConstant(Cst, DL, SVT));
30870 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Vals);
30873 // (vzext (bitcast (vzext (x)) -> (vzext x)
30874 SDValue V = peekThroughBitcasts(Op);
30875 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
30876 MVT InnerVT = V.getSimpleValueType();
30877 MVT InnerEltVT = InnerVT.getVectorElementType();
30879 // If the element sizes match exactly, we can just do one larger vzext. This
30880 // is always an exact type match as vzext operates on integer types.
30881 if (OpEltVT == InnerEltVT) {
30882 assert(OpVT == InnerVT && "Types must match for vzext!");
30883 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
30886 // The only other way we can combine them is if only a single element of the
30887 // inner vzext is used in the input to the outer vzext.
30888 if (InnerEltVT.getSizeInBits() < InputBits)
30891 // In this case, the inner vzext is completely dead because we're going to
30892 // only look at bits inside of the low element. Just do the outer vzext on
30893 // a bitcast of the input to the inner.
30894 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
30897 // Check if we can bypass extracting and re-inserting an element of an input
30898 // vector. Essentially:
30899 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
30900 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
30901 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
30902 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
30903 SDValue ExtractedV = V.getOperand(0);
30904 SDValue OrigV = ExtractedV.getOperand(0);
30905 if (isNullConstant(ExtractedV.getOperand(1))) {
30906 MVT OrigVT = OrigV.getSimpleValueType();
30907 // Extract a subvector if necessary...
30908 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
30909 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
30910 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
30911 OrigVT.getVectorNumElements() / Ratio);
30912 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
30913 DAG.getIntPtrConstant(0, DL));
30915 Op = DAG.getBitcast(OpVT, OrigV);
30916 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
30923 /// Canonicalize (LSUB p, 1) -> (LADD p, -1).
30924 static SDValue combineLockSub(SDNode *N, SelectionDAG &DAG,
30925 const X86Subtarget &Subtarget) {
30926 SDValue Chain = N->getOperand(0);
30927 SDValue LHS = N->getOperand(1);
30928 SDValue RHS = N->getOperand(2);
30929 MVT VT = RHS.getSimpleValueType();
30932 auto *C = dyn_cast<ConstantSDNode>(RHS);
30933 if (!C || C->getZExtValue() != 1)
30936 RHS = DAG.getConstant(-1, DL, VT);
30937 MachineMemOperand *MMO = cast<MemSDNode>(N)->getMemOperand();
30938 return DAG.getMemIntrinsicNode(X86ISD::LADD, DL,
30939 DAG.getVTList(MVT::i32, MVT::Other),
30940 {Chain, LHS, RHS}, VT, MMO);
30943 // TEST (AND a, b) ,(AND a, b) -> TEST a, b
30944 static SDValue combineTestM(SDNode *N, SelectionDAG &DAG) {
30945 SDValue Op0 = N->getOperand(0);
30946 SDValue Op1 = N->getOperand(1);
30948 if (Op0 != Op1 || Op1->getOpcode() != ISD::AND)
30951 EVT VT = N->getValueType(0);
30954 return DAG.getNode(X86ISD::TESTM, DL, VT,
30955 Op0->getOperand(0), Op0->getOperand(1));
30958 static SDValue combineVectorCompare(SDNode *N, SelectionDAG &DAG,
30959 const X86Subtarget &Subtarget) {
30960 MVT VT = N->getSimpleValueType(0);
30963 if (N->getOperand(0) == N->getOperand(1)) {
30964 if (N->getOpcode() == X86ISD::PCMPEQ)
30965 return getOnesVector(VT, Subtarget, DAG, DL);
30966 if (N->getOpcode() == X86ISD::PCMPGT)
30967 return getZeroVector(VT, Subtarget, DAG, DL);
30974 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
30975 DAGCombinerInfo &DCI) const {
30976 SelectionDAG &DAG = DCI.DAG;
30977 switch (N->getOpcode()) {
30979 case ISD::EXTRACT_VECTOR_ELT: return combineExtractVectorElt(N, DAG, DCI);
30982 case X86ISD::SHRUNKBLEND: return combineSelect(N, DAG, DCI, Subtarget);
30983 case ISD::BITCAST: return combineBitcast(N, DAG, Subtarget);
30984 case X86ISD::CMOV: return combineCMov(N, DAG, DCI, Subtarget);
30985 case ISD::ADD: return combineAdd(N, DAG, Subtarget);
30986 case ISD::SUB: return combineSub(N, DAG, Subtarget);
30987 case X86ISD::ADC: return combineADC(N, DAG, DCI);
30988 case ISD::MUL: return combineMul(N, DAG, DCI, Subtarget);
30991 case ISD::SRL: return combineShift(N, DAG, DCI, Subtarget);
30992 case ISD::AND: return combineAnd(N, DAG, DCI, Subtarget);
30993 case ISD::OR: return combineOr(N, DAG, DCI, Subtarget);
30994 case ISD::XOR: return combineXor(N, DAG, DCI, Subtarget);
30995 case ISD::LOAD: return combineLoad(N, DAG, DCI, Subtarget);
30996 case ISD::MLOAD: return combineMaskedLoad(N, DAG, DCI, Subtarget);
30997 case ISD::STORE: return combineStore(N, DAG, Subtarget);
30998 case ISD::MSTORE: return combineMaskedStore(N, DAG, Subtarget);
30999 case ISD::SINT_TO_FP: return combineSIntToFP(N, DAG, Subtarget);
31000 case ISD::UINT_TO_FP: return combineUIntToFP(N, DAG, Subtarget);
31002 case ISD::FSUB: return combineFaddFsub(N, DAG, Subtarget);
31003 case ISD::FNEG: return combineFneg(N, DAG, Subtarget);
31004 case ISD::TRUNCATE: return combineTruncate(N, DAG, Subtarget);
31006 case X86ISD::FOR: return combineFOr(N, DAG, Subtarget);
31008 case X86ISD::FMAX: return combineFMinFMax(N, DAG);
31010 case ISD::FMAXNUM: return combineFMinNumFMaxNum(N, DAG, Subtarget);
31011 case X86ISD::FAND: return combineFAnd(N, DAG, Subtarget);
31012 case X86ISD::FANDN: return combineFAndn(N, DAG, Subtarget);
31013 case X86ISD::BT: return combineBT(N, DAG, DCI);
31014 case X86ISD::VZEXT_MOVL: return combineVZextMovl(N, DAG);
31015 case ISD::ANY_EXTEND:
31016 case ISD::ZERO_EXTEND: return combineZext(N, DAG, DCI, Subtarget);
31017 case ISD::SIGN_EXTEND: return combineSext(N, DAG, DCI, Subtarget);
31018 case ISD::SIGN_EXTEND_INREG: return combineSignExtendInReg(N, DAG, Subtarget);
31019 case ISD::SETCC: return combineSetCC(N, DAG, Subtarget);
31020 case X86ISD::SETCC: return combineX86SetCC(N, DAG, DCI, Subtarget);
31021 case X86ISD::BRCOND: return combineBrCond(N, DAG, DCI, Subtarget);
31022 case X86ISD::VZEXT: return combineVZext(N, DAG, DCI, Subtarget);
31023 case X86ISD::SHUFP: // Handle all target specific shuffles
31024 case X86ISD::INSERTPS:
31025 case X86ISD::PALIGNR:
31026 case X86ISD::VSHLDQ:
31027 case X86ISD::VSRLDQ:
31028 case X86ISD::BLENDI:
31029 case X86ISD::UNPCKH:
31030 case X86ISD::UNPCKL:
31031 case X86ISD::MOVHLPS:
31032 case X86ISD::MOVLHPS:
31033 case X86ISD::PSHUFB:
31034 case X86ISD::PSHUFD:
31035 case X86ISD::PSHUFHW:
31036 case X86ISD::PSHUFLW:
31037 case X86ISD::MOVSHDUP:
31038 case X86ISD::MOVSLDUP:
31039 case X86ISD::MOVDDUP:
31040 case X86ISD::MOVSS:
31041 case X86ISD::MOVSD:
31042 case X86ISD::VPPERM:
31043 case X86ISD::VPERMI:
31044 case X86ISD::VPERMV:
31045 case X86ISD::VPERMV3:
31046 case X86ISD::VPERMIL2:
31047 case X86ISD::VPERMILPI:
31048 case X86ISD::VPERMILPV:
31049 case X86ISD::VPERM2X128:
31050 case ISD::VECTOR_SHUFFLE: return combineShuffle(N, DAG, DCI,Subtarget);
31051 case ISD::FMA: return combineFMA(N, DAG, Subtarget);
31053 case ISD::MSCATTER: return combineGatherScatter(N, DAG);
31054 case X86ISD::LSUB: return combineLockSub(N, DAG, Subtarget);
31055 case X86ISD::TESTM: return combineTestM(N, DAG);
31056 case X86ISD::PCMPEQ:
31057 case X86ISD::PCMPGT: return combineVectorCompare(N, DAG, Subtarget);
31063 /// Return true if the target has native support for the specified value type
31064 /// and it is 'desirable' to use the type for the given node type. e.g. On x86
31065 /// i16 is legal, but undesirable since i16 instruction encodings are longer and
31066 /// some i16 instructions are slow.
31067 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
31068 if (!isTypeLegal(VT))
31070 if (VT != MVT::i16)
31077 case ISD::SIGN_EXTEND:
31078 case ISD::ZERO_EXTEND:
31079 case ISD::ANY_EXTEND:
31092 /// This function checks if any of the users of EFLAGS copies the EFLAGS. We
31093 /// know that the code that lowers COPY of EFLAGS has to use the stack, and if
31094 /// we don't adjust the stack we clobber the first frame index.
31095 /// See X86InstrInfo::copyPhysReg.
31096 bool X86TargetLowering::hasCopyImplyingStackAdjustment(
31097 MachineFunction *MF) const {
31098 const MachineRegisterInfo &MRI = MF->getRegInfo();
31100 return any_of(MRI.reg_instructions(X86::EFLAGS),
31101 [](const MachineInstr &RI) { return RI.isCopy(); });
31104 /// This method query the target whether it is beneficial for dag combiner to
31105 /// promote the specified node. If true, it should return the desired promotion
31106 /// type by reference.
31107 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
31108 EVT VT = Op.getValueType();
31109 if (VT != MVT::i16)
31112 bool Promote = false;
31113 bool Commute = false;
31114 switch (Op.getOpcode()) {
31116 case ISD::SIGN_EXTEND:
31117 case ISD::ZERO_EXTEND:
31118 case ISD::ANY_EXTEND:
31123 SDValue N0 = Op.getOperand(0);
31124 // Look out for (store (shl (load), x)).
31125 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
31138 SDValue N0 = Op.getOperand(0);
31139 SDValue N1 = Op.getOperand(1);
31140 if (!Commute && MayFoldLoad(N1))
31142 // Avoid disabling potential load folding opportunities.
31143 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
31145 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
31155 //===----------------------------------------------------------------------===//
31156 // X86 Inline Assembly Support
31157 //===----------------------------------------------------------------------===//
31159 // Helper to match a string separated by whitespace.
31160 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
31161 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
31163 for (StringRef Piece : Pieces) {
31164 if (!S.startswith(Piece)) // Check if the piece matches.
31167 S = S.substr(Piece.size());
31168 StringRef::size_type Pos = S.find_first_not_of(" \t");
31169 if (Pos == 0) // We matched a prefix.
31178 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
31180 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
31181 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
31182 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
31183 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
31185 if (AsmPieces.size() == 3)
31187 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
31194 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
31195 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
31197 const std::string &AsmStr = IA->getAsmString();
31199 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
31200 if (!Ty || Ty->getBitWidth() % 16 != 0)
31203 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
31204 SmallVector<StringRef, 4> AsmPieces;
31205 SplitString(AsmStr, AsmPieces, ";\n");
31207 switch (AsmPieces.size()) {
31208 default: return false;
31210 // FIXME: this should verify that we are targeting a 486 or better. If not,
31211 // we will turn this bswap into something that will be lowered to logical
31212 // ops instead of emitting the bswap asm. For now, we don't support 486 or
31213 // lower so don't worry about this.
31215 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
31216 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
31217 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
31218 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
31219 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
31220 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
31221 // No need to check constraints, nothing other than the equivalent of
31222 // "=r,0" would be valid here.
31223 return IntrinsicLowering::LowerToByteSwap(CI);
31226 // rorw $$8, ${0:w} --> llvm.bswap.i16
31227 if (CI->getType()->isIntegerTy(16) &&
31228 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
31229 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
31230 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
31232 StringRef ConstraintsStr = IA->getConstraintString();
31233 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
31234 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
31235 if (clobbersFlagRegisters(AsmPieces))
31236 return IntrinsicLowering::LowerToByteSwap(CI);
31240 if (CI->getType()->isIntegerTy(32) &&
31241 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
31242 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
31243 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
31244 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
31246 StringRef ConstraintsStr = IA->getConstraintString();
31247 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
31248 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
31249 if (clobbersFlagRegisters(AsmPieces))
31250 return IntrinsicLowering::LowerToByteSwap(CI);
31253 if (CI->getType()->isIntegerTy(64)) {
31254 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
31255 if (Constraints.size() >= 2 &&
31256 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
31257 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
31258 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
31259 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
31260 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
31261 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
31262 return IntrinsicLowering::LowerToByteSwap(CI);
31270 /// Given a constraint letter, return the type of constraint for this target.
31271 X86TargetLowering::ConstraintType
31272 X86TargetLowering::getConstraintType(StringRef Constraint) const {
31273 if (Constraint.size() == 1) {
31274 switch (Constraint[0]) {
31285 return C_RegisterClass;
31309 return TargetLowering::getConstraintType(Constraint);
31312 /// Examine constraint type and operand type and determine a weight value.
31313 /// This object must already have been set up with the operand type
31314 /// and the current alternative constraint selected.
31315 TargetLowering::ConstraintWeight
31316 X86TargetLowering::getSingleConstraintMatchWeight(
31317 AsmOperandInfo &info, const char *constraint) const {
31318 ConstraintWeight weight = CW_Invalid;
31319 Value *CallOperandVal = info.CallOperandVal;
31320 // If we don't have a value, we can't do a match,
31321 // but allow it at the lowest weight.
31322 if (!CallOperandVal)
31324 Type *type = CallOperandVal->getType();
31325 // Look at the constraint type.
31326 switch (*constraint) {
31328 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
31339 if (CallOperandVal->getType()->isIntegerTy())
31340 weight = CW_SpecificReg;
31345 if (type->isFloatingPointTy())
31346 weight = CW_SpecificReg;
31349 if (type->isX86_MMXTy() && Subtarget.hasMMX())
31350 weight = CW_SpecificReg;
31354 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
31355 ((type->getPrimitiveSizeInBits() == 256) && Subtarget.hasFp256()))
31356 weight = CW_Register;
31359 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
31360 if (C->getZExtValue() <= 31)
31361 weight = CW_Constant;
31365 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
31366 if (C->getZExtValue() <= 63)
31367 weight = CW_Constant;
31371 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
31372 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
31373 weight = CW_Constant;
31377 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
31378 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
31379 weight = CW_Constant;
31383 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
31384 if (C->getZExtValue() <= 3)
31385 weight = CW_Constant;
31389 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
31390 if (C->getZExtValue() <= 0xff)
31391 weight = CW_Constant;
31396 if (isa<ConstantFP>(CallOperandVal)) {
31397 weight = CW_Constant;
31401 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
31402 if ((C->getSExtValue() >= -0x80000000LL) &&
31403 (C->getSExtValue() <= 0x7fffffffLL))
31404 weight = CW_Constant;
31408 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
31409 if (C->getZExtValue() <= 0xffffffff)
31410 weight = CW_Constant;
31417 /// Try to replace an X constraint, which matches anything, with another that
31418 /// has more specific requirements based on the type of the corresponding
31420 const char *X86TargetLowering::
31421 LowerXConstraint(EVT ConstraintVT) const {
31422 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
31423 // 'f' like normal targets.
31424 if (ConstraintVT.isFloatingPoint()) {
31425 if (Subtarget.hasSSE2())
31427 if (Subtarget.hasSSE1())
31431 return TargetLowering::LowerXConstraint(ConstraintVT);
31434 /// Lower the specified operand into the Ops vector.
31435 /// If it is invalid, don't add anything to Ops.
31436 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
31437 std::string &Constraint,
31438 std::vector<SDValue>&Ops,
31439 SelectionDAG &DAG) const {
31442 // Only support length 1 constraints for now.
31443 if (Constraint.length() > 1) return;
31445 char ConstraintLetter = Constraint[0];
31446 switch (ConstraintLetter) {
31449 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
31450 if (C->getZExtValue() <= 31) {
31451 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
31452 Op.getValueType());
31458 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
31459 if (C->getZExtValue() <= 63) {
31460 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
31461 Op.getValueType());
31467 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
31468 if (isInt<8>(C->getSExtValue())) {
31469 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
31470 Op.getValueType());
31476 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
31477 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
31478 (Subtarget.is64Bit() && C->getZExtValue() == 0xffffffff)) {
31479 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
31480 Op.getValueType());
31486 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
31487 if (C->getZExtValue() <= 3) {
31488 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
31489 Op.getValueType());
31495 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
31496 if (C->getZExtValue() <= 255) {
31497 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
31498 Op.getValueType());
31504 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
31505 if (C->getZExtValue() <= 127) {
31506 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
31507 Op.getValueType());
31513 // 32-bit signed value
31514 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
31515 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
31516 C->getSExtValue())) {
31517 // Widen to 64 bits here to get it sign extended.
31518 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
31521 // FIXME gcc accepts some relocatable values here too, but only in certain
31522 // memory models; it's complicated.
31527 // 32-bit unsigned value
31528 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
31529 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
31530 C->getZExtValue())) {
31531 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
31532 Op.getValueType());
31536 // FIXME gcc accepts some relocatable values here too, but only in certain
31537 // memory models; it's complicated.
31541 // Literal immediates are always ok.
31542 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
31543 // Widen to 64 bits here to get it sign extended.
31544 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
31548 // In any sort of PIC mode addresses need to be computed at runtime by
31549 // adding in a register or some sort of table lookup. These can't
31550 // be used as immediates.
31551 if (Subtarget.isPICStyleGOT() || Subtarget.isPICStyleStubPIC())
31554 // If we are in non-pic codegen mode, we allow the address of a global (with
31555 // an optional displacement) to be used with 'i'.
31556 GlobalAddressSDNode *GA = nullptr;
31557 int64_t Offset = 0;
31559 // Match either (GA), (GA+C), (GA+C1+C2), etc.
31561 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
31562 Offset += GA->getOffset();
31564 } else if (Op.getOpcode() == ISD::ADD) {
31565 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
31566 Offset += C->getZExtValue();
31567 Op = Op.getOperand(0);
31570 } else if (Op.getOpcode() == ISD::SUB) {
31571 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
31572 Offset += -C->getZExtValue();
31573 Op = Op.getOperand(0);
31578 // Otherwise, this isn't something we can handle, reject it.
31582 const GlobalValue *GV = GA->getGlobal();
31583 // If we require an extra load to get this address, as in PIC mode, we
31584 // can't accept it.
31585 if (isGlobalStubReference(Subtarget.classifyGlobalReference(GV)))
31588 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
31589 GA->getValueType(0), Offset);
31594 if (Result.getNode()) {
31595 Ops.push_back(Result);
31598 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
31601 /// Check if \p RC is a general purpose register class.
31602 /// I.e., GR* or one of their variant.
31603 static bool isGRClass(const TargetRegisterClass &RC) {
31604 switch (RC.getID()) {
31605 case X86::GR8RegClassID:
31606 case X86::GR8_ABCD_LRegClassID:
31607 case X86::GR8_ABCD_HRegClassID:
31608 case X86::GR8_NOREXRegClassID:
31609 case X86::GR16RegClassID:
31610 case X86::GR16_ABCDRegClassID:
31611 case X86::GR16_NOREXRegClassID:
31612 case X86::GR32RegClassID:
31613 case X86::GR32_ABCDRegClassID:
31614 case X86::GR32_TCRegClassID:
31615 case X86::GR32_NOREXRegClassID:
31616 case X86::GR32_NOAXRegClassID:
31617 case X86::GR32_NOSPRegClassID:
31618 case X86::GR32_NOREX_NOSPRegClassID:
31619 case X86::GR32_ADRegClassID:
31620 case X86::GR64RegClassID:
31621 case X86::GR64_ABCDRegClassID:
31622 case X86::GR64_TCRegClassID:
31623 case X86::GR64_TCW64RegClassID:
31624 case X86::GR64_NOREXRegClassID:
31625 case X86::GR64_NOSPRegClassID:
31626 case X86::GR64_NOREX_NOSPRegClassID:
31627 case X86::LOW32_ADDR_ACCESSRegClassID:
31628 case X86::LOW32_ADDR_ACCESS_RBPRegClassID:
31635 /// Check if \p RC is a vector register class.
31636 /// I.e., FR* / VR* or one of their variant.
31637 static bool isFRClass(const TargetRegisterClass &RC) {
31638 switch (RC.getID()) {
31639 case X86::FR32RegClassID:
31640 case X86::FR32XRegClassID:
31641 case X86::FR64RegClassID:
31642 case X86::FR64XRegClassID:
31643 case X86::FR128RegClassID:
31644 case X86::VR64RegClassID:
31645 case X86::VR128RegClassID:
31646 case X86::VR128LRegClassID:
31647 case X86::VR128HRegClassID:
31648 case X86::VR128XRegClassID:
31649 case X86::VR256RegClassID:
31650 case X86::VR256LRegClassID:
31651 case X86::VR256HRegClassID:
31652 case X86::VR256XRegClassID:
31653 case X86::VR512RegClassID:
31660 std::pair<unsigned, const TargetRegisterClass *>
31661 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
31662 StringRef Constraint,
31664 // First, see if this is a constraint that directly corresponds to an LLVM
31666 if (Constraint.size() == 1) {
31667 // GCC Constraint Letters
31668 switch (Constraint[0]) {
31670 // TODO: Slight differences here in allocation order and leaving
31671 // RIP in the class. Do they matter any more here than they do
31672 // in the normal allocation?
31673 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
31674 if (Subtarget.is64Bit()) {
31675 if (VT == MVT::i32 || VT == MVT::f32)
31676 return std::make_pair(0U, &X86::GR32RegClass);
31677 if (VT == MVT::i16)
31678 return std::make_pair(0U, &X86::GR16RegClass);
31679 if (VT == MVT::i8 || VT == MVT::i1)
31680 return std::make_pair(0U, &X86::GR8RegClass);
31681 if (VT == MVT::i64 || VT == MVT::f64)
31682 return std::make_pair(0U, &X86::GR64RegClass);
31685 // 32-bit fallthrough
31686 case 'Q': // Q_REGS
31687 if (VT == MVT::i32 || VT == MVT::f32)
31688 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
31689 if (VT == MVT::i16)
31690 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
31691 if (VT == MVT::i8 || VT == MVT::i1)
31692 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
31693 if (VT == MVT::i64)
31694 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
31696 case 'r': // GENERAL_REGS
31697 case 'l': // INDEX_REGS
31698 if (VT == MVT::i8 || VT == MVT::i1)
31699 return std::make_pair(0U, &X86::GR8RegClass);
31700 if (VT == MVT::i16)
31701 return std::make_pair(0U, &X86::GR16RegClass);
31702 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget.is64Bit())
31703 return std::make_pair(0U, &X86::GR32RegClass);
31704 return std::make_pair(0U, &X86::GR64RegClass);
31705 case 'R': // LEGACY_REGS
31706 if (VT == MVT::i8 || VT == MVT::i1)
31707 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
31708 if (VT == MVT::i16)
31709 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
31710 if (VT == MVT::i32 || !Subtarget.is64Bit())
31711 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
31712 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
31713 case 'f': // FP Stack registers.
31714 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
31715 // value to the correct fpstack register class.
31716 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
31717 return std::make_pair(0U, &X86::RFP32RegClass);
31718 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
31719 return std::make_pair(0U, &X86::RFP64RegClass);
31720 return std::make_pair(0U, &X86::RFP80RegClass);
31721 case 'y': // MMX_REGS if MMX allowed.
31722 if (!Subtarget.hasMMX()) break;
31723 return std::make_pair(0U, &X86::VR64RegClass);
31724 case 'Y': // SSE_REGS if SSE2 allowed
31725 if (!Subtarget.hasSSE2()) break;
31727 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
31728 if (!Subtarget.hasSSE1()) break;
31730 switch (VT.SimpleTy) {
31732 // Scalar SSE types.
31735 return std::make_pair(0U, &X86::FR32RegClass);
31738 return std::make_pair(0U, &X86::FR64RegClass);
31739 // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
31747 return std::make_pair(0U, &X86::VR128RegClass);
31755 return std::make_pair(0U, &X86::VR256RegClass);
31760 return std::make_pair(0U, &X86::VR512RegClass);
31766 // Use the default implementation in TargetLowering to convert the register
31767 // constraint into a member of a register class.
31768 std::pair<unsigned, const TargetRegisterClass*> Res;
31769 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
31771 // Not found as a standard register?
31773 // Map st(0) -> st(7) -> ST0
31774 if (Constraint.size() == 7 && Constraint[0] == '{' &&
31775 tolower(Constraint[1]) == 's' &&
31776 tolower(Constraint[2]) == 't' &&
31777 Constraint[3] == '(' &&
31778 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
31779 Constraint[5] == ')' &&
31780 Constraint[6] == '}') {
31782 Res.first = X86::FP0+Constraint[4]-'0';
31783 Res.second = &X86::RFP80RegClass;
31787 // GCC allows "st(0)" to be called just plain "st".
31788 if (StringRef("{st}").equals_lower(Constraint)) {
31789 Res.first = X86::FP0;
31790 Res.second = &X86::RFP80RegClass;
31795 if (StringRef("{flags}").equals_lower(Constraint)) {
31796 Res.first = X86::EFLAGS;
31797 Res.second = &X86::CCRRegClass;
31801 // 'A' means EAX + EDX.
31802 if (Constraint == "A") {
31803 Res.first = X86::EAX;
31804 Res.second = &X86::GR32_ADRegClass;
31810 // Otherwise, check to see if this is a register class of the wrong value
31811 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
31812 // turn into {ax},{dx}.
31813 // MVT::Other is used to specify clobber names.
31814 if (Res.second->hasType(VT) || VT == MVT::Other)
31815 return Res; // Correct type already, nothing to do.
31817 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
31818 // return "eax". This should even work for things like getting 64bit integer
31819 // registers when given an f64 type.
31820 const TargetRegisterClass *Class = Res.second;
31821 // The generic code will match the first register class that contains the
31822 // given register. Thus, based on the ordering of the tablegened file,
31823 // the "plain" GR classes might not come first.
31824 // Therefore, use a helper method.
31825 if (isGRClass(*Class)) {
31826 unsigned Size = VT.getSizeInBits();
31827 if (Size == 1) Size = 8;
31828 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
31830 Res.first = DestReg;
31831 Res.second = Size == 8 ? &X86::GR8RegClass
31832 : Size == 16 ? &X86::GR16RegClass
31833 : Size == 32 ? &X86::GR32RegClass
31834 : &X86::GR64RegClass;
31835 assert(Res.second->contains(Res.first) && "Register in register class");
31837 // No register found/type mismatch.
31839 Res.second = nullptr;
31841 } else if (isFRClass(*Class)) {
31842 // Handle references to XMM physical registers that got mapped into the
31843 // wrong class. This can happen with constraints like {xmm0} where the
31844 // target independent register mapper will just pick the first match it can
31845 // find, ignoring the required type.
31847 // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
31848 if (VT == MVT::f32 || VT == MVT::i32)
31849 Res.second = &X86::FR32RegClass;
31850 else if (VT == MVT::f64 || VT == MVT::i64)
31851 Res.second = &X86::FR64RegClass;
31852 else if (X86::VR128RegClass.hasType(VT))
31853 Res.second = &X86::VR128RegClass;
31854 else if (X86::VR256RegClass.hasType(VT))
31855 Res.second = &X86::VR256RegClass;
31856 else if (X86::VR512RegClass.hasType(VT))
31857 Res.second = &X86::VR512RegClass;
31859 // Type mismatch and not a clobber: Return an error;
31861 Res.second = nullptr;
31868 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
31869 const AddrMode &AM, Type *Ty,
31870 unsigned AS) const {
31871 // Scaling factors are not free at all.
31872 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
31873 // will take 2 allocations in the out of order engine instead of 1
31874 // for plain addressing mode, i.e. inst (reg1).
31876 // vaddps (%rsi,%drx), %ymm0, %ymm1
31877 // Requires two allocations (one for the load, one for the computation)
31879 // vaddps (%rsi), %ymm0, %ymm1
31880 // Requires just 1 allocation, i.e., freeing allocations for other operations
31881 // and having less micro operations to execute.
31883 // For some X86 architectures, this is even worse because for instance for
31884 // stores, the complex addressing mode forces the instruction to use the
31885 // "load" ports instead of the dedicated "store" port.
31886 // E.g., on Haswell:
31887 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
31888 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
31889 if (isLegalAddressingMode(DL, AM, Ty, AS))
31890 // Scale represents reg2 * scale, thus account for 1
31891 // as soon as we use a second register.
31892 return AM.Scale != 0;
31896 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
31897 // Integer division on x86 is expensive. However, when aggressively optimizing
31898 // for code size, we prefer to use a div instruction, as it is usually smaller
31899 // than the alternative sequence.
31900 // The exception to this is vector division. Since x86 doesn't have vector
31901 // integer division, leaving the division as-is is a loss even in terms of
31902 // size, because it will have to be scalarized, while the alternative code
31903 // sequence can be performed in vector form.
31904 bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
31905 Attribute::MinSize);
31906 return OptSize && !VT.isVector();
31909 void X86TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
31910 if (!Subtarget.is64Bit())
31913 // Update IsSplitCSR in X86MachineFunctionInfo.
31914 X86MachineFunctionInfo *AFI =
31915 Entry->getParent()->getInfo<X86MachineFunctionInfo>();
31916 AFI->setIsSplitCSR(true);
31919 void X86TargetLowering::insertCopiesSplitCSR(
31920 MachineBasicBlock *Entry,
31921 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
31922 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
31923 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
31927 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
31928 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
31929 MachineBasicBlock::iterator MBBI = Entry->begin();
31930 for (const MCPhysReg *I = IStart; *I; ++I) {
31931 const TargetRegisterClass *RC = nullptr;
31932 if (X86::GR64RegClass.contains(*I))
31933 RC = &X86::GR64RegClass;
31935 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
31937 unsigned NewVR = MRI->createVirtualRegister(RC);
31938 // Create copy from CSR to a virtual register.
31939 // FIXME: this currently does not emit CFI pseudo-instructions, it works
31940 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
31941 // nounwind. If we want to generalize this later, we may need to emit
31942 // CFI pseudo-instructions.
31943 assert(Entry->getParent()->getFunction()->hasFnAttribute(
31944 Attribute::NoUnwind) &&
31945 "Function should be nounwind in insertCopiesSplitCSR!");
31946 Entry->addLiveIn(*I);
31947 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
31950 // Insert the copy-back instructions right before the terminator.
31951 for (auto *Exit : Exits)
31952 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
31953 TII->get(TargetOpcode::COPY), *I)