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 "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
60 #define DEBUG_TYPE "x86-isel"
62 STATISTIC(NumTailCalls, "Number of tail calls");
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65 "x86-experimental-vector-widening-legalization", cl::init(false),
66 cl::desc("Enable an experimental vector type legalization through widening "
67 "rather than promotion."),
70 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
71 const X86Subtarget &STI)
72 : TargetLowering(TM), Subtarget(&STI) {
73 X86ScalarSSEf64 = Subtarget->hasSSE2();
74 X86ScalarSSEf32 = Subtarget->hasSSE1();
75 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
77 // Set up the TargetLowering object.
78 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
80 // X86 is weird. It always uses i8 for shift amounts and setcc results.
81 setBooleanContents(ZeroOrOneBooleanContent);
82 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
83 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
85 // For 64-bit, since we have so many registers, use the ILP scheduler.
86 // For 32-bit, use the register pressure specific scheduling.
87 // For Atom, always use ILP scheduling.
88 if (Subtarget->isAtom())
89 setSchedulingPreference(Sched::ILP);
90 else if (Subtarget->is64Bit())
91 setSchedulingPreference(Sched::ILP);
93 setSchedulingPreference(Sched::RegPressure);
94 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
95 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
97 // Bypass expensive divides on Atom when compiling with O2.
98 if (TM.getOptLevel() >= CodeGenOpt::Default) {
99 if (Subtarget->hasSlowDivide32())
100 addBypassSlowDiv(32, 8);
101 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
102 addBypassSlowDiv(64, 16);
105 if (Subtarget->isTargetKnownWindowsMSVC()) {
106 // Setup Windows compiler runtime calls.
107 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
108 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
109 setLibcallName(RTLIB::SREM_I64, "_allrem");
110 setLibcallName(RTLIB::UREM_I64, "_aullrem");
111 setLibcallName(RTLIB::MUL_I64, "_allmul");
112 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
113 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
114 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
115 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
116 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
118 // The _ftol2 runtime function has an unusual calling conv, which
119 // is modeled by a special pseudo-instruction.
120 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
121 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
122 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
123 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
126 if (Subtarget->isTargetDarwin()) {
127 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
128 setUseUnderscoreSetJmp(false);
129 setUseUnderscoreLongJmp(false);
130 } else if (Subtarget->isTargetWindowsGNU()) {
131 // MS runtime is weird: it exports _setjmp, but longjmp!
132 setUseUnderscoreSetJmp(true);
133 setUseUnderscoreLongJmp(false);
135 setUseUnderscoreSetJmp(true);
136 setUseUnderscoreLongJmp(true);
139 // Set up the register classes.
140 addRegisterClass(MVT::i8, &X86::GR8RegClass);
141 addRegisterClass(MVT::i16, &X86::GR16RegClass);
142 addRegisterClass(MVT::i32, &X86::GR32RegClass);
143 if (Subtarget->is64Bit())
144 addRegisterClass(MVT::i64, &X86::GR64RegClass);
146 for (MVT VT : MVT::integer_valuetypes())
147 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
149 // We don't accept any truncstore of integer registers.
150 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
151 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
152 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
153 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
154 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
155 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
157 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
159 // SETOEQ and SETUNE require checking two conditions.
160 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
161 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
162 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
163 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
164 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
165 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
167 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
169 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
170 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
171 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
173 if (Subtarget->is64Bit()) {
174 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
175 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
176 } else if (!Subtarget->useSoftFloat()) {
177 // We have an algorithm for SSE2->double, and we turn this into a
178 // 64-bit FILD followed by conditional FADD for other targets.
179 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
180 // We have an algorithm for SSE2, and we turn this into a 64-bit
181 // FILD for other targets.
182 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
185 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
187 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
188 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
190 if (!Subtarget->useSoftFloat()) {
191 // SSE has no i16 to fp conversion, only i32
192 if (X86ScalarSSEf32) {
193 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
194 // f32 and f64 cases are Legal, f80 case is not
195 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
197 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
198 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
201 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
202 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
205 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
206 // are Legal, f80 is custom lowered.
207 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
208 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
210 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
212 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
213 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
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 // Handle FP_TO_UINT by promoting the destination to a larger signed
226 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
227 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
228 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
230 if (Subtarget->is64Bit()) {
231 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
232 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
233 } else if (!Subtarget->useSoftFloat()) {
234 // Since AVX is a superset of SSE3, only check for SSE here.
235 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
236 // Expand FP_TO_UINT into a select.
237 // FIXME: We would like to use a Custom expander here eventually to do
238 // the optimal thing for SSE vs. the default expansion in the legalizer.
239 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
241 // With SSE3 we can use fisttpll to convert to a signed i64; without
242 // SSE, we're stuck with a fistpll.
243 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
246 if (isTargetFTOL()) {
247 // Use the _ftol2 runtime function, which has a pseudo-instruction
248 // to handle its weird calling convention.
249 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
252 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
253 if (!X86ScalarSSEf64) {
254 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
255 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
256 if (Subtarget->is64Bit()) {
257 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
258 // Without SSE, i64->f64 goes through memory.
259 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
263 // Scalar integer divide and remainder are lowered to use operations that
264 // produce two results, to match the available instructions. This exposes
265 // the two-result form to trivial CSE, which is able to combine x/y and x%y
266 // into a single instruction.
268 // Scalar integer multiply-high is also lowered to use two-result
269 // operations, to match the available instructions. However, plain multiply
270 // (low) operations are left as Legal, as there are single-result
271 // instructions for this in x86. Using the two-result multiply instructions
272 // when both high and low results are needed must be arranged by dagcombine.
273 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
275 setOperationAction(ISD::MULHS, VT, Expand);
276 setOperationAction(ISD::MULHU, VT, Expand);
277 setOperationAction(ISD::SDIV, VT, Expand);
278 setOperationAction(ISD::UDIV, VT, Expand);
279 setOperationAction(ISD::SREM, VT, Expand);
280 setOperationAction(ISD::UREM, VT, Expand);
282 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
283 setOperationAction(ISD::ADDC, VT, Custom);
284 setOperationAction(ISD::ADDE, VT, Custom);
285 setOperationAction(ISD::SUBC, VT, Custom);
286 setOperationAction(ISD::SUBE, VT, Custom);
289 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
290 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
291 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
292 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
293 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
294 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
295 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
296 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
297 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
298 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
299 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
300 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
301 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
302 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
303 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
304 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
305 if (Subtarget->is64Bit())
306 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
307 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
308 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
309 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
310 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 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
319 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
320 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
321 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
322 if (Subtarget->hasBMI()) {
323 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
324 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
325 if (Subtarget->is64Bit())
326 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
328 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
329 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
330 if (Subtarget->is64Bit())
331 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
334 if (Subtarget->hasLZCNT()) {
335 // When promoting the i8 variants, force them to i32 for a shorter
337 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
338 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
339 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
340 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
341 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
342 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
343 if (Subtarget->is64Bit())
344 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
346 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
347 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
348 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
349 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
350 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
351 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
352 if (Subtarget->is64Bit()) {
353 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
354 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
358 // Special handling for half-precision floating point conversions.
359 // If we don't have F16C support, then lower half float conversions
360 // into library calls.
361 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
362 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
363 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
366 // There's never any support for operations beyond MVT::f32.
367 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
368 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
369 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
370 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
372 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
373 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
374 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
375 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
376 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
377 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
379 if (Subtarget->hasPOPCNT()) {
380 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
382 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
383 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
384 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
385 if (Subtarget->is64Bit())
386 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
389 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
391 if (!Subtarget->hasMOVBE())
392 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
394 // These should be promoted to a larger select which is supported.
395 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
396 // X86 wants to expand cmov itself.
397 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
398 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
399 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
400 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
401 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
402 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
403 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
404 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
405 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
406 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
407 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
408 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
409 if (Subtarget->is64Bit()) {
410 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
411 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
413 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
414 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
415 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
416 // support continuation, user-level threading, and etc.. As a result, no
417 // other SjLj exception interfaces are implemented and please don't build
418 // your own exception handling based on them.
419 // LLVM/Clang supports zero-cost DWARF exception handling.
420 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
421 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
424 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
425 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
426 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
427 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
428 if (Subtarget->is64Bit())
429 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
430 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
431 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
432 if (Subtarget->is64Bit()) {
433 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
434 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
435 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
436 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
437 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
439 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
440 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
441 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
442 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
443 if (Subtarget->is64Bit()) {
444 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
445 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
446 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
449 if (Subtarget->hasSSE1())
450 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
452 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
454 // Expand certain atomics
455 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
457 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
458 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
459 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
462 if (Subtarget->hasCmpxchg16b()) {
463 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
466 // FIXME - use subtarget debug flags
467 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
468 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
469 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
472 if (Subtarget->is64Bit()) {
473 setExceptionPointerRegister(X86::RAX);
474 setExceptionSelectorRegister(X86::RDX);
476 setExceptionPointerRegister(X86::EAX);
477 setExceptionSelectorRegister(X86::EDX);
479 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
480 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
482 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
483 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
485 setOperationAction(ISD::TRAP, MVT::Other, Legal);
486 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
488 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
489 setOperationAction(ISD::VASTART , MVT::Other, Custom);
490 setOperationAction(ISD::VAEND , MVT::Other, Expand);
491 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
492 // TargetInfo::X86_64ABIBuiltinVaList
493 setOperationAction(ISD::VAARG , MVT::Other, Custom);
494 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
496 // TargetInfo::CharPtrBuiltinVaList
497 setOperationAction(ISD::VAARG , MVT::Other, Expand);
498 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
501 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
502 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
504 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
506 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
507 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
508 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
510 if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
511 // f32 and f64 use SSE.
512 // Set up the FP register classes.
513 addRegisterClass(MVT::f32, &X86::FR32RegClass);
514 addRegisterClass(MVT::f64, &X86::FR64RegClass);
516 // Use ANDPD to simulate FABS.
517 setOperationAction(ISD::FABS , MVT::f64, Custom);
518 setOperationAction(ISD::FABS , MVT::f32, Custom);
520 // Use XORP to simulate FNEG.
521 setOperationAction(ISD::FNEG , MVT::f64, Custom);
522 setOperationAction(ISD::FNEG , MVT::f32, Custom);
524 // Use ANDPD and ORPD to simulate FCOPYSIGN.
525 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
526 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
528 // Lower this to FGETSIGNx86 plus an AND.
529 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
530 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
532 // We don't support sin/cos/fmod
533 setOperationAction(ISD::FSIN , MVT::f64, Expand);
534 setOperationAction(ISD::FCOS , MVT::f64, Expand);
535 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
536 setOperationAction(ISD::FSIN , MVT::f32, Expand);
537 setOperationAction(ISD::FCOS , MVT::f32, Expand);
538 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
540 // Expand FP immediates into loads from the stack, except for the special
542 addLegalFPImmediate(APFloat(+0.0)); // xorpd
543 addLegalFPImmediate(APFloat(+0.0f)); // xorps
544 } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
545 // Use SSE for f32, x87 for f64.
546 // Set up the FP register classes.
547 addRegisterClass(MVT::f32, &X86::FR32RegClass);
548 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
550 // Use ANDPS to simulate FABS.
551 setOperationAction(ISD::FABS , MVT::f32, Custom);
553 // Use XORP to simulate FNEG.
554 setOperationAction(ISD::FNEG , MVT::f32, Custom);
556 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
558 // Use ANDPS and ORPS to simulate FCOPYSIGN.
559 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
560 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
562 // We don't support sin/cos/fmod
563 setOperationAction(ISD::FSIN , MVT::f32, Expand);
564 setOperationAction(ISD::FCOS , MVT::f32, Expand);
565 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
567 // Special cases we handle for FP constants.
568 addLegalFPImmediate(APFloat(+0.0f)); // xorps
569 addLegalFPImmediate(APFloat(+0.0)); // FLD0
570 addLegalFPImmediate(APFloat(+1.0)); // FLD1
571 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
572 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
574 if (!TM.Options.UnsafeFPMath) {
575 setOperationAction(ISD::FSIN , MVT::f64, Expand);
576 setOperationAction(ISD::FCOS , MVT::f64, Expand);
577 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
579 } else if (!Subtarget->useSoftFloat()) {
580 // f32 and f64 in x87.
581 // Set up the FP register classes.
582 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
583 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
585 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
586 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
587 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
588 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
590 if (!TM.Options.UnsafeFPMath) {
591 setOperationAction(ISD::FSIN , MVT::f64, Expand);
592 setOperationAction(ISD::FSIN , MVT::f32, Expand);
593 setOperationAction(ISD::FCOS , MVT::f64, Expand);
594 setOperationAction(ISD::FCOS , MVT::f32, Expand);
595 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
596 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
598 addLegalFPImmediate(APFloat(+0.0)); // FLD0
599 addLegalFPImmediate(APFloat(+1.0)); // FLD1
600 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
601 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
602 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
603 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
604 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
605 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
608 // We don't support FMA.
609 setOperationAction(ISD::FMA, MVT::f64, Expand);
610 setOperationAction(ISD::FMA, MVT::f32, Expand);
612 // Long double always uses X87.
613 if (!Subtarget->useSoftFloat()) {
614 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
615 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
616 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
618 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
619 addLegalFPImmediate(TmpFlt); // FLD0
621 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
624 APFloat TmpFlt2(+1.0);
625 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
627 addLegalFPImmediate(TmpFlt2); // FLD1
628 TmpFlt2.changeSign();
629 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
632 if (!TM.Options.UnsafeFPMath) {
633 setOperationAction(ISD::FSIN , MVT::f80, Expand);
634 setOperationAction(ISD::FCOS , MVT::f80, Expand);
635 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
638 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
639 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
640 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
641 setOperationAction(ISD::FRINT, MVT::f80, Expand);
642 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
643 setOperationAction(ISD::FMA, MVT::f80, Expand);
646 // Always use a library call for pow.
647 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
648 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
649 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
651 setOperationAction(ISD::FLOG, MVT::f80, Expand);
652 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
653 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
654 setOperationAction(ISD::FEXP, MVT::f80, Expand);
655 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
656 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
657 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
659 // First set operation action for all vector types to either promote
660 // (for widening) or expand (for scalarization). Then we will selectively
661 // turn on ones that can be effectively codegen'd.
662 for (MVT VT : MVT::vector_valuetypes()) {
663 setOperationAction(ISD::ADD , VT, Expand);
664 setOperationAction(ISD::SUB , VT, Expand);
665 setOperationAction(ISD::FADD, VT, Expand);
666 setOperationAction(ISD::FNEG, VT, Expand);
667 setOperationAction(ISD::FSUB, VT, Expand);
668 setOperationAction(ISD::MUL , VT, Expand);
669 setOperationAction(ISD::FMUL, VT, Expand);
670 setOperationAction(ISD::SDIV, VT, Expand);
671 setOperationAction(ISD::UDIV, VT, Expand);
672 setOperationAction(ISD::FDIV, VT, Expand);
673 setOperationAction(ISD::SREM, VT, Expand);
674 setOperationAction(ISD::UREM, VT, Expand);
675 setOperationAction(ISD::LOAD, VT, Expand);
676 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
677 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
678 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
679 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
680 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
681 setOperationAction(ISD::FABS, VT, Expand);
682 setOperationAction(ISD::FSIN, VT, Expand);
683 setOperationAction(ISD::FSINCOS, VT, Expand);
684 setOperationAction(ISD::FCOS, VT, Expand);
685 setOperationAction(ISD::FSINCOS, VT, Expand);
686 setOperationAction(ISD::FREM, VT, Expand);
687 setOperationAction(ISD::FMA, VT, Expand);
688 setOperationAction(ISD::FPOWI, VT, Expand);
689 setOperationAction(ISD::FSQRT, VT, Expand);
690 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
691 setOperationAction(ISD::FFLOOR, VT, Expand);
692 setOperationAction(ISD::FCEIL, VT, Expand);
693 setOperationAction(ISD::FTRUNC, VT, Expand);
694 setOperationAction(ISD::FRINT, VT, Expand);
695 setOperationAction(ISD::FNEARBYINT, VT, Expand);
696 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
697 setOperationAction(ISD::MULHS, VT, Expand);
698 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
699 setOperationAction(ISD::MULHU, VT, Expand);
700 setOperationAction(ISD::SDIVREM, VT, Expand);
701 setOperationAction(ISD::UDIVREM, VT, Expand);
702 setOperationAction(ISD::FPOW, VT, Expand);
703 setOperationAction(ISD::CTPOP, VT, Expand);
704 setOperationAction(ISD::CTTZ, VT, Expand);
705 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
706 setOperationAction(ISD::CTLZ, VT, Expand);
707 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
708 setOperationAction(ISD::SHL, VT, Expand);
709 setOperationAction(ISD::SRA, VT, Expand);
710 setOperationAction(ISD::SRL, VT, Expand);
711 setOperationAction(ISD::ROTL, VT, Expand);
712 setOperationAction(ISD::ROTR, VT, Expand);
713 setOperationAction(ISD::BSWAP, VT, Expand);
714 setOperationAction(ISD::SETCC, VT, Expand);
715 setOperationAction(ISD::FLOG, VT, Expand);
716 setOperationAction(ISD::FLOG2, VT, Expand);
717 setOperationAction(ISD::FLOG10, VT, Expand);
718 setOperationAction(ISD::FEXP, VT, Expand);
719 setOperationAction(ISD::FEXP2, VT, Expand);
720 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
721 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
722 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
723 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
724 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
725 setOperationAction(ISD::TRUNCATE, VT, Expand);
726 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
727 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
728 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
729 setOperationAction(ISD::VSELECT, VT, Expand);
730 setOperationAction(ISD::SELECT_CC, VT, Expand);
731 for (MVT InnerVT : MVT::vector_valuetypes()) {
732 setTruncStoreAction(InnerVT, VT, Expand);
734 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
735 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
737 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
738 // types, we have to deal with them whether we ask for Expansion or not.
739 // Setting Expand causes its own optimisation problems though, so leave
741 if (VT.getVectorElementType() == MVT::i1)
742 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
744 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
745 // split/scalarized right now.
746 if (VT.getVectorElementType() == MVT::f16)
747 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
751 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
752 // with -msoft-float, disable use of MMX as well.
753 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
754 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
755 // No operations on x86mmx supported, everything uses intrinsics.
758 // MMX-sized vectors (other than x86mmx) are expected to be expanded
759 // into smaller operations.
760 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
761 setOperationAction(ISD::MULHS, MMXTy, Expand);
762 setOperationAction(ISD::AND, MMXTy, Expand);
763 setOperationAction(ISD::OR, MMXTy, Expand);
764 setOperationAction(ISD::XOR, MMXTy, Expand);
765 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
766 setOperationAction(ISD::SELECT, MMXTy, Expand);
767 setOperationAction(ISD::BITCAST, MMXTy, Expand);
769 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
771 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
772 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
774 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
775 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
776 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
777 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
778 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
779 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
780 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
781 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
782 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
783 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
784 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
785 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
786 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
787 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
790 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
791 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
793 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
794 // registers cannot be used even for integer operations.
795 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
796 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
797 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
798 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
800 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
801 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
802 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
803 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
804 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
805 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
806 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
807 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
808 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
809 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
810 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
811 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
812 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
813 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
814 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
815 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
816 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
817 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
818 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
819 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
820 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
821 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
822 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
824 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
825 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
826 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
827 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
829 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
830 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
831 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
832 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
834 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
835 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
836 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
837 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
838 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
840 setOperationAction(ISD::CTPOP, MVT::v16i8, Custom);
841 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
842 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
843 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
845 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
846 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
847 MVT VT = (MVT::SimpleValueType)i;
848 // Do not attempt to custom lower non-power-of-2 vectors
849 if (!isPowerOf2_32(VT.getVectorNumElements()))
851 // Do not attempt to custom lower non-128-bit vectors
852 if (!VT.is128BitVector())
854 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
855 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
856 setOperationAction(ISD::VSELECT, VT, Custom);
857 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
860 // We support custom legalizing of sext and anyext loads for specific
861 // memory vector types which we can load as a scalar (or sequence of
862 // scalars) and extend in-register to a legal 128-bit vector type. For sext
863 // loads these must work with a single scalar load.
864 for (MVT VT : MVT::integer_vector_valuetypes()) {
865 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
866 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
867 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
868 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
869 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
870 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
871 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
872 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
873 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
876 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
877 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
878 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
879 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
880 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
881 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
882 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
883 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
885 if (Subtarget->is64Bit()) {
886 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
887 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
890 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
891 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
892 MVT VT = (MVT::SimpleValueType)i;
894 // Do not attempt to promote non-128-bit vectors
895 if (!VT.is128BitVector())
898 setOperationAction(ISD::AND, VT, Promote);
899 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
900 setOperationAction(ISD::OR, VT, Promote);
901 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
902 setOperationAction(ISD::XOR, VT, Promote);
903 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
904 setOperationAction(ISD::LOAD, VT, Promote);
905 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
906 setOperationAction(ISD::SELECT, VT, Promote);
907 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
910 // Custom lower v2i64 and v2f64 selects.
911 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
912 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
913 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
914 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
916 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
917 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
919 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
921 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
922 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
923 // As there is no 64-bit GPR available, we need build a special custom
924 // sequence to convert from v2i32 to v2f32.
925 if (!Subtarget->is64Bit())
926 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
928 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
929 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
931 for (MVT VT : MVT::fp_vector_valuetypes())
932 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
934 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
935 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
936 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
939 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
940 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
941 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
942 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
943 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
944 setOperationAction(ISD::FRINT, RoundedTy, Legal);
945 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
948 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
949 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
950 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
951 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
952 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
953 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
954 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
955 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
957 // FIXME: Do we need to handle scalar-to-vector here?
958 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
960 // We directly match byte blends in the backend as they match the VSELECT
962 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
964 // SSE41 brings specific instructions for doing vector sign extend even in
965 // cases where we don't have SRA.
966 for (MVT VT : MVT::integer_vector_valuetypes()) {
967 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
968 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
969 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
972 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
973 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
974 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
975 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
976 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
977 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
978 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
980 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
981 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
982 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
983 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
984 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
985 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
987 // i8 and i16 vectors are custom because the source register and source
988 // source memory operand types are not the same width. f32 vectors are
989 // custom since the immediate controlling the insert encodes additional
991 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
992 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
993 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
994 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
996 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
997 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
998 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
999 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1001 // FIXME: these should be Legal, but that's only for the case where
1002 // the index is constant. For now custom expand to deal with that.
1003 if (Subtarget->is64Bit()) {
1004 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1005 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1009 if (Subtarget->hasSSE2()) {
1010 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1011 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1012 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1014 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1015 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1017 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1018 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1020 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1021 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1023 // In the customized shift lowering, the legal cases in AVX2 will be
1025 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1026 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1028 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1029 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1031 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1032 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1035 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1036 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1037 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1038 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1039 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1040 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1041 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1043 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1044 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1045 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1047 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1048 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1049 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1050 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1051 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1052 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1053 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1054 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1055 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1056 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1057 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1058 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1060 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1061 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1062 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1063 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1064 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1065 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1066 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1067 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1068 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1069 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1070 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1071 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1073 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1074 // even though v8i16 is a legal type.
1075 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1076 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1077 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1079 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1080 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1081 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1083 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1084 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1086 for (MVT VT : MVT::fp_vector_valuetypes())
1087 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1089 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1090 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1092 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1093 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1095 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1096 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1098 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1099 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1100 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1101 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1103 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1104 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1105 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1107 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1108 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1109 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1110 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1111 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1112 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1113 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1114 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1115 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1116 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1117 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1118 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1120 setOperationAction(ISD::CTPOP, MVT::v32i8, Custom);
1121 setOperationAction(ISD::CTPOP, MVT::v16i16, Custom);
1122 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1123 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1125 if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1126 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1127 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1128 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1129 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1130 setOperationAction(ISD::FMA, MVT::f32, Legal);
1131 setOperationAction(ISD::FMA, MVT::f64, Legal);
1134 if (Subtarget->hasInt256()) {
1135 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1136 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1137 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1138 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1140 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1141 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1142 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1143 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1145 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1146 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1147 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1148 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1150 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1151 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1152 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1153 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1155 setOperationAction(ISD::SMAX, MVT::v32i8, Legal);
1156 setOperationAction(ISD::SMAX, MVT::v16i16, Legal);
1157 setOperationAction(ISD::SMAX, MVT::v8i32, Legal);
1158 setOperationAction(ISD::UMAX, MVT::v32i8, Legal);
1159 setOperationAction(ISD::UMAX, MVT::v16i16, Legal);
1160 setOperationAction(ISD::UMAX, MVT::v8i32, Legal);
1161 setOperationAction(ISD::SMIN, MVT::v32i8, Legal);
1162 setOperationAction(ISD::SMIN, MVT::v16i16, Legal);
1163 setOperationAction(ISD::SMIN, MVT::v8i32, Legal);
1164 setOperationAction(ISD::UMIN, MVT::v32i8, Legal);
1165 setOperationAction(ISD::UMIN, MVT::v16i16, Legal);
1166 setOperationAction(ISD::UMIN, MVT::v8i32, Legal);
1168 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1169 // when we have a 256bit-wide blend with immediate.
1170 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1172 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1173 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1174 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1175 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1176 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1177 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1178 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1180 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1181 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1182 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1183 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1184 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1185 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1187 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1188 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1189 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1190 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1192 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1193 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1194 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1195 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1197 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1198 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1199 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1200 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1203 // In the customized shift lowering, the legal cases in AVX2 will be
1205 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1206 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1208 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1209 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1211 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1212 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1214 // Custom lower several nodes for 256-bit types.
1215 for (MVT VT : MVT::vector_valuetypes()) {
1216 if (VT.getScalarSizeInBits() >= 32) {
1217 setOperationAction(ISD::MLOAD, VT, Legal);
1218 setOperationAction(ISD::MSTORE, VT, Legal);
1220 // Extract subvector is special because the value type
1221 // (result) is 128-bit but the source is 256-bit wide.
1222 if (VT.is128BitVector()) {
1223 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1225 // Do not attempt to custom lower other non-256-bit vectors
1226 if (!VT.is256BitVector())
1229 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1230 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1231 setOperationAction(ISD::VSELECT, VT, Custom);
1232 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1233 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1234 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1235 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1236 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1239 if (Subtarget->hasInt256())
1240 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1243 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1244 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1245 MVT VT = (MVT::SimpleValueType)i;
1247 // Do not attempt to promote non-256-bit vectors
1248 if (!VT.is256BitVector())
1251 setOperationAction(ISD::AND, VT, Promote);
1252 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1253 setOperationAction(ISD::OR, VT, Promote);
1254 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1255 setOperationAction(ISD::XOR, VT, Promote);
1256 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1257 setOperationAction(ISD::LOAD, VT, Promote);
1258 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1259 setOperationAction(ISD::SELECT, VT, Promote);
1260 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1264 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1265 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1266 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1267 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1268 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1270 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1271 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1272 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1274 for (MVT VT : MVT::fp_vector_valuetypes())
1275 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1277 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1278 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1279 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1280 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1281 setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1282 setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1283 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1284 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1285 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1286 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1287 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1288 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1290 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1291 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1292 setOperationAction(ISD::XOR, MVT::i1, Legal);
1293 setOperationAction(ISD::OR, MVT::i1, Legal);
1294 setOperationAction(ISD::AND, MVT::i1, Legal);
1295 setOperationAction(ISD::SUB, MVT::i1, Custom);
1296 setOperationAction(ISD::ADD, MVT::i1, Custom);
1297 setOperationAction(ISD::MUL, MVT::i1, Custom);
1298 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1299 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1300 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1301 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1302 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1304 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1305 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1306 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1307 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1308 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1309 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1311 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1312 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1313 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1314 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1315 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1316 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1317 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1318 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1320 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1321 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1322 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1323 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1324 if (Subtarget->is64Bit()) {
1325 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1326 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1327 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1328 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1330 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1331 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1332 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1333 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1334 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1335 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1336 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1337 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1338 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1339 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1340 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1341 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1342 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1343 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1344 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1345 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1347 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1348 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1349 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1350 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1351 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1352 if (Subtarget->hasVLX()){
1353 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1354 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1355 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1356 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1357 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1359 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1360 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1361 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1362 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1363 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1365 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1366 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1367 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1368 if (Subtarget->hasDQI()) {
1369 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1370 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1372 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1373 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1374 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1375 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1376 if (Subtarget->hasVLX()) {
1377 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1378 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1379 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1380 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1381 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1382 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1383 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1384 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1387 if (Subtarget->hasVLX()) {
1388 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1389 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1390 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1391 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1392 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1393 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1394 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1395 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1397 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1398 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1399 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1400 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1401 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1402 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1403 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1404 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1405 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1406 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1407 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1408 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1409 if (Subtarget->hasDQI()) {
1410 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1411 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1413 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1414 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1415 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1416 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1417 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1418 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1419 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1420 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1421 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1422 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1424 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1425 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1426 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1427 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1428 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1430 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1431 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1433 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1435 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1436 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1437 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1438 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1439 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1440 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1441 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1442 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1443 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1444 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1445 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1447 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1448 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1449 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1450 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1451 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1452 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1453 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1454 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1456 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1457 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1459 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1460 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1462 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1464 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1465 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1467 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1468 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1470 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1471 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1473 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1474 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1475 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1476 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1477 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1478 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1480 if (Subtarget->hasCDI()) {
1481 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1482 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1484 if (Subtarget->hasDQI()) {
1485 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1486 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1487 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1489 // Custom lower several nodes.
1490 for (MVT VT : MVT::vector_valuetypes()) {
1491 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1493 setOperationAction(ISD::AND, VT, Legal);
1494 setOperationAction(ISD::OR, VT, Legal);
1495 setOperationAction(ISD::XOR, VT, Legal);
1497 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1498 setOperationAction(ISD::MGATHER, VT, Custom);
1499 setOperationAction(ISD::MSCATTER, VT, Custom);
1501 // Extract subvector is special because the value type
1502 // (result) is 256/128-bit but the source is 512-bit wide.
1503 if (VT.is128BitVector() || VT.is256BitVector()) {
1504 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1506 if (VT.getVectorElementType() == MVT::i1)
1507 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1509 // Do not attempt to custom lower other non-512-bit vectors
1510 if (!VT.is512BitVector())
1513 if (EltSize >= 32) {
1514 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1515 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1516 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1517 setOperationAction(ISD::VSELECT, VT, Legal);
1518 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1519 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1520 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1521 setOperationAction(ISD::MLOAD, VT, Legal);
1522 setOperationAction(ISD::MSTORE, VT, Legal);
1525 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1526 MVT VT = (MVT::SimpleValueType)i;
1528 // Do not attempt to promote non-512-bit vectors.
1529 if (!VT.is512BitVector())
1532 setOperationAction(ISD::SELECT, VT, Promote);
1533 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1537 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1538 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1539 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1541 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1542 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1544 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1545 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1546 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1547 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1548 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1549 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1550 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1551 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1552 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1553 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1554 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1555 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1556 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1557 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1558 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1559 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1560 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1561 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1562 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1563 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1564 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1565 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1566 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1567 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1568 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1569 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1570 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1571 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1572 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1573 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1575 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1576 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1577 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1578 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1579 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1580 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1581 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1582 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1584 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1585 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1586 if (Subtarget->hasVLX())
1587 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1589 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1590 const MVT VT = (MVT::SimpleValueType)i;
1592 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1594 // Do not attempt to promote non-512-bit vectors.
1595 if (!VT.is512BitVector())
1599 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1600 setOperationAction(ISD::VSELECT, VT, Legal);
1605 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1606 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1607 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1609 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1610 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1611 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1612 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1613 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1614 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1615 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1616 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1617 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1618 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1620 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1621 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1622 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1623 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1624 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1625 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1626 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1627 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1629 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1630 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1631 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1632 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1633 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1634 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1635 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1636 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1639 // We want to custom lower some of our intrinsics.
1640 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1641 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1642 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1643 if (!Subtarget->is64Bit())
1644 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1646 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1647 // handle type legalization for these operations here.
1649 // FIXME: We really should do custom legalization for addition and
1650 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1651 // than generic legalization for 64-bit multiplication-with-overflow, though.
1652 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1653 // Add/Sub/Mul with overflow operations are custom lowered.
1655 setOperationAction(ISD::SADDO, VT, Custom);
1656 setOperationAction(ISD::UADDO, VT, Custom);
1657 setOperationAction(ISD::SSUBO, VT, Custom);
1658 setOperationAction(ISD::USUBO, VT, Custom);
1659 setOperationAction(ISD::SMULO, VT, Custom);
1660 setOperationAction(ISD::UMULO, VT, Custom);
1664 if (!Subtarget->is64Bit()) {
1665 // These libcalls are not available in 32-bit.
1666 setLibcallName(RTLIB::SHL_I128, nullptr);
1667 setLibcallName(RTLIB::SRL_I128, nullptr);
1668 setLibcallName(RTLIB::SRA_I128, nullptr);
1671 // Combine sin / cos into one node or libcall if possible.
1672 if (Subtarget->hasSinCos()) {
1673 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1674 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1675 if (Subtarget->isTargetDarwin()) {
1676 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1677 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1678 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1679 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1683 if (Subtarget->isTargetWin64()) {
1684 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1685 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1686 setOperationAction(ISD::SREM, MVT::i128, Custom);
1687 setOperationAction(ISD::UREM, MVT::i128, Custom);
1688 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1689 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1692 // We have target-specific dag combine patterns for the following nodes:
1693 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1694 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1695 setTargetDAGCombine(ISD::BITCAST);
1696 setTargetDAGCombine(ISD::VSELECT);
1697 setTargetDAGCombine(ISD::SELECT);
1698 setTargetDAGCombine(ISD::SHL);
1699 setTargetDAGCombine(ISD::SRA);
1700 setTargetDAGCombine(ISD::SRL);
1701 setTargetDAGCombine(ISD::OR);
1702 setTargetDAGCombine(ISD::AND);
1703 setTargetDAGCombine(ISD::ADD);
1704 setTargetDAGCombine(ISD::FADD);
1705 setTargetDAGCombine(ISD::FSUB);
1706 setTargetDAGCombine(ISD::FMA);
1707 setTargetDAGCombine(ISD::SUB);
1708 setTargetDAGCombine(ISD::LOAD);
1709 setTargetDAGCombine(ISD::MLOAD);
1710 setTargetDAGCombine(ISD::STORE);
1711 setTargetDAGCombine(ISD::MSTORE);
1712 setTargetDAGCombine(ISD::ZERO_EXTEND);
1713 setTargetDAGCombine(ISD::ANY_EXTEND);
1714 setTargetDAGCombine(ISD::SIGN_EXTEND);
1715 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1716 setTargetDAGCombine(ISD::SINT_TO_FP);
1717 setTargetDAGCombine(ISD::UINT_TO_FP);
1718 setTargetDAGCombine(ISD::SETCC);
1719 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1720 setTargetDAGCombine(ISD::BUILD_VECTOR);
1721 setTargetDAGCombine(ISD::MUL);
1722 setTargetDAGCombine(ISD::XOR);
1724 computeRegisterProperties(Subtarget->getRegisterInfo());
1726 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1727 MaxStoresPerMemsetOptSize = 8;
1728 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1729 MaxStoresPerMemcpyOptSize = 4;
1730 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1731 MaxStoresPerMemmoveOptSize = 4;
1732 setPrefLoopAlignment(4); // 2^4 bytes.
1734 // Predictable cmov don't hurt on atom because it's in-order.
1735 PredictableSelectIsExpensive = !Subtarget->isAtom();
1736 EnableExtLdPromotion = true;
1737 setPrefFunctionAlignment(4); // 2^4 bytes.
1739 verifyIntrinsicTables();
1742 // This has so far only been implemented for 64-bit MachO.
1743 bool X86TargetLowering::useLoadStackGuardNode() const {
1744 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1747 TargetLoweringBase::LegalizeTypeAction
1748 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1749 if (ExperimentalVectorWideningLegalization &&
1750 VT.getVectorNumElements() != 1 &&
1751 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1752 return TypeWidenVector;
1754 return TargetLoweringBase::getPreferredVectorAction(VT);
1757 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1760 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1762 const unsigned NumElts = VT.getVectorNumElements();
1763 const EVT EltVT = VT.getVectorElementType();
1764 if (VT.is512BitVector()) {
1765 if (Subtarget->hasAVX512())
1766 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1767 EltVT == MVT::f32 || EltVT == MVT::f64)
1769 case 8: return MVT::v8i1;
1770 case 16: return MVT::v16i1;
1772 if (Subtarget->hasBWI())
1773 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1775 case 32: return MVT::v32i1;
1776 case 64: return MVT::v64i1;
1780 if (VT.is256BitVector() || VT.is128BitVector()) {
1781 if (Subtarget->hasVLX())
1782 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1783 EltVT == MVT::f32 || EltVT == MVT::f64)
1785 case 2: return MVT::v2i1;
1786 case 4: return MVT::v4i1;
1787 case 8: return MVT::v8i1;
1789 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1790 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1792 case 8: return MVT::v8i1;
1793 case 16: return MVT::v16i1;
1794 case 32: return MVT::v32i1;
1798 return VT.changeVectorElementTypeToInteger();
1801 /// Helper for getByValTypeAlignment to determine
1802 /// the desired ByVal argument alignment.
1803 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1806 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1807 if (VTy->getBitWidth() == 128)
1809 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1810 unsigned EltAlign = 0;
1811 getMaxByValAlign(ATy->getElementType(), EltAlign);
1812 if (EltAlign > MaxAlign)
1813 MaxAlign = EltAlign;
1814 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1815 for (auto *EltTy : STy->elements()) {
1816 unsigned EltAlign = 0;
1817 getMaxByValAlign(EltTy, EltAlign);
1818 if (EltAlign > MaxAlign)
1819 MaxAlign = EltAlign;
1826 /// Return the desired alignment for ByVal aggregate
1827 /// function arguments in the caller parameter area. For X86, aggregates
1828 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1829 /// are at 4-byte boundaries.
1830 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1831 const DataLayout &DL) const {
1832 if (Subtarget->is64Bit()) {
1833 // Max of 8 and alignment of type.
1834 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1841 if (Subtarget->hasSSE1())
1842 getMaxByValAlign(Ty, Align);
1846 /// Returns the target specific optimal type for load
1847 /// and store operations as a result of memset, memcpy, and memmove
1848 /// lowering. If DstAlign is zero that means it's safe to destination
1849 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1850 /// means there isn't a need to check it against alignment requirement,
1851 /// probably because the source does not need to be loaded. If 'IsMemset' is
1852 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1853 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1854 /// source is constant so it does not need to be loaded.
1855 /// It returns EVT::Other if the type should be determined using generic
1856 /// target-independent logic.
1858 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1859 unsigned DstAlign, unsigned SrcAlign,
1860 bool IsMemset, bool ZeroMemset,
1862 MachineFunction &MF) const {
1863 const Function *F = MF.getFunction();
1864 if ((!IsMemset || ZeroMemset) &&
1865 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1867 (Subtarget->isUnalignedMemAccessFast() ||
1868 ((DstAlign == 0 || DstAlign >= 16) &&
1869 (SrcAlign == 0 || SrcAlign >= 16)))) {
1871 if (Subtarget->hasInt256())
1873 if (Subtarget->hasFp256())
1876 if (Subtarget->hasSSE2())
1878 if (Subtarget->hasSSE1())
1880 } else if (!MemcpyStrSrc && Size >= 8 &&
1881 !Subtarget->is64Bit() &&
1882 Subtarget->hasSSE2()) {
1883 // Do not use f64 to lower memcpy if source is string constant. It's
1884 // better to use i32 to avoid the loads.
1888 if (Subtarget->is64Bit() && Size >= 8)
1893 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1895 return X86ScalarSSEf32;
1896 else if (VT == MVT::f64)
1897 return X86ScalarSSEf64;
1902 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1907 *Fast = Subtarget->isUnalignedMemAccessFast();
1911 /// Return the entry encoding for a jump table in the
1912 /// current function. The returned value is a member of the
1913 /// MachineJumpTableInfo::JTEntryKind enum.
1914 unsigned X86TargetLowering::getJumpTableEncoding() const {
1915 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1917 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1918 Subtarget->isPICStyleGOT())
1919 return MachineJumpTableInfo::EK_Custom32;
1921 // Otherwise, use the normal jump table encoding heuristics.
1922 return TargetLowering::getJumpTableEncoding();
1925 bool X86TargetLowering::useSoftFloat() const {
1926 return Subtarget->useSoftFloat();
1930 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1931 const MachineBasicBlock *MBB,
1932 unsigned uid,MCContext &Ctx) const{
1933 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1934 Subtarget->isPICStyleGOT());
1935 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1937 return MCSymbolRefExpr::create(MBB->getSymbol(),
1938 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1941 /// Returns relocation base for the given PIC jumptable.
1942 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1943 SelectionDAG &DAG) const {
1944 if (!Subtarget->is64Bit())
1945 // This doesn't have SDLoc associated with it, but is not really the
1946 // same as a Register.
1947 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1948 getPointerTy(DAG.getDataLayout()));
1952 /// This returns the relocation base for the given PIC jumptable,
1953 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1954 const MCExpr *X86TargetLowering::
1955 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1956 MCContext &Ctx) const {
1957 // X86-64 uses RIP relative addressing based on the jump table label.
1958 if (Subtarget->isPICStyleRIPRel())
1959 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1961 // Otherwise, the reference is relative to the PIC base.
1962 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1965 std::pair<const TargetRegisterClass *, uint8_t>
1966 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1968 const TargetRegisterClass *RRC = nullptr;
1970 switch (VT.SimpleTy) {
1972 return TargetLowering::findRepresentativeClass(TRI, VT);
1973 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1974 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1977 RRC = &X86::VR64RegClass;
1979 case MVT::f32: case MVT::f64:
1980 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1981 case MVT::v4f32: case MVT::v2f64:
1982 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1984 RRC = &X86::VR128RegClass;
1987 return std::make_pair(RRC, Cost);
1990 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1991 unsigned &Offset) const {
1992 if (!Subtarget->isTargetLinux())
1995 if (Subtarget->is64Bit()) {
1996 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1998 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2010 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2011 unsigned DestAS) const {
2012 assert(SrcAS != DestAS && "Expected different address spaces!");
2014 return SrcAS < 256 && DestAS < 256;
2017 //===----------------------------------------------------------------------===//
2018 // Return Value Calling Convention Implementation
2019 //===----------------------------------------------------------------------===//
2021 #include "X86GenCallingConv.inc"
2024 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2025 MachineFunction &MF, bool isVarArg,
2026 const SmallVectorImpl<ISD::OutputArg> &Outs,
2027 LLVMContext &Context) const {
2028 SmallVector<CCValAssign, 16> RVLocs;
2029 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2030 return CCInfo.CheckReturn(Outs, RetCC_X86);
2033 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2034 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2039 X86TargetLowering::LowerReturn(SDValue Chain,
2040 CallingConv::ID CallConv, bool isVarArg,
2041 const SmallVectorImpl<ISD::OutputArg> &Outs,
2042 const SmallVectorImpl<SDValue> &OutVals,
2043 SDLoc dl, SelectionDAG &DAG) const {
2044 MachineFunction &MF = DAG.getMachineFunction();
2045 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2047 SmallVector<CCValAssign, 16> RVLocs;
2048 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2049 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2052 SmallVector<SDValue, 6> RetOps;
2053 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2054 // Operand #1 = Bytes To Pop
2055 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2058 // Copy the result values into the output registers.
2059 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2060 CCValAssign &VA = RVLocs[i];
2061 assert(VA.isRegLoc() && "Can only return in registers!");
2062 SDValue ValToCopy = OutVals[i];
2063 EVT ValVT = ValToCopy.getValueType();
2065 // Promote values to the appropriate types.
2066 if (VA.getLocInfo() == CCValAssign::SExt)
2067 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2068 else if (VA.getLocInfo() == CCValAssign::ZExt)
2069 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2070 else if (VA.getLocInfo() == CCValAssign::AExt) {
2071 if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2072 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2074 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2076 else if (VA.getLocInfo() == CCValAssign::BCvt)
2077 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2079 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2080 "Unexpected FP-extend for return value.");
2082 // If this is x86-64, and we disabled SSE, we can't return FP values,
2083 // or SSE or MMX vectors.
2084 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2085 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2086 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2087 report_fatal_error("SSE register return with SSE disabled");
2089 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2090 // llvm-gcc has never done it right and no one has noticed, so this
2091 // should be OK for now.
2092 if (ValVT == MVT::f64 &&
2093 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2094 report_fatal_error("SSE2 register return with SSE2 disabled");
2096 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2097 // the RET instruction and handled by the FP Stackifier.
2098 if (VA.getLocReg() == X86::FP0 ||
2099 VA.getLocReg() == X86::FP1) {
2100 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2101 // change the value to the FP stack register class.
2102 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2103 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2104 RetOps.push_back(ValToCopy);
2105 // Don't emit a copytoreg.
2109 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2110 // which is returned in RAX / RDX.
2111 if (Subtarget->is64Bit()) {
2112 if (ValVT == MVT::x86mmx) {
2113 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2114 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2115 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2117 // If we don't have SSE2 available, convert to v4f32 so the generated
2118 // register is legal.
2119 if (!Subtarget->hasSSE2())
2120 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2125 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2126 Flag = Chain.getValue(1);
2127 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2130 // All x86 ABIs require that for returning structs by value we copy
2131 // the sret argument into %rax/%eax (depending on ABI) for the return.
2132 // We saved the argument into a virtual register in the entry block,
2133 // so now we copy the value out and into %rax/%eax.
2135 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2136 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2137 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2138 // either case FuncInfo->setSRetReturnReg() will have been called.
2139 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2140 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2141 getPointerTy(MF.getDataLayout()));
2144 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2145 X86::RAX : X86::EAX;
2146 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2147 Flag = Chain.getValue(1);
2149 // RAX/EAX now acts like a return value.
2151 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2154 RetOps[0] = Chain; // Update chain.
2156 // Add the flag if we have it.
2158 RetOps.push_back(Flag);
2160 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2163 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2164 if (N->getNumValues() != 1)
2166 if (!N->hasNUsesOfValue(1, 0))
2169 SDValue TCChain = Chain;
2170 SDNode *Copy = *N->use_begin();
2171 if (Copy->getOpcode() == ISD::CopyToReg) {
2172 // If the copy has a glue operand, we conservatively assume it isn't safe to
2173 // perform a tail call.
2174 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2176 TCChain = Copy->getOperand(0);
2177 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2180 bool HasRet = false;
2181 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2183 if (UI->getOpcode() != X86ISD::RET_FLAG)
2185 // If we are returning more than one value, we can definitely
2186 // not make a tail call see PR19530
2187 if (UI->getNumOperands() > 4)
2189 if (UI->getNumOperands() == 4 &&
2190 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2203 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2204 ISD::NodeType ExtendKind) const {
2206 // TODO: Is this also valid on 32-bit?
2207 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2208 ReturnMVT = MVT::i8;
2210 ReturnMVT = MVT::i32;
2212 EVT MinVT = getRegisterType(Context, ReturnMVT);
2213 return VT.bitsLT(MinVT) ? MinVT : VT;
2216 /// Lower the result values of a call into the
2217 /// appropriate copies out of appropriate physical registers.
2220 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2221 CallingConv::ID CallConv, bool isVarArg,
2222 const SmallVectorImpl<ISD::InputArg> &Ins,
2223 SDLoc dl, SelectionDAG &DAG,
2224 SmallVectorImpl<SDValue> &InVals) const {
2226 // Assign locations to each value returned by this call.
2227 SmallVector<CCValAssign, 16> RVLocs;
2228 bool Is64Bit = Subtarget->is64Bit();
2229 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2231 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2233 // Copy all of the result registers out of their specified physreg.
2234 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2235 CCValAssign &VA = RVLocs[i];
2236 EVT CopyVT = VA.getLocVT();
2238 // If this is x86-64, and we disabled SSE, we can't return FP values
2239 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2240 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2241 report_fatal_error("SSE register return with SSE disabled");
2244 // If we prefer to use the value in xmm registers, copy it out as f80 and
2245 // use a truncate to move it from fp stack reg to xmm reg.
2246 bool RoundAfterCopy = false;
2247 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2248 isScalarFPTypeInSSEReg(VA.getValVT())) {
2250 RoundAfterCopy = (CopyVT != VA.getLocVT());
2253 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2254 CopyVT, InFlag).getValue(1);
2255 SDValue Val = Chain.getValue(0);
2258 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2259 // This truncation won't change the value.
2260 DAG.getIntPtrConstant(1, dl));
2262 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2263 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2265 InFlag = Chain.getValue(2);
2266 InVals.push_back(Val);
2272 //===----------------------------------------------------------------------===//
2273 // C & StdCall & Fast Calling Convention implementation
2274 //===----------------------------------------------------------------------===//
2275 // StdCall calling convention seems to be standard for many Windows' API
2276 // routines and around. It differs from C calling convention just a little:
2277 // callee should clean up the stack, not caller. Symbols should be also
2278 // decorated in some fancy way :) It doesn't support any vector arguments.
2279 // For info on fast calling convention see Fast Calling Convention (tail call)
2280 // implementation LowerX86_32FastCCCallTo.
2282 /// CallIsStructReturn - Determines whether a call uses struct return
2284 enum StructReturnType {
2289 static StructReturnType
2290 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2292 return NotStructReturn;
2294 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2295 if (!Flags.isSRet())
2296 return NotStructReturn;
2297 if (Flags.isInReg())
2298 return RegStructReturn;
2299 return StackStructReturn;
2302 /// Determines whether a function uses struct return semantics.
2303 static StructReturnType
2304 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2306 return NotStructReturn;
2308 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2309 if (!Flags.isSRet())
2310 return NotStructReturn;
2311 if (Flags.isInReg())
2312 return RegStructReturn;
2313 return StackStructReturn;
2316 /// Make a copy of an aggregate at address specified by "Src" to address
2317 /// "Dst" with size and alignment information specified by the specific
2318 /// parameter attribute. The copy will be passed as a byval function parameter.
2320 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2321 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2323 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2325 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2326 /*isVolatile*/false, /*AlwaysInline=*/true,
2327 /*isTailCall*/false,
2328 MachinePointerInfo(), MachinePointerInfo());
2331 /// Return true if the calling convention is one that
2332 /// supports tail call optimization.
2333 static bool IsTailCallConvention(CallingConv::ID CC) {
2334 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2335 CC == CallingConv::HiPE);
2338 /// \brief Return true if the calling convention is a C calling convention.
2339 static bool IsCCallConvention(CallingConv::ID CC) {
2340 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2341 CC == CallingConv::X86_64_SysV);
2344 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2346 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2347 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2351 CallingConv::ID CalleeCC = CS.getCallingConv();
2352 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2358 /// Return true if the function is being made into
2359 /// a tailcall target by changing its ABI.
2360 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2361 bool GuaranteedTailCallOpt) {
2362 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2366 X86TargetLowering::LowerMemArgument(SDValue Chain,
2367 CallingConv::ID CallConv,
2368 const SmallVectorImpl<ISD::InputArg> &Ins,
2369 SDLoc dl, SelectionDAG &DAG,
2370 const CCValAssign &VA,
2371 MachineFrameInfo *MFI,
2373 // Create the nodes corresponding to a load from this parameter slot.
2374 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2375 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2376 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2377 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2380 // If value is passed by pointer we have address passed instead of the value
2382 bool ExtendedInMem = VA.isExtInLoc() &&
2383 VA.getValVT().getScalarType() == MVT::i1;
2385 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2386 ValVT = VA.getLocVT();
2388 ValVT = VA.getValVT();
2390 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2391 // changed with more analysis.
2392 // In case of tail call optimization mark all arguments mutable. Since they
2393 // could be overwritten by lowering of arguments in case of a tail call.
2394 if (Flags.isByVal()) {
2395 unsigned Bytes = Flags.getByValSize();
2396 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2397 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2398 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2400 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2401 VA.getLocMemOffset(), isImmutable);
2402 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2403 SDValue Val = DAG.getLoad(
2404 ValVT, dl, Chain, FIN,
2405 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2407 return ExtendedInMem ?
2408 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2412 // FIXME: Get this from tablegen.
2413 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2414 const X86Subtarget *Subtarget) {
2415 assert(Subtarget->is64Bit());
2417 if (Subtarget->isCallingConvWin64(CallConv)) {
2418 static const MCPhysReg GPR64ArgRegsWin64[] = {
2419 X86::RCX, X86::RDX, X86::R8, X86::R9
2421 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2424 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2425 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2427 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2430 // FIXME: Get this from tablegen.
2431 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2432 CallingConv::ID CallConv,
2433 const X86Subtarget *Subtarget) {
2434 assert(Subtarget->is64Bit());
2435 if (Subtarget->isCallingConvWin64(CallConv)) {
2436 // The XMM registers which might contain var arg parameters are shadowed
2437 // in their paired GPR. So we only need to save the GPR to their home
2439 // TODO: __vectorcall will change this.
2443 const Function *Fn = MF.getFunction();
2444 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2445 bool isSoftFloat = Subtarget->useSoftFloat();
2446 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2447 "SSE register cannot be used when SSE is disabled!");
2448 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2449 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2453 static const MCPhysReg XMMArgRegs64Bit[] = {
2454 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2455 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2457 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2461 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2462 CallingConv::ID CallConv,
2464 const SmallVectorImpl<ISD::InputArg> &Ins,
2467 SmallVectorImpl<SDValue> &InVals)
2469 MachineFunction &MF = DAG.getMachineFunction();
2470 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2471 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2473 const Function* Fn = MF.getFunction();
2474 if (Fn->hasExternalLinkage() &&
2475 Subtarget->isTargetCygMing() &&
2476 Fn->getName() == "main")
2477 FuncInfo->setForceFramePointer(true);
2479 MachineFrameInfo *MFI = MF.getFrameInfo();
2480 bool Is64Bit = Subtarget->is64Bit();
2481 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2483 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2484 "Var args not supported with calling convention fastcc, ghc or hipe");
2486 // Assign locations to all of the incoming arguments.
2487 SmallVector<CCValAssign, 16> ArgLocs;
2488 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2490 // Allocate shadow area for Win64
2492 CCInfo.AllocateStack(32, 8);
2494 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2496 unsigned LastVal = ~0U;
2498 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2499 CCValAssign &VA = ArgLocs[i];
2500 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2502 assert(VA.getValNo() != LastVal &&
2503 "Don't support value assigned to multiple locs yet");
2505 LastVal = VA.getValNo();
2507 if (VA.isRegLoc()) {
2508 EVT RegVT = VA.getLocVT();
2509 const TargetRegisterClass *RC;
2510 if (RegVT == MVT::i32)
2511 RC = &X86::GR32RegClass;
2512 else if (Is64Bit && RegVT == MVT::i64)
2513 RC = &X86::GR64RegClass;
2514 else if (RegVT == MVT::f32)
2515 RC = &X86::FR32RegClass;
2516 else if (RegVT == MVT::f64)
2517 RC = &X86::FR64RegClass;
2518 else if (RegVT.is512BitVector())
2519 RC = &X86::VR512RegClass;
2520 else if (RegVT.is256BitVector())
2521 RC = &X86::VR256RegClass;
2522 else if (RegVT.is128BitVector())
2523 RC = &X86::VR128RegClass;
2524 else if (RegVT == MVT::x86mmx)
2525 RC = &X86::VR64RegClass;
2526 else if (RegVT == MVT::i1)
2527 RC = &X86::VK1RegClass;
2528 else if (RegVT == MVT::v8i1)
2529 RC = &X86::VK8RegClass;
2530 else if (RegVT == MVT::v16i1)
2531 RC = &X86::VK16RegClass;
2532 else if (RegVT == MVT::v32i1)
2533 RC = &X86::VK32RegClass;
2534 else if (RegVT == MVT::v64i1)
2535 RC = &X86::VK64RegClass;
2537 llvm_unreachable("Unknown argument type!");
2539 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2540 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2542 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2543 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2545 if (VA.getLocInfo() == CCValAssign::SExt)
2546 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2547 DAG.getValueType(VA.getValVT()));
2548 else if (VA.getLocInfo() == CCValAssign::ZExt)
2549 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2550 DAG.getValueType(VA.getValVT()));
2551 else if (VA.getLocInfo() == CCValAssign::BCvt)
2552 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2554 if (VA.isExtInLoc()) {
2555 // Handle MMX values passed in XMM regs.
2556 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2557 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2559 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2562 assert(VA.isMemLoc());
2563 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2566 // If value is passed via pointer - do a load.
2567 if (VA.getLocInfo() == CCValAssign::Indirect)
2568 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2569 MachinePointerInfo(), false, false, false, 0);
2571 InVals.push_back(ArgValue);
2574 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2575 // All x86 ABIs require that for returning structs by value we copy the
2576 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2577 // the argument into a virtual register so that we can access it from the
2579 if (Ins[i].Flags.isSRet()) {
2580 unsigned Reg = FuncInfo->getSRetReturnReg();
2582 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2583 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2584 FuncInfo->setSRetReturnReg(Reg);
2586 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2587 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2592 unsigned StackSize = CCInfo.getNextStackOffset();
2593 // Align stack specially for tail calls.
2594 if (FuncIsMadeTailCallSafe(CallConv,
2595 MF.getTarget().Options.GuaranteedTailCallOpt))
2596 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2598 // If the function takes variable number of arguments, make a frame index for
2599 // the start of the first vararg value... for expansion of llvm.va_start. We
2600 // can skip this if there are no va_start calls.
2601 if (MFI->hasVAStart() &&
2602 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2603 CallConv != CallingConv::X86_ThisCall))) {
2604 FuncInfo->setVarArgsFrameIndex(
2605 MFI->CreateFixedObject(1, StackSize, true));
2608 MachineModuleInfo &MMI = MF.getMMI();
2609 const Function *WinEHParent = nullptr;
2610 if (MMI.hasWinEHFuncInfo(Fn))
2611 WinEHParent = MMI.getWinEHParent(Fn);
2612 bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2613 bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2615 // Figure out if XMM registers are in use.
2616 assert(!(Subtarget->useSoftFloat() &&
2617 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2618 "SSE register cannot be used when SSE is disabled!");
2620 // 64-bit calling conventions support varargs and register parameters, so we
2621 // have to do extra work to spill them in the prologue.
2622 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2623 // Find the first unallocated argument registers.
2624 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2625 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2626 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2627 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2628 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2629 "SSE register cannot be used when SSE is disabled!");
2631 // Gather all the live in physical registers.
2632 SmallVector<SDValue, 6> LiveGPRs;
2633 SmallVector<SDValue, 8> LiveXMMRegs;
2635 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2636 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2638 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2640 if (!ArgXMMs.empty()) {
2641 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2642 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2643 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2644 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2645 LiveXMMRegs.push_back(
2646 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2651 // Get to the caller-allocated home save location. Add 8 to account
2652 // for the return address.
2653 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2654 FuncInfo->setRegSaveFrameIndex(
2655 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2656 // Fixup to set vararg frame on shadow area (4 x i64).
2658 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2660 // For X86-64, if there are vararg parameters that are passed via
2661 // registers, then we must store them to their spots on the stack so
2662 // they may be loaded by deferencing the result of va_next.
2663 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2664 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2665 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2666 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2669 // Store the integer parameter registers.
2670 SmallVector<SDValue, 8> MemOps;
2671 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2672 getPointerTy(DAG.getDataLayout()));
2673 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2674 for (SDValue Val : LiveGPRs) {
2675 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2676 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2678 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2679 MachinePointerInfo::getFixedStack(
2680 DAG.getMachineFunction(),
2681 FuncInfo->getRegSaveFrameIndex(), Offset),
2683 MemOps.push_back(Store);
2687 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2688 // Now store the XMM (fp + vector) parameter registers.
2689 SmallVector<SDValue, 12> SaveXMMOps;
2690 SaveXMMOps.push_back(Chain);
2691 SaveXMMOps.push_back(ALVal);
2692 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2693 FuncInfo->getRegSaveFrameIndex(), dl));
2694 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2695 FuncInfo->getVarArgsFPOffset(), dl));
2696 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2698 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2699 MVT::Other, SaveXMMOps));
2702 if (!MemOps.empty())
2703 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2704 } else if (IsWin64 && IsWinEHOutlined) {
2705 // Get to the caller-allocated home save location. Add 8 to account
2706 // for the return address.
2707 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2708 FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2709 /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2711 MMI.getWinEHFuncInfo(Fn)
2712 .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2713 FuncInfo->getRegSaveFrameIndex();
2715 // Store the second integer parameter (rdx) into rsp+16 relative to the
2716 // stack pointer at the entry of the function.
2717 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2718 getPointerTy(DAG.getDataLayout()));
2719 unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2720 SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2721 Chain = DAG.getStore(
2722 Val.getValue(1), dl, Val, RSFIN,
2723 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2724 FuncInfo->getRegSaveFrameIndex()),
2725 /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2728 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2729 // Find the largest legal vector type.
2730 MVT VecVT = MVT::Other;
2731 // FIXME: Only some x86_32 calling conventions support AVX512.
2732 if (Subtarget->hasAVX512() &&
2733 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2734 CallConv == CallingConv::Intel_OCL_BI)))
2735 VecVT = MVT::v16f32;
2736 else if (Subtarget->hasAVX())
2738 else if (Subtarget->hasSSE2())
2741 // We forward some GPRs and some vector types.
2742 SmallVector<MVT, 2> RegParmTypes;
2743 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2744 RegParmTypes.push_back(IntVT);
2745 if (VecVT != MVT::Other)
2746 RegParmTypes.push_back(VecVT);
2748 // Compute the set of forwarded registers. The rest are scratch.
2749 SmallVectorImpl<ForwardedRegister> &Forwards =
2750 FuncInfo->getForwardedMustTailRegParms();
2751 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2753 // Conservatively forward AL on x86_64, since it might be used for varargs.
2754 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2755 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2756 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2759 // Copy all forwards from physical to virtual registers.
2760 for (ForwardedRegister &F : Forwards) {
2761 // FIXME: Can we use a less constrained schedule?
2762 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2763 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2764 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2768 // Some CCs need callee pop.
2769 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2770 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2771 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2773 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2774 // If this is an sret function, the return should pop the hidden pointer.
2775 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2776 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2777 argsAreStructReturn(Ins) == StackStructReturn)
2778 FuncInfo->setBytesToPopOnReturn(4);
2782 // RegSaveFrameIndex is X86-64 only.
2783 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2784 if (CallConv == CallingConv::X86_FastCall ||
2785 CallConv == CallingConv::X86_ThisCall)
2786 // fastcc functions can't have varargs.
2787 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2790 FuncInfo->setArgumentStackSize(StackSize);
2792 if (IsWinEHParent) {
2794 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2795 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2796 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2797 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2798 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2799 MachinePointerInfo::getFixedStack(
2800 DAG.getMachineFunction(), UnwindHelpFI),
2801 /*isVolatile=*/true,
2802 /*isNonTemporal=*/false, /*Alignment=*/0);
2804 // Functions using Win32 EH are considered to have opaque SP adjustments
2805 // to force local variables to be addressed from the frame or base
2807 MFI->setHasOpaqueSPAdjustment(true);
2815 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2816 SDValue StackPtr, SDValue Arg,
2817 SDLoc dl, SelectionDAG &DAG,
2818 const CCValAssign &VA,
2819 ISD::ArgFlagsTy Flags) const {
2820 unsigned LocMemOffset = VA.getLocMemOffset();
2821 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2822 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2824 if (Flags.isByVal())
2825 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2827 return DAG.getStore(
2828 Chain, dl, Arg, PtrOff,
2829 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2833 /// Emit a load of return address if tail call
2834 /// optimization is performed and it is required.
2836 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2837 SDValue &OutRetAddr, SDValue Chain,
2838 bool IsTailCall, bool Is64Bit,
2839 int FPDiff, SDLoc dl) const {
2840 // Adjust the Return address stack slot.
2841 EVT VT = getPointerTy(DAG.getDataLayout());
2842 OutRetAddr = getReturnAddressFrameIndex(DAG);
2844 // Load the "old" Return address.
2845 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2846 false, false, false, 0);
2847 return SDValue(OutRetAddr.getNode(), 1);
2850 /// Emit a store of the return address if tail call
2851 /// optimization is performed and it is required (FPDiff!=0).
2852 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2853 SDValue Chain, SDValue RetAddrFrIdx,
2854 EVT PtrVT, unsigned SlotSize,
2855 int FPDiff, SDLoc dl) {
2856 // Store the return address to the appropriate stack slot.
2857 if (!FPDiff) return Chain;
2858 // Calculate the new stack slot for the return address.
2859 int NewReturnAddrFI =
2860 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2862 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2863 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2864 MachinePointerInfo::getFixedStack(
2865 DAG.getMachineFunction(), NewReturnAddrFI),
2870 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2871 /// operation of specified width.
2872 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2874 unsigned NumElems = VT.getVectorNumElements();
2875 SmallVector<int, 8> Mask;
2876 Mask.push_back(NumElems);
2877 for (unsigned i = 1; i != NumElems; ++i)
2879 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2883 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2884 SmallVectorImpl<SDValue> &InVals) const {
2885 SelectionDAG &DAG = CLI.DAG;
2887 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2888 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2889 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2890 SDValue Chain = CLI.Chain;
2891 SDValue Callee = CLI.Callee;
2892 CallingConv::ID CallConv = CLI.CallConv;
2893 bool &isTailCall = CLI.IsTailCall;
2894 bool isVarArg = CLI.IsVarArg;
2896 MachineFunction &MF = DAG.getMachineFunction();
2897 bool Is64Bit = Subtarget->is64Bit();
2898 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2899 StructReturnType SR = callIsStructReturn(Outs);
2900 bool IsSibcall = false;
2901 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2902 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2904 if (Attr.getValueAsString() == "true")
2907 if (Subtarget->isPICStyleGOT() &&
2908 !MF.getTarget().Options.GuaranteedTailCallOpt) {
2909 // If we are using a GOT, disable tail calls to external symbols with
2910 // default visibility. Tail calling such a symbol requires using a GOT
2911 // relocation, which forces early binding of the symbol. This breaks code
2912 // that require lazy function symbol resolution. Using musttail or
2913 // GuaranteedTailCallOpt will override this.
2914 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2915 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2916 G->getGlobal()->hasDefaultVisibility()))
2920 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2922 // Force this to be a tail call. The verifier rules are enough to ensure
2923 // that we can lower this successfully without moving the return address
2926 } else if (isTailCall) {
2927 // Check if it's really possible to do a tail call.
2928 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2929 isVarArg, SR != NotStructReturn,
2930 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2931 Outs, OutVals, Ins, DAG);
2933 // Sibcalls are automatically detected tailcalls which do not require
2935 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2942 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2943 "Var args not supported with calling convention fastcc, ghc or hipe");
2945 // Analyze operands of the call, assigning locations to each operand.
2946 SmallVector<CCValAssign, 16> ArgLocs;
2947 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2949 // Allocate shadow area for Win64
2951 CCInfo.AllocateStack(32, 8);
2953 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2955 // Get a count of how many bytes are to be pushed on the stack.
2956 unsigned NumBytes = CCInfo.getNextStackOffset();
2958 // This is a sibcall. The memory operands are available in caller's
2959 // own caller's stack.
2961 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2962 IsTailCallConvention(CallConv))
2963 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2966 if (isTailCall && !IsSibcall && !IsMustTail) {
2967 // Lower arguments at fp - stackoffset + fpdiff.
2968 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2970 FPDiff = NumBytesCallerPushed - NumBytes;
2972 // Set the delta of movement of the returnaddr stackslot.
2973 // But only set if delta is greater than previous delta.
2974 if (FPDiff < X86Info->getTCReturnAddrDelta())
2975 X86Info->setTCReturnAddrDelta(FPDiff);
2978 unsigned NumBytesToPush = NumBytes;
2979 unsigned NumBytesToPop = NumBytes;
2981 // If we have an inalloca argument, all stack space has already been allocated
2982 // for us and be right at the top of the stack. We don't support multiple
2983 // arguments passed in memory when using inalloca.
2984 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2986 if (!ArgLocs.back().isMemLoc())
2987 report_fatal_error("cannot use inalloca attribute on a register "
2989 if (ArgLocs.back().getLocMemOffset() != 0)
2990 report_fatal_error("any parameter with the inalloca attribute must be "
2991 "the only memory argument");
2995 Chain = DAG.getCALLSEQ_START(
2996 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2998 SDValue RetAddrFrIdx;
2999 // Load return address for tail calls.
3000 if (isTailCall && FPDiff)
3001 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3002 Is64Bit, FPDiff, dl);
3004 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3005 SmallVector<SDValue, 8> MemOpChains;
3008 // Walk the register/memloc assignments, inserting copies/loads. In the case
3009 // of tail call optimization arguments are handle later.
3010 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3011 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3012 // Skip inalloca arguments, they have already been written.
3013 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3014 if (Flags.isInAlloca())
3017 CCValAssign &VA = ArgLocs[i];
3018 EVT RegVT = VA.getLocVT();
3019 SDValue Arg = OutVals[i];
3020 bool isByVal = Flags.isByVal();
3022 // Promote the value if needed.
3023 switch (VA.getLocInfo()) {
3024 default: llvm_unreachable("Unknown loc info!");
3025 case CCValAssign::Full: break;
3026 case CCValAssign::SExt:
3027 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3029 case CCValAssign::ZExt:
3030 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3032 case CCValAssign::AExt:
3033 if (Arg.getValueType().isVector() &&
3034 Arg.getValueType().getScalarType() == MVT::i1)
3035 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3036 else if (RegVT.is128BitVector()) {
3037 // Special case: passing MMX values in XMM registers.
3038 Arg = DAG.getBitcast(MVT::i64, Arg);
3039 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3040 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3042 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3044 case CCValAssign::BCvt:
3045 Arg = DAG.getBitcast(RegVT, Arg);
3047 case CCValAssign::Indirect: {
3048 // Store the argument.
3049 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3050 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3051 Chain = DAG.getStore(
3052 Chain, dl, Arg, SpillSlot,
3053 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3060 if (VA.isRegLoc()) {
3061 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3062 if (isVarArg && IsWin64) {
3063 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3064 // shadow reg if callee is a varargs function.
3065 unsigned ShadowReg = 0;
3066 switch (VA.getLocReg()) {
3067 case X86::XMM0: ShadowReg = X86::RCX; break;
3068 case X86::XMM1: ShadowReg = X86::RDX; break;
3069 case X86::XMM2: ShadowReg = X86::R8; break;
3070 case X86::XMM3: ShadowReg = X86::R9; break;
3073 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3075 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3076 assert(VA.isMemLoc());
3077 if (!StackPtr.getNode())
3078 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3079 getPointerTy(DAG.getDataLayout()));
3080 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3081 dl, DAG, VA, Flags));
3085 if (!MemOpChains.empty())
3086 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3088 if (Subtarget->isPICStyleGOT()) {
3089 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3092 RegsToPass.push_back(std::make_pair(
3093 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3094 getPointerTy(DAG.getDataLayout()))));
3096 // If we are tail calling and generating PIC/GOT style code load the
3097 // address of the callee into ECX. The value in ecx is used as target of
3098 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3099 // for tail calls on PIC/GOT architectures. Normally we would just put the
3100 // address of GOT into ebx and then call target@PLT. But for tail calls
3101 // ebx would be restored (since ebx is callee saved) before jumping to the
3104 // Note: The actual moving to ECX is done further down.
3105 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3106 if (G && !G->getGlobal()->hasLocalLinkage() &&
3107 G->getGlobal()->hasDefaultVisibility())
3108 Callee = LowerGlobalAddress(Callee, DAG);
3109 else if (isa<ExternalSymbolSDNode>(Callee))
3110 Callee = LowerExternalSymbol(Callee, DAG);
3114 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3115 // From AMD64 ABI document:
3116 // For calls that may call functions that use varargs or stdargs
3117 // (prototype-less calls or calls to functions containing ellipsis (...) in
3118 // the declaration) %al is used as hidden argument to specify the number
3119 // of SSE registers used. The contents of %al do not need to match exactly
3120 // the number of registers, but must be an ubound on the number of SSE
3121 // registers used and is in the range 0 - 8 inclusive.
3123 // Count the number of XMM registers allocated.
3124 static const MCPhysReg XMMArgRegs[] = {
3125 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3126 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3128 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3129 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3130 && "SSE registers cannot be used when SSE is disabled");
3132 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3133 DAG.getConstant(NumXMMRegs, dl,
3137 if (isVarArg && IsMustTail) {
3138 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3139 for (const auto &F : Forwards) {
3140 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3141 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3145 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3146 // don't need this because the eligibility check rejects calls that require
3147 // shuffling arguments passed in memory.
3148 if (!IsSibcall && isTailCall) {
3149 // Force all the incoming stack arguments to be loaded from the stack
3150 // before any new outgoing arguments are stored to the stack, because the
3151 // outgoing stack slots may alias the incoming argument stack slots, and
3152 // the alias isn't otherwise explicit. This is slightly more conservative
3153 // than necessary, because it means that each store effectively depends
3154 // on every argument instead of just those arguments it would clobber.
3155 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3157 SmallVector<SDValue, 8> MemOpChains2;
3160 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3161 CCValAssign &VA = ArgLocs[i];
3164 assert(VA.isMemLoc());
3165 SDValue Arg = OutVals[i];
3166 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3167 // Skip inalloca arguments. They don't require any work.
3168 if (Flags.isInAlloca())
3170 // Create frame index.
3171 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3172 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3173 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3174 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3176 if (Flags.isByVal()) {
3177 // Copy relative to framepointer.
3178 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3179 if (!StackPtr.getNode())
3180 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3181 getPointerTy(DAG.getDataLayout()));
3182 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3185 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3189 // Store relative to framepointer.
3190 MemOpChains2.push_back(DAG.getStore(
3191 ArgChain, dl, Arg, FIN,
3192 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3197 if (!MemOpChains2.empty())
3198 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3200 // Store the return address to the appropriate stack slot.
3201 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3202 getPointerTy(DAG.getDataLayout()),
3203 RegInfo->getSlotSize(), FPDiff, dl);
3206 // Build a sequence of copy-to-reg nodes chained together with token chain
3207 // and flag operands which copy the outgoing args into registers.
3209 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3210 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3211 RegsToPass[i].second, InFlag);
3212 InFlag = Chain.getValue(1);
3215 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3216 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3217 // In the 64-bit large code model, we have to make all calls
3218 // through a register, since the call instruction's 32-bit
3219 // pc-relative offset may not be large enough to hold the whole
3221 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3222 // If the callee is a GlobalAddress node (quite common, every direct call
3223 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3225 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3227 // We should use extra load for direct calls to dllimported functions in
3229 const GlobalValue *GV = G->getGlobal();
3230 if (!GV->hasDLLImportStorageClass()) {
3231 unsigned char OpFlags = 0;
3232 bool ExtraLoad = false;
3233 unsigned WrapperKind = ISD::DELETED_NODE;
3235 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3236 // external symbols most go through the PLT in PIC mode. If the symbol
3237 // has hidden or protected visibility, or if it is static or local, then
3238 // we don't need to use the PLT - we can directly call it.
3239 if (Subtarget->isTargetELF() &&
3240 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3241 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3242 OpFlags = X86II::MO_PLT;
3243 } else if (Subtarget->isPICStyleStubAny() &&
3244 !GV->isStrongDefinitionForLinker() &&
3245 (!Subtarget->getTargetTriple().isMacOSX() ||
3246 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3247 // PC-relative references to external symbols should go through $stub,
3248 // unless we're building with the leopard linker or later, which
3249 // automatically synthesizes these stubs.
3250 OpFlags = X86II::MO_DARWIN_STUB;
3251 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3252 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3253 // If the function is marked as non-lazy, generate an indirect call
3254 // which loads from the GOT directly. This avoids runtime overhead
3255 // at the cost of eager binding (and one extra byte of encoding).
3256 OpFlags = X86II::MO_GOTPCREL;
3257 WrapperKind = X86ISD::WrapperRIP;
3261 Callee = DAG.getTargetGlobalAddress(
3262 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3264 // Add a wrapper if needed.
3265 if (WrapperKind != ISD::DELETED_NODE)
3266 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3267 getPointerTy(DAG.getDataLayout()), Callee);
3268 // Add extra indirection if needed.
3270 Callee = DAG.getLoad(
3271 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3272 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3275 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3276 unsigned char OpFlags = 0;
3278 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3279 // external symbols should go through the PLT.
3280 if (Subtarget->isTargetELF() &&
3281 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3282 OpFlags = X86II::MO_PLT;
3283 } else if (Subtarget->isPICStyleStubAny() &&
3284 (!Subtarget->getTargetTriple().isMacOSX() ||
3285 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3286 // PC-relative references to external symbols should go through $stub,
3287 // unless we're building with the leopard linker or later, which
3288 // automatically synthesizes these stubs.
3289 OpFlags = X86II::MO_DARWIN_STUB;
3292 Callee = DAG.getTargetExternalSymbol(
3293 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3294 } else if (Subtarget->isTarget64BitILP32() &&
3295 Callee->getValueType(0) == MVT::i32) {
3296 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3297 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3300 // Returns a chain & a flag for retval copy to use.
3301 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3302 SmallVector<SDValue, 8> Ops;
3304 if (!IsSibcall && isTailCall) {
3305 Chain = DAG.getCALLSEQ_END(Chain,
3306 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3307 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3308 InFlag = Chain.getValue(1);
3311 Ops.push_back(Chain);
3312 Ops.push_back(Callee);
3315 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3317 // Add argument registers to the end of the list so that they are known live
3319 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3320 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3321 RegsToPass[i].second.getValueType()));
3323 // Add a register mask operand representing the call-preserved registers.
3324 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3325 assert(Mask && "Missing call preserved mask for calling convention");
3327 // If this is an invoke in a 32-bit function using an MSVC personality, assume
3328 // the function clobbers all registers. If an exception is thrown, the runtime
3329 // will not restore CSRs.
3330 // FIXME: Model this more precisely so that we can register allocate across
3331 // the normal edge and spill and fill across the exceptional edge.
3332 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3333 const Function *CallerFn = MF.getFunction();
3334 EHPersonality Pers =
3335 CallerFn->hasPersonalityFn()
3336 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3337 : EHPersonality::Unknown;
3338 if (isMSVCEHPersonality(Pers))
3339 Mask = RegInfo->getNoPreservedMask();
3342 Ops.push_back(DAG.getRegisterMask(Mask));
3344 if (InFlag.getNode())
3345 Ops.push_back(InFlag);
3349 //// If this is the first return lowered for this function, add the regs
3350 //// to the liveout set for the function.
3351 // This isn't right, although it's probably harmless on x86; liveouts
3352 // should be computed from returns not tail calls. Consider a void
3353 // function making a tail call to a function returning int.
3354 MF.getFrameInfo()->setHasTailCall();
3355 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3358 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3359 InFlag = Chain.getValue(1);
3361 // Create the CALLSEQ_END node.
3362 unsigned NumBytesForCalleeToPop;
3363 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3364 DAG.getTarget().Options.GuaranteedTailCallOpt))
3365 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3366 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3367 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3368 SR == StackStructReturn)
3369 // If this is a call to a struct-return function, the callee
3370 // pops the hidden struct pointer, so we have to push it back.
3371 // This is common for Darwin/X86, Linux & Mingw32 targets.
3372 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3373 NumBytesForCalleeToPop = 4;
3375 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3377 // Returns a flag for retval copy to use.
3379 Chain = DAG.getCALLSEQ_END(Chain,
3380 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3381 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3384 InFlag = Chain.getValue(1);
3387 // Handle result values, copying them out of physregs into vregs that we
3389 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3390 Ins, dl, DAG, InVals);
3393 //===----------------------------------------------------------------------===//
3394 // Fast Calling Convention (tail call) implementation
3395 //===----------------------------------------------------------------------===//
3397 // Like std call, callee cleans arguments, convention except that ECX is
3398 // reserved for storing the tail called function address. Only 2 registers are
3399 // free for argument passing (inreg). Tail call optimization is performed
3401 // * tailcallopt is enabled
3402 // * caller/callee are fastcc
3403 // On X86_64 architecture with GOT-style position independent code only local
3404 // (within module) calls are supported at the moment.
3405 // To keep the stack aligned according to platform abi the function
3406 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3407 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3408 // If a tail called function callee has more arguments than the caller the
3409 // caller needs to make sure that there is room to move the RETADDR to. This is
3410 // achieved by reserving an area the size of the argument delta right after the
3411 // original RETADDR, but before the saved framepointer or the spilled registers
3412 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3424 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3427 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3428 SelectionDAG& DAG) const {
3429 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3430 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3431 unsigned StackAlignment = TFI.getStackAlignment();
3432 uint64_t AlignMask = StackAlignment - 1;
3433 int64_t Offset = StackSize;
3434 unsigned SlotSize = RegInfo->getSlotSize();
3435 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3436 // Number smaller than 12 so just add the difference.
3437 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3439 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3440 Offset = ((~AlignMask) & Offset) + StackAlignment +
3441 (StackAlignment-SlotSize);
3446 /// Return true if the given stack call argument is already available in the
3447 /// same position (relatively) of the caller's incoming argument stack.
3449 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3450 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3451 const X86InstrInfo *TII) {
3452 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3454 if (Arg.getOpcode() == ISD::CopyFromReg) {
3455 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3456 if (!TargetRegisterInfo::isVirtualRegister(VR))
3458 MachineInstr *Def = MRI->getVRegDef(VR);
3461 if (!Flags.isByVal()) {
3462 if (!TII->isLoadFromStackSlot(Def, FI))
3465 unsigned Opcode = Def->getOpcode();
3466 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3467 Opcode == X86::LEA64_32r) &&
3468 Def->getOperand(1).isFI()) {
3469 FI = Def->getOperand(1).getIndex();
3470 Bytes = Flags.getByValSize();
3474 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3475 if (Flags.isByVal())
3476 // ByVal argument is passed in as a pointer but it's now being
3477 // dereferenced. e.g.
3478 // define @foo(%struct.X* %A) {
3479 // tail call @bar(%struct.X* byval %A)
3482 SDValue Ptr = Ld->getBasePtr();
3483 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3486 FI = FINode->getIndex();
3487 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3488 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3489 FI = FINode->getIndex();
3490 Bytes = Flags.getByValSize();
3494 assert(FI != INT_MAX);
3495 if (!MFI->isFixedObjectIndex(FI))
3497 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3500 /// Check whether the call is eligible for tail call optimization. Targets
3501 /// that want to do tail call optimization should implement this function.
3503 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3504 CallingConv::ID CalleeCC,
3506 bool isCalleeStructRet,
3507 bool isCallerStructRet,
3509 const SmallVectorImpl<ISD::OutputArg> &Outs,
3510 const SmallVectorImpl<SDValue> &OutVals,
3511 const SmallVectorImpl<ISD::InputArg> &Ins,
3512 SelectionDAG &DAG) const {
3513 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3516 // If -tailcallopt is specified, make fastcc functions tail-callable.
3517 const MachineFunction &MF = DAG.getMachineFunction();
3518 const Function *CallerF = MF.getFunction();
3520 // If the function return type is x86_fp80 and the callee return type is not,
3521 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3522 // perform a tailcall optimization here.
3523 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3526 CallingConv::ID CallerCC = CallerF->getCallingConv();
3527 bool CCMatch = CallerCC == CalleeCC;
3528 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3529 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3531 // Win64 functions have extra shadow space for argument homing. Don't do the
3532 // sibcall if the caller and callee have mismatched expectations for this
3534 if (IsCalleeWin64 != IsCallerWin64)
3537 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3538 if (IsTailCallConvention(CalleeCC) && CCMatch)
3543 // Look for obvious safe cases to perform tail call optimization that do not
3544 // require ABI changes. This is what gcc calls sibcall.
3546 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3547 // emit a special epilogue.
3548 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3549 if (RegInfo->needsStackRealignment(MF))
3552 // Also avoid sibcall optimization if either caller or callee uses struct
3553 // return semantics.
3554 if (isCalleeStructRet || isCallerStructRet)
3557 // An stdcall/thiscall caller is expected to clean up its arguments; the
3558 // callee isn't going to do that.
3559 // FIXME: this is more restrictive than needed. We could produce a tailcall
3560 // when the stack adjustment matches. For example, with a thiscall that takes
3561 // only one argument.
3562 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3563 CallerCC == CallingConv::X86_ThisCall))
3566 // Do not sibcall optimize vararg calls unless all arguments are passed via
3568 if (isVarArg && !Outs.empty()) {
3570 // Optimizing for varargs on Win64 is unlikely to be safe without
3571 // additional testing.
3572 if (IsCalleeWin64 || IsCallerWin64)
3575 SmallVector<CCValAssign, 16> ArgLocs;
3576 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3579 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3580 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3581 if (!ArgLocs[i].isRegLoc())
3585 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3586 // stack. Therefore, if it's not used by the call it is not safe to optimize
3587 // this into a sibcall.
3588 bool Unused = false;
3589 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3596 SmallVector<CCValAssign, 16> RVLocs;
3597 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3599 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3600 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3601 CCValAssign &VA = RVLocs[i];
3602 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3607 // If the calling conventions do not match, then we'd better make sure the
3608 // results are returned in the same way as what the caller expects.
3610 SmallVector<CCValAssign, 16> RVLocs1;
3611 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3613 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3615 SmallVector<CCValAssign, 16> RVLocs2;
3616 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3618 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3620 if (RVLocs1.size() != RVLocs2.size())
3622 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3623 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3625 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3627 if (RVLocs1[i].isRegLoc()) {
3628 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3631 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3637 // If the callee takes no arguments then go on to check the results of the
3639 if (!Outs.empty()) {
3640 // Check if stack adjustment is needed. For now, do not do this if any
3641 // argument is passed on the stack.
3642 SmallVector<CCValAssign, 16> ArgLocs;
3643 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3646 // Allocate shadow area for Win64
3648 CCInfo.AllocateStack(32, 8);
3650 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3651 if (CCInfo.getNextStackOffset()) {
3652 MachineFunction &MF = DAG.getMachineFunction();
3653 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3656 // Check if the arguments are already laid out in the right way as
3657 // the caller's fixed stack objects.
3658 MachineFrameInfo *MFI = MF.getFrameInfo();
3659 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3660 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3661 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3662 CCValAssign &VA = ArgLocs[i];
3663 SDValue Arg = OutVals[i];
3664 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3665 if (VA.getLocInfo() == CCValAssign::Indirect)
3667 if (!VA.isRegLoc()) {
3668 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3675 // If the tailcall address may be in a register, then make sure it's
3676 // possible to register allocate for it. In 32-bit, the call address can
3677 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3678 // callee-saved registers are restored. These happen to be the same
3679 // registers used to pass 'inreg' arguments so watch out for those.
3680 if (!Subtarget->is64Bit() &&
3681 ((!isa<GlobalAddressSDNode>(Callee) &&
3682 !isa<ExternalSymbolSDNode>(Callee)) ||
3683 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3684 unsigned NumInRegs = 0;
3685 // In PIC we need an extra register to formulate the address computation
3687 unsigned MaxInRegs =
3688 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3690 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3691 CCValAssign &VA = ArgLocs[i];
3694 unsigned Reg = VA.getLocReg();
3697 case X86::EAX: case X86::EDX: case X86::ECX:
3698 if (++NumInRegs == MaxInRegs)
3710 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3711 const TargetLibraryInfo *libInfo) const {
3712 return X86::createFastISel(funcInfo, libInfo);
3715 //===----------------------------------------------------------------------===//
3716 // Other Lowering Hooks
3717 //===----------------------------------------------------------------------===//
3719 static bool MayFoldLoad(SDValue Op) {
3720 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3723 static bool MayFoldIntoStore(SDValue Op) {
3724 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3727 static bool isTargetShuffle(unsigned Opcode) {
3729 default: return false;
3730 case X86ISD::BLENDI:
3731 case X86ISD::PSHUFB:
3732 case X86ISD::PSHUFD:
3733 case X86ISD::PSHUFHW:
3734 case X86ISD::PSHUFLW:
3736 case X86ISD::PALIGNR:
3737 case X86ISD::MOVLHPS:
3738 case X86ISD::MOVLHPD:
3739 case X86ISD::MOVHLPS:
3740 case X86ISD::MOVLPS:
3741 case X86ISD::MOVLPD:
3742 case X86ISD::MOVSHDUP:
3743 case X86ISD::MOVSLDUP:
3744 case X86ISD::MOVDDUP:
3747 case X86ISD::UNPCKL:
3748 case X86ISD::UNPCKH:
3749 case X86ISD::VPERMILPI:
3750 case X86ISD::VPERM2X128:
3751 case X86ISD::VPERMI:
3756 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3757 SDValue V1, unsigned TargetMask,
3758 SelectionDAG &DAG) {
3760 default: llvm_unreachable("Unknown x86 shuffle node");
3761 case X86ISD::PSHUFD:
3762 case X86ISD::PSHUFHW:
3763 case X86ISD::PSHUFLW:
3764 case X86ISD::VPERMILPI:
3765 case X86ISD::VPERMI:
3766 return DAG.getNode(Opc, dl, VT, V1,
3767 DAG.getConstant(TargetMask, dl, MVT::i8));
3771 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3772 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3774 default: llvm_unreachable("Unknown x86 shuffle node");
3775 case X86ISD::MOVLHPS:
3776 case X86ISD::MOVLHPD:
3777 case X86ISD::MOVHLPS:
3778 case X86ISD::MOVLPS:
3779 case X86ISD::MOVLPD:
3782 case X86ISD::UNPCKL:
3783 case X86ISD::UNPCKH:
3784 return DAG.getNode(Opc, dl, VT, V1, V2);
3788 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3789 MachineFunction &MF = DAG.getMachineFunction();
3790 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3791 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3792 int ReturnAddrIndex = FuncInfo->getRAIndex();
3794 if (ReturnAddrIndex == 0) {
3795 // Set up a frame object for the return address.
3796 unsigned SlotSize = RegInfo->getSlotSize();
3797 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3800 FuncInfo->setRAIndex(ReturnAddrIndex);
3803 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3806 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3807 bool hasSymbolicDisplacement) {
3808 // Offset should fit into 32 bit immediate field.
3809 if (!isInt<32>(Offset))
3812 // If we don't have a symbolic displacement - we don't have any extra
3814 if (!hasSymbolicDisplacement)
3817 // FIXME: Some tweaks might be needed for medium code model.
3818 if (M != CodeModel::Small && M != CodeModel::Kernel)
3821 // For small code model we assume that latest object is 16MB before end of 31
3822 // bits boundary. We may also accept pretty large negative constants knowing
3823 // that all objects are in the positive half of address space.
3824 if (M == CodeModel::Small && Offset < 16*1024*1024)
3827 // For kernel code model we know that all object resist in the negative half
3828 // of 32bits address space. We may not accept negative offsets, since they may
3829 // be just off and we may accept pretty large positive ones.
3830 if (M == CodeModel::Kernel && Offset >= 0)
3836 /// Determines whether the callee is required to pop its own arguments.
3837 /// Callee pop is necessary to support tail calls.
3838 bool X86::isCalleePop(CallingConv::ID CallingConv,
3839 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3840 switch (CallingConv) {
3843 case CallingConv::X86_StdCall:
3844 case CallingConv::X86_FastCall:
3845 case CallingConv::X86_ThisCall:
3847 case CallingConv::Fast:
3848 case CallingConv::GHC:
3849 case CallingConv::HiPE:
3856 /// \brief Return true if the condition is an unsigned comparison operation.
3857 static bool isX86CCUnsigned(unsigned X86CC) {
3859 default: llvm_unreachable("Invalid integer condition!");
3860 case X86::COND_E: return true;
3861 case X86::COND_G: return false;
3862 case X86::COND_GE: return false;
3863 case X86::COND_L: return false;
3864 case X86::COND_LE: return false;
3865 case X86::COND_NE: return true;
3866 case X86::COND_B: return true;
3867 case X86::COND_A: return true;
3868 case X86::COND_BE: return true;
3869 case X86::COND_AE: return true;
3871 llvm_unreachable("covered switch fell through?!");
3874 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3875 /// condition code, returning the condition code and the LHS/RHS of the
3876 /// comparison to make.
3877 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3878 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3880 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3881 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3882 // X > -1 -> X == 0, jump !sign.
3883 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3884 return X86::COND_NS;
3886 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3887 // X < 0 -> X == 0, jump on sign.
3890 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3892 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3893 return X86::COND_LE;
3897 switch (SetCCOpcode) {
3898 default: llvm_unreachable("Invalid integer condition!");
3899 case ISD::SETEQ: return X86::COND_E;
3900 case ISD::SETGT: return X86::COND_G;
3901 case ISD::SETGE: return X86::COND_GE;
3902 case ISD::SETLT: return X86::COND_L;
3903 case ISD::SETLE: return X86::COND_LE;
3904 case ISD::SETNE: return X86::COND_NE;
3905 case ISD::SETULT: return X86::COND_B;
3906 case ISD::SETUGT: return X86::COND_A;
3907 case ISD::SETULE: return X86::COND_BE;
3908 case ISD::SETUGE: return X86::COND_AE;
3912 // First determine if it is required or is profitable to flip the operands.
3914 // If LHS is a foldable load, but RHS is not, flip the condition.
3915 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3916 !ISD::isNON_EXTLoad(RHS.getNode())) {
3917 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3918 std::swap(LHS, RHS);
3921 switch (SetCCOpcode) {
3927 std::swap(LHS, RHS);
3931 // On a floating point condition, the flags are set as follows:
3933 // 0 | 0 | 0 | X > Y
3934 // 0 | 0 | 1 | X < Y
3935 // 1 | 0 | 0 | X == Y
3936 // 1 | 1 | 1 | unordered
3937 switch (SetCCOpcode) {
3938 default: llvm_unreachable("Condcode should be pre-legalized away");
3940 case ISD::SETEQ: return X86::COND_E;
3941 case ISD::SETOLT: // flipped
3943 case ISD::SETGT: return X86::COND_A;
3944 case ISD::SETOLE: // flipped
3946 case ISD::SETGE: return X86::COND_AE;
3947 case ISD::SETUGT: // flipped
3949 case ISD::SETLT: return X86::COND_B;
3950 case ISD::SETUGE: // flipped
3952 case ISD::SETLE: return X86::COND_BE;
3954 case ISD::SETNE: return X86::COND_NE;
3955 case ISD::SETUO: return X86::COND_P;
3956 case ISD::SETO: return X86::COND_NP;
3958 case ISD::SETUNE: return X86::COND_INVALID;
3962 /// Is there a floating point cmov for the specific X86 condition code?
3963 /// Current x86 isa includes the following FP cmov instructions:
3964 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3965 static bool hasFPCMov(unsigned X86CC) {
3981 /// Returns true if the target can instruction select the
3982 /// specified FP immediate natively. If false, the legalizer will
3983 /// materialize the FP immediate as a load from a constant pool.
3984 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3985 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3986 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3992 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3993 ISD::LoadExtType ExtTy,
3995 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3996 // relocation target a movq or addq instruction: don't let the load shrink.
3997 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3998 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3999 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4000 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4004 /// \brief Returns true if it is beneficial to convert a load of a constant
4005 /// to just the constant itself.
4006 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4008 assert(Ty->isIntegerTy());
4010 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4011 if (BitSize == 0 || BitSize > 64)
4016 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4017 unsigned Index) const {
4018 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4021 return (Index == 0 || Index == ResVT.getVectorNumElements());
4024 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4025 // Speculate cttz only if we can directly use TZCNT.
4026 return Subtarget->hasBMI();
4029 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4030 // Speculate ctlz only if we can directly use LZCNT.
4031 return Subtarget->hasLZCNT();
4034 /// Return true if every element in Mask, beginning
4035 /// from position Pos and ending in Pos+Size is undef.
4036 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4037 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4043 /// Return true if Val is undef or if its value falls within the
4044 /// specified range (L, H].
4045 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4046 return (Val < 0) || (Val >= Low && Val < Hi);
4049 /// Val is either less than zero (undef) or equal to the specified value.
4050 static bool isUndefOrEqual(int Val, int CmpVal) {
4051 return (Val < 0 || Val == CmpVal);
4054 /// Return true if every element in Mask, beginning
4055 /// from position Pos and ending in Pos+Size, falls within the specified
4056 /// sequential range (Low, Low+Size]. or is undef.
4057 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4058 unsigned Pos, unsigned Size, int Low) {
4059 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4060 if (!isUndefOrEqual(Mask[i], Low))
4065 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4066 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4067 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4068 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4069 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4072 // The index should be aligned on a vecWidth-bit boundary.
4074 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4076 MVT VT = N->getSimpleValueType(0);
4077 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4078 bool Result = (Index * ElSize) % vecWidth == 0;
4083 /// Return true if the specified INSERT_SUBVECTOR
4084 /// operand specifies a subvector insert that is suitable for input to
4085 /// insertion of 128 or 256-bit subvectors
4086 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4087 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4088 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4090 // The index should be aligned on a vecWidth-bit boundary.
4092 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4094 MVT VT = N->getSimpleValueType(0);
4095 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4096 bool Result = (Index * ElSize) % vecWidth == 0;
4101 bool X86::isVINSERT128Index(SDNode *N) {
4102 return isVINSERTIndex(N, 128);
4105 bool X86::isVINSERT256Index(SDNode *N) {
4106 return isVINSERTIndex(N, 256);
4109 bool X86::isVEXTRACT128Index(SDNode *N) {
4110 return isVEXTRACTIndex(N, 128);
4113 bool X86::isVEXTRACT256Index(SDNode *N) {
4114 return isVEXTRACTIndex(N, 256);
4117 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4118 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4119 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4120 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4123 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4125 MVT VecVT = N->getOperand(0).getSimpleValueType();
4126 MVT ElVT = VecVT.getVectorElementType();
4128 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4129 return Index / NumElemsPerChunk;
4132 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4133 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4134 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4135 llvm_unreachable("Illegal insert subvector for VINSERT");
4138 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4140 MVT VecVT = N->getSimpleValueType(0);
4141 MVT ElVT = VecVT.getVectorElementType();
4143 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4144 return Index / NumElemsPerChunk;
4147 /// Return the appropriate immediate to extract the specified
4148 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4149 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4150 return getExtractVEXTRACTImmediate(N, 128);
4153 /// Return the appropriate immediate to extract the specified
4154 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4155 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4156 return getExtractVEXTRACTImmediate(N, 256);
4159 /// Return the appropriate immediate to insert at the specified
4160 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4161 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4162 return getInsertVINSERTImmediate(N, 128);
4165 /// Return the appropriate immediate to insert at the specified
4166 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4167 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4168 return getInsertVINSERTImmediate(N, 256);
4171 /// Returns true if Elt is a constant integer zero
4172 static bool isZero(SDValue V) {
4173 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4174 return C && C->isNullValue();
4177 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4178 bool X86::isZeroNode(SDValue Elt) {
4181 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4182 return CFP->getValueAPF().isPosZero();
4186 /// Returns a vector of specified type with all zero elements.
4187 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4188 SelectionDAG &DAG, SDLoc dl) {
4189 assert(VT.isVector() && "Expected a vector type");
4191 // Always build SSE zero vectors as <4 x i32> bitcasted
4192 // to their dest type. This ensures they get CSE'd.
4194 if (VT.is128BitVector()) { // SSE
4195 if (Subtarget->hasSSE2()) { // SSE2
4196 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4197 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4199 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4200 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4202 } else if (VT.is256BitVector()) { // AVX
4203 if (Subtarget->hasInt256()) { // AVX2
4204 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4205 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4206 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4208 // 256-bit logic and arithmetic instructions in AVX are all
4209 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4210 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4211 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4212 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4214 } else if (VT.is512BitVector()) { // AVX-512
4215 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4216 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4217 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4218 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4219 } else if (VT.getScalarType() == MVT::i1) {
4221 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4222 && "Unexpected vector type");
4223 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4224 && "Unexpected vector type");
4225 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4226 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4227 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4229 llvm_unreachable("Unexpected vector type");
4231 return DAG.getBitcast(VT, Vec);
4234 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4235 SelectionDAG &DAG, SDLoc dl,
4236 unsigned vectorWidth) {
4237 assert((vectorWidth == 128 || vectorWidth == 256) &&
4238 "Unsupported vector width");
4239 EVT VT = Vec.getValueType();
4240 EVT ElVT = VT.getVectorElementType();
4241 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4242 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4243 VT.getVectorNumElements()/Factor);
4245 // Extract from UNDEF is UNDEF.
4246 if (Vec.getOpcode() == ISD::UNDEF)
4247 return DAG.getUNDEF(ResultVT);
4249 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4250 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4252 // This is the index of the first element of the vectorWidth-bit chunk
4254 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4257 // If the input is a buildvector just emit a smaller one.
4258 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4259 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4260 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4263 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4264 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4267 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4268 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4269 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4270 /// instructions or a simple subregister reference. Idx is an index in the
4271 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4272 /// lowering EXTRACT_VECTOR_ELT operations easier.
4273 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4274 SelectionDAG &DAG, SDLoc dl) {
4275 assert((Vec.getValueType().is256BitVector() ||
4276 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4277 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4280 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4281 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4282 SelectionDAG &DAG, SDLoc dl) {
4283 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4284 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4287 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4288 unsigned IdxVal, SelectionDAG &DAG,
4289 SDLoc dl, unsigned vectorWidth) {
4290 assert((vectorWidth == 128 || vectorWidth == 256) &&
4291 "Unsupported vector width");
4292 // Inserting UNDEF is Result
4293 if (Vec.getOpcode() == ISD::UNDEF)
4295 EVT VT = Vec.getValueType();
4296 EVT ElVT = VT.getVectorElementType();
4297 EVT ResultVT = Result.getValueType();
4299 // Insert the relevant vectorWidth bits.
4300 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4302 // This is the index of the first element of the vectorWidth-bit chunk
4304 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4307 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4308 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4311 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4312 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4313 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4314 /// simple superregister reference. Idx is an index in the 128 bits
4315 /// we want. It need not be aligned to a 128-bit boundary. That makes
4316 /// lowering INSERT_VECTOR_ELT operations easier.
4317 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4318 SelectionDAG &DAG, SDLoc dl) {
4319 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4321 // For insertion into the zero index (low half) of a 256-bit vector, it is
4322 // more efficient to generate a blend with immediate instead of an insert*128.
4323 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4324 // extend the subvector to the size of the result vector. Make sure that
4325 // we are not recursing on that node by checking for undef here.
4326 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4327 Result.getOpcode() != ISD::UNDEF) {
4328 EVT ResultVT = Result.getValueType();
4329 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4330 SDValue Undef = DAG.getUNDEF(ResultVT);
4331 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4334 // The blend instruction, and therefore its mask, depend on the data type.
4335 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4336 if (ScalarType.isFloatingPoint()) {
4337 // Choose either vblendps (float) or vblendpd (double).
4338 unsigned ScalarSize = ScalarType.getSizeInBits();
4339 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4340 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4341 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4342 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4345 const X86Subtarget &Subtarget =
4346 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4348 // AVX2 is needed for 256-bit integer blend support.
4349 // Integers must be cast to 32-bit because there is only vpblendd;
4350 // vpblendw can't be used for this because it has a handicapped mask.
4352 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4353 // is still more efficient than using the wrong domain vinsertf128 that
4354 // will be created by InsertSubVector().
4355 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4357 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4358 Vec256 = DAG.getBitcast(CastVT, Vec256);
4359 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4360 return DAG.getBitcast(ResultVT, Vec256);
4363 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4366 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4367 SelectionDAG &DAG, SDLoc dl) {
4368 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4369 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4372 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4373 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4374 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4375 /// large BUILD_VECTORS.
4376 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4377 unsigned NumElems, SelectionDAG &DAG,
4379 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4380 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4383 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4384 unsigned NumElems, SelectionDAG &DAG,
4386 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4387 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4390 /// Returns a vector of specified type with all bits set.
4391 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4392 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4393 /// Then bitcast to their original type, ensuring they get CSE'd.
4394 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4396 assert(VT.isVector() && "Expected a vector type");
4398 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4400 if (VT.is256BitVector()) {
4401 if (HasInt256) { // AVX2
4402 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4403 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4405 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4406 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4408 } else if (VT.is128BitVector()) {
4409 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4411 llvm_unreachable("Unexpected vector type");
4413 return DAG.getBitcast(VT, Vec);
4416 /// Returns a vector_shuffle node for an unpackl operation.
4417 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4419 unsigned NumElems = VT.getVectorNumElements();
4420 SmallVector<int, 8> Mask;
4421 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4423 Mask.push_back(i + NumElems);
4425 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4428 /// Returns a vector_shuffle node for an unpackh operation.
4429 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4431 unsigned NumElems = VT.getVectorNumElements();
4432 SmallVector<int, 8> Mask;
4433 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4434 Mask.push_back(i + Half);
4435 Mask.push_back(i + NumElems + Half);
4437 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4440 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4441 /// This produces a shuffle where the low element of V2 is swizzled into the
4442 /// zero/undef vector, landing at element Idx.
4443 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4444 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4446 const X86Subtarget *Subtarget,
4447 SelectionDAG &DAG) {
4448 MVT VT = V2.getSimpleValueType();
4450 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4451 unsigned NumElems = VT.getVectorNumElements();
4452 SmallVector<int, 16> MaskVec;
4453 for (unsigned i = 0; i != NumElems; ++i)
4454 // If this is the insertion idx, put the low elt of V2 here.
4455 MaskVec.push_back(i == Idx ? NumElems : i);
4456 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4459 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4460 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4461 /// uses one source. Note that this will set IsUnary for shuffles which use a
4462 /// single input multiple times, and in those cases it will
4463 /// adjust the mask to only have indices within that single input.
4464 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4465 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4466 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4467 unsigned NumElems = VT.getVectorNumElements();
4471 bool IsFakeUnary = false;
4472 switch(N->getOpcode()) {
4473 case X86ISD::BLENDI:
4474 ImmN = N->getOperand(N->getNumOperands()-1);
4475 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4478 ImmN = N->getOperand(N->getNumOperands()-1);
4479 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4480 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4482 case X86ISD::UNPCKH:
4483 DecodeUNPCKHMask(VT, Mask);
4484 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4486 case X86ISD::UNPCKL:
4487 DecodeUNPCKLMask(VT, Mask);
4488 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4490 case X86ISD::MOVHLPS:
4491 DecodeMOVHLPSMask(NumElems, Mask);
4492 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4494 case X86ISD::MOVLHPS:
4495 DecodeMOVLHPSMask(NumElems, Mask);
4496 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4498 case X86ISD::PALIGNR:
4499 ImmN = N->getOperand(N->getNumOperands()-1);
4500 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4502 case X86ISD::PSHUFD:
4503 case X86ISD::VPERMILPI:
4504 ImmN = N->getOperand(N->getNumOperands()-1);
4505 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4508 case X86ISD::PSHUFHW:
4509 ImmN = N->getOperand(N->getNumOperands()-1);
4510 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4513 case X86ISD::PSHUFLW:
4514 ImmN = N->getOperand(N->getNumOperands()-1);
4515 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4518 case X86ISD::PSHUFB: {
4520 SDValue MaskNode = N->getOperand(1);
4521 while (MaskNode->getOpcode() == ISD::BITCAST)
4522 MaskNode = MaskNode->getOperand(0);
4524 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4525 // If we have a build-vector, then things are easy.
4526 EVT VT = MaskNode.getValueType();
4527 assert(VT.isVector() &&
4528 "Can't produce a non-vector with a build_vector!");
4529 if (!VT.isInteger())
4532 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4534 SmallVector<uint64_t, 32> RawMask;
4535 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4536 SDValue Op = MaskNode->getOperand(i);
4537 if (Op->getOpcode() == ISD::UNDEF) {
4538 RawMask.push_back((uint64_t)SM_SentinelUndef);
4541 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4544 APInt MaskElement = CN->getAPIntValue();
4546 // We now have to decode the element which could be any integer size and
4547 // extract each byte of it.
4548 for (int j = 0; j < NumBytesPerElement; ++j) {
4549 // Note that this is x86 and so always little endian: the low byte is
4550 // the first byte of the mask.
4551 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4552 MaskElement = MaskElement.lshr(8);
4555 DecodePSHUFBMask(RawMask, Mask);
4559 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4563 SDValue Ptr = MaskLoad->getBasePtr();
4564 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4565 Ptr->getOpcode() == X86ISD::WrapperRIP)
4566 Ptr = Ptr->getOperand(0);
4568 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4569 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4572 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4573 DecodePSHUFBMask(C, Mask);
4581 case X86ISD::VPERMI:
4582 ImmN = N->getOperand(N->getNumOperands()-1);
4583 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4588 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4590 case X86ISD::VPERM2X128:
4591 ImmN = N->getOperand(N->getNumOperands()-1);
4592 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4593 if (Mask.empty()) return false;
4594 // Mask only contains negative index if an element is zero.
4595 if (std::any_of(Mask.begin(), Mask.end(),
4596 [](int M){ return M == SM_SentinelZero; }))
4599 case X86ISD::MOVSLDUP:
4600 DecodeMOVSLDUPMask(VT, Mask);
4603 case X86ISD::MOVSHDUP:
4604 DecodeMOVSHDUPMask(VT, Mask);
4607 case X86ISD::MOVDDUP:
4608 DecodeMOVDDUPMask(VT, Mask);
4611 case X86ISD::MOVLHPD:
4612 case X86ISD::MOVLPD:
4613 case X86ISD::MOVLPS:
4614 // Not yet implemented
4616 default: llvm_unreachable("unknown target shuffle node");
4619 // If we have a fake unary shuffle, the shuffle mask is spread across two
4620 // inputs that are actually the same node. Re-map the mask to always point
4621 // into the first input.
4624 if (M >= (int)Mask.size())
4630 /// Returns the scalar element that will make up the ith
4631 /// element of the result of the vector shuffle.
4632 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4635 return SDValue(); // Limit search depth.
4637 SDValue V = SDValue(N, 0);
4638 EVT VT = V.getValueType();
4639 unsigned Opcode = V.getOpcode();
4641 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4642 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4643 int Elt = SV->getMaskElt(Index);
4646 return DAG.getUNDEF(VT.getVectorElementType());
4648 unsigned NumElems = VT.getVectorNumElements();
4649 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4650 : SV->getOperand(1);
4651 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4654 // Recurse into target specific vector shuffles to find scalars.
4655 if (isTargetShuffle(Opcode)) {
4656 MVT ShufVT = V.getSimpleValueType();
4657 unsigned NumElems = ShufVT.getVectorNumElements();
4658 SmallVector<int, 16> ShuffleMask;
4661 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4664 int Elt = ShuffleMask[Index];
4666 return DAG.getUNDEF(ShufVT.getVectorElementType());
4668 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4670 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4674 // Actual nodes that may contain scalar elements
4675 if (Opcode == ISD::BITCAST) {
4676 V = V.getOperand(0);
4677 EVT SrcVT = V.getValueType();
4678 unsigned NumElems = VT.getVectorNumElements();
4680 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4684 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4685 return (Index == 0) ? V.getOperand(0)
4686 : DAG.getUNDEF(VT.getVectorElementType());
4688 if (V.getOpcode() == ISD::BUILD_VECTOR)
4689 return V.getOperand(Index);
4694 /// Custom lower build_vector of v16i8.
4695 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4696 unsigned NumNonZero, unsigned NumZero,
4698 const X86Subtarget* Subtarget,
4699 const TargetLowering &TLI) {
4707 // SSE4.1 - use PINSRB to insert each byte directly.
4708 if (Subtarget->hasSSE41()) {
4709 for (unsigned i = 0; i < 16; ++i) {
4710 bool isNonZero = (NonZeros & (1 << i)) != 0;
4714 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4716 V = DAG.getUNDEF(MVT::v16i8);
4719 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4720 MVT::v16i8, V, Op.getOperand(i),
4721 DAG.getIntPtrConstant(i, dl));
4728 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4729 for (unsigned i = 0; i < 16; ++i) {
4730 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4731 if (ThisIsNonZero && First) {
4733 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4735 V = DAG.getUNDEF(MVT::v8i16);
4740 SDValue ThisElt, LastElt;
4741 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4742 if (LastIsNonZero) {
4743 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4744 MVT::i16, Op.getOperand(i-1));
4746 if (ThisIsNonZero) {
4747 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4748 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4749 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4751 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4755 if (ThisElt.getNode())
4756 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4757 DAG.getIntPtrConstant(i/2, dl));
4761 return DAG.getBitcast(MVT::v16i8, V);
4764 /// Custom lower build_vector of v8i16.
4765 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4766 unsigned NumNonZero, unsigned NumZero,
4768 const X86Subtarget* Subtarget,
4769 const TargetLowering &TLI) {
4776 for (unsigned i = 0; i < 8; ++i) {
4777 bool isNonZero = (NonZeros & (1 << i)) != 0;
4781 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4783 V = DAG.getUNDEF(MVT::v8i16);
4786 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4787 MVT::v8i16, V, Op.getOperand(i),
4788 DAG.getIntPtrConstant(i, dl));
4795 /// Custom lower build_vector of v4i32 or v4f32.
4796 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4797 const X86Subtarget *Subtarget,
4798 const TargetLowering &TLI) {
4799 // Find all zeroable elements.
4800 std::bitset<4> Zeroable;
4801 for (int i=0; i < 4; ++i) {
4802 SDValue Elt = Op->getOperand(i);
4803 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4805 assert(Zeroable.size() - Zeroable.count() > 1 &&
4806 "We expect at least two non-zero elements!");
4808 // We only know how to deal with build_vector nodes where elements are either
4809 // zeroable or extract_vector_elt with constant index.
4810 SDValue FirstNonZero;
4811 unsigned FirstNonZeroIdx;
4812 for (unsigned i=0; i < 4; ++i) {
4815 SDValue Elt = Op->getOperand(i);
4816 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4817 !isa<ConstantSDNode>(Elt.getOperand(1)))
4819 // Make sure that this node is extracting from a 128-bit vector.
4820 MVT VT = Elt.getOperand(0).getSimpleValueType();
4821 if (!VT.is128BitVector())
4823 if (!FirstNonZero.getNode()) {
4825 FirstNonZeroIdx = i;
4829 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4830 SDValue V1 = FirstNonZero.getOperand(0);
4831 MVT VT = V1.getSimpleValueType();
4833 // See if this build_vector can be lowered as a blend with zero.
4835 unsigned EltMaskIdx, EltIdx;
4837 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4838 if (Zeroable[EltIdx]) {
4839 // The zero vector will be on the right hand side.
4840 Mask[EltIdx] = EltIdx+4;
4844 Elt = Op->getOperand(EltIdx);
4845 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4846 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4847 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4849 Mask[EltIdx] = EltIdx;
4853 // Let the shuffle legalizer deal with blend operations.
4854 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4855 if (V1.getSimpleValueType() != VT)
4856 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4857 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4860 // See if we can lower this build_vector to a INSERTPS.
4861 if (!Subtarget->hasSSE41())
4864 SDValue V2 = Elt.getOperand(0);
4865 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4868 bool CanFold = true;
4869 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4873 SDValue Current = Op->getOperand(i);
4874 SDValue SrcVector = Current->getOperand(0);
4877 CanFold = SrcVector == V1 &&
4878 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4884 assert(V1.getNode() && "Expected at least two non-zero elements!");
4885 if (V1.getSimpleValueType() != MVT::v4f32)
4886 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4887 if (V2.getSimpleValueType() != MVT::v4f32)
4888 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4890 // Ok, we can emit an INSERTPS instruction.
4891 unsigned ZMask = Zeroable.to_ulong();
4893 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4894 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4896 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4897 DAG.getIntPtrConstant(InsertPSMask, DL));
4898 return DAG.getBitcast(VT, Result);
4901 /// Return a vector logical shift node.
4902 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4903 unsigned NumBits, SelectionDAG &DAG,
4904 const TargetLowering &TLI, SDLoc dl) {
4905 assert(VT.is128BitVector() && "Unknown type for VShift");
4906 MVT ShVT = MVT::v2i64;
4907 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4908 SrcOp = DAG.getBitcast(ShVT, SrcOp);
4909 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4910 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4911 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4912 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4916 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4918 // Check if the scalar load can be widened into a vector load. And if
4919 // the address is "base + cst" see if the cst can be "absorbed" into
4920 // the shuffle mask.
4921 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4922 SDValue Ptr = LD->getBasePtr();
4923 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4925 EVT PVT = LD->getValueType(0);
4926 if (PVT != MVT::i32 && PVT != MVT::f32)
4931 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4932 FI = FINode->getIndex();
4934 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4935 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4936 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4937 Offset = Ptr.getConstantOperandVal(1);
4938 Ptr = Ptr.getOperand(0);
4943 // FIXME: 256-bit vector instructions don't require a strict alignment,
4944 // improve this code to support it better.
4945 unsigned RequiredAlign = VT.getSizeInBits()/8;
4946 SDValue Chain = LD->getChain();
4947 // Make sure the stack object alignment is at least 16 or 32.
4948 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4949 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4950 if (MFI->isFixedObjectIndex(FI)) {
4951 // Can't change the alignment. FIXME: It's possible to compute
4952 // the exact stack offset and reference FI + adjust offset instead.
4953 // If someone *really* cares about this. That's the way to implement it.
4956 MFI->setObjectAlignment(FI, RequiredAlign);
4960 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4961 // Ptr + (Offset & ~15).
4964 if ((Offset % RequiredAlign) & 3)
4966 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4969 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4970 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4973 int EltNo = (Offset - StartOffset) >> 2;
4974 unsigned NumElems = VT.getVectorNumElements();
4976 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4977 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4978 LD->getPointerInfo().getWithOffset(StartOffset),
4979 false, false, false, 0);
4981 SmallVector<int, 8> Mask(NumElems, EltNo);
4983 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4989 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4990 /// elements can be replaced by a single large load which has the same value as
4991 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4993 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4995 /// FIXME: we'd also like to handle the case where the last elements are zero
4996 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4997 /// There's even a handy isZeroNode for that purpose.
4998 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4999 SDLoc &DL, SelectionDAG &DAG,
5000 bool isAfterLegalize) {
5001 unsigned NumElems = Elts.size();
5003 LoadSDNode *LDBase = nullptr;
5004 unsigned LastLoadedElt = -1U;
5006 // For each element in the initializer, see if we've found a load or an undef.
5007 // If we don't find an initial load element, or later load elements are
5008 // non-consecutive, bail out.
5009 for (unsigned i = 0; i < NumElems; ++i) {
5010 SDValue Elt = Elts[i];
5011 // Look through a bitcast.
5012 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5013 Elt = Elt.getOperand(0);
5014 if (!Elt.getNode() ||
5015 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5018 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5020 LDBase = cast<LoadSDNode>(Elt.getNode());
5024 if (Elt.getOpcode() == ISD::UNDEF)
5027 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5028 EVT LdVT = Elt.getValueType();
5029 // Each loaded element must be the correct fractional portion of the
5030 // requested vector load.
5031 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5033 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5038 // If we have found an entire vector of loads and undefs, then return a large
5039 // load of the entire vector width starting at the base pointer. If we found
5040 // consecutive loads for the low half, generate a vzext_load node.
5041 if (LastLoadedElt == NumElems - 1) {
5042 assert(LDBase && "Did not find base load for merging consecutive loads");
5043 EVT EltVT = LDBase->getValueType(0);
5044 // Ensure that the input vector size for the merged loads matches the
5045 // cumulative size of the input elements.
5046 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5049 if (isAfterLegalize &&
5050 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5053 SDValue NewLd = SDValue();
5055 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5056 LDBase->getPointerInfo(), LDBase->isVolatile(),
5057 LDBase->isNonTemporal(), LDBase->isInvariant(),
5058 LDBase->getAlignment());
5060 if (LDBase->hasAnyUseOfValue(1)) {
5061 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5063 SDValue(NewLd.getNode(), 1));
5064 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5065 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5066 SDValue(NewLd.getNode(), 1));
5072 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5073 //of a v4i32 / v4f32. It's probably worth generalizing.
5074 EVT EltVT = VT.getVectorElementType();
5075 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5076 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5077 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5078 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5080 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5081 LDBase->getPointerInfo(),
5082 LDBase->getAlignment(),
5083 false/*isVolatile*/, true/*ReadMem*/,
5086 // Make sure the newly-created LOAD is in the same position as LDBase in
5087 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5088 // update uses of LDBase's output chain to use the TokenFactor.
5089 if (LDBase->hasAnyUseOfValue(1)) {
5090 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5091 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5092 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5093 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5094 SDValue(ResNode.getNode(), 1));
5097 return DAG.getBitcast(VT, ResNode);
5102 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5103 /// to generate a splat value for the following cases:
5104 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5105 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5106 /// a scalar load, or a constant.
5107 /// The VBROADCAST node is returned when a pattern is found,
5108 /// or SDValue() otherwise.
5109 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5110 SelectionDAG &DAG) {
5111 // VBROADCAST requires AVX.
5112 // TODO: Splats could be generated for non-AVX CPUs using SSE
5113 // instructions, but there's less potential gain for only 128-bit vectors.
5114 if (!Subtarget->hasAVX())
5117 MVT VT = Op.getSimpleValueType();
5120 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5121 "Unsupported vector type for broadcast.");
5126 switch (Op.getOpcode()) {
5128 // Unknown pattern found.
5131 case ISD::BUILD_VECTOR: {
5132 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5133 BitVector UndefElements;
5134 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5136 // We need a splat of a single value to use broadcast, and it doesn't
5137 // make any sense if the value is only in one element of the vector.
5138 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5142 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5143 Ld.getOpcode() == ISD::ConstantFP);
5145 // Make sure that all of the users of a non-constant load are from the
5146 // BUILD_VECTOR node.
5147 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5152 case ISD::VECTOR_SHUFFLE: {
5153 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5155 // Shuffles must have a splat mask where the first element is
5157 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5160 SDValue Sc = Op.getOperand(0);
5161 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5162 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5164 if (!Subtarget->hasInt256())
5167 // Use the register form of the broadcast instruction available on AVX2.
5168 if (VT.getSizeInBits() >= 256)
5169 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5170 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5173 Ld = Sc.getOperand(0);
5174 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5175 Ld.getOpcode() == ISD::ConstantFP);
5177 // The scalar_to_vector node and the suspected
5178 // load node must have exactly one user.
5179 // Constants may have multiple users.
5181 // AVX-512 has register version of the broadcast
5182 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5183 Ld.getValueType().getSizeInBits() >= 32;
5184 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5191 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5192 bool IsGE256 = (VT.getSizeInBits() >= 256);
5194 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5195 // instruction to save 8 or more bytes of constant pool data.
5196 // TODO: If multiple splats are generated to load the same constant,
5197 // it may be detrimental to overall size. There needs to be a way to detect
5198 // that condition to know if this is truly a size win.
5199 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5201 // Handle broadcasting a single constant scalar from the constant pool
5203 // On Sandybridge (no AVX2), it is still better to load a constant vector
5204 // from the constant pool and not to broadcast it from a scalar.
5205 // But override that restriction when optimizing for size.
5206 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5207 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5208 EVT CVT = Ld.getValueType();
5209 assert(!CVT.isVector() && "Must not broadcast a vector type");
5211 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5212 // For size optimization, also splat v2f64 and v2i64, and for size opt
5213 // with AVX2, also splat i8 and i16.
5214 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5215 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5216 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5217 const Constant *C = nullptr;
5218 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5219 C = CI->getConstantIntValue();
5220 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5221 C = CF->getConstantFPValue();
5223 assert(C && "Invalid constant type");
5225 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5227 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5228 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5230 CVT, dl, DAG.getEntryNode(), CP,
5231 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5232 false, false, Alignment);
5234 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5238 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5240 // Handle AVX2 in-register broadcasts.
5241 if (!IsLoad && Subtarget->hasInt256() &&
5242 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5243 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5245 // The scalar source must be a normal load.
5249 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5250 (Subtarget->hasVLX() && ScalarSize == 64))
5251 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5253 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5254 // double since there is no vbroadcastsd xmm
5255 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5256 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5257 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5260 // Unsupported broadcast.
5264 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5265 /// underlying vector and index.
5267 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5269 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5271 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5272 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5275 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5277 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5279 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5280 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5283 // In this case the vector is the extract_subvector expression and the index
5284 // is 2, as specified by the shuffle.
5285 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5286 SDValue ShuffleVec = SVOp->getOperand(0);
5287 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5288 assert(ShuffleVecVT.getVectorElementType() ==
5289 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5291 int ShuffleIdx = SVOp->getMaskElt(Idx);
5292 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5293 ExtractedFromVec = ShuffleVec;
5299 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5300 MVT VT = Op.getSimpleValueType();
5302 // Skip if insert_vec_elt is not supported.
5303 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5304 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5308 unsigned NumElems = Op.getNumOperands();
5312 SmallVector<unsigned, 4> InsertIndices;
5313 SmallVector<int, 8> Mask(NumElems, -1);
5315 for (unsigned i = 0; i != NumElems; ++i) {
5316 unsigned Opc = Op.getOperand(i).getOpcode();
5318 if (Opc == ISD::UNDEF)
5321 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5322 // Quit if more than 1 elements need inserting.
5323 if (InsertIndices.size() > 1)
5326 InsertIndices.push_back(i);
5330 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5331 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5332 // Quit if non-constant index.
5333 if (!isa<ConstantSDNode>(ExtIdx))
5335 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5337 // Quit if extracted from vector of different type.
5338 if (ExtractedFromVec.getValueType() != VT)
5341 if (!VecIn1.getNode())
5342 VecIn1 = ExtractedFromVec;
5343 else if (VecIn1 != ExtractedFromVec) {
5344 if (!VecIn2.getNode())
5345 VecIn2 = ExtractedFromVec;
5346 else if (VecIn2 != ExtractedFromVec)
5347 // Quit if more than 2 vectors to shuffle
5351 if (ExtractedFromVec == VecIn1)
5353 else if (ExtractedFromVec == VecIn2)
5354 Mask[i] = Idx + NumElems;
5357 if (!VecIn1.getNode())
5360 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5361 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5362 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5363 unsigned Idx = InsertIndices[i];
5364 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5365 DAG.getIntPtrConstant(Idx, DL));
5371 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5372 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5373 Op.getScalarValueSizeInBits() == 1 &&
5374 "Can not convert non-constant vector");
5375 uint64_t Immediate = 0;
5376 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5377 SDValue In = Op.getOperand(idx);
5378 if (In.getOpcode() != ISD::UNDEF)
5379 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5383 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5384 return DAG.getConstant(Immediate, dl, VT);
5386 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5388 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5390 MVT VT = Op.getSimpleValueType();
5391 assert((VT.getVectorElementType() == MVT::i1) &&
5392 "Unexpected type in LowerBUILD_VECTORvXi1!");
5395 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5396 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5397 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5398 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5401 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5402 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5403 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5404 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5407 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5408 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5409 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5410 return DAG.getBitcast(VT, Imm);
5411 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5412 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5413 DAG.getIntPtrConstant(0, dl));
5416 // Vector has one or more non-const elements
5417 uint64_t Immediate = 0;
5418 SmallVector<unsigned, 16> NonConstIdx;
5419 bool IsSplat = true;
5420 bool HasConstElts = false;
5422 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5423 SDValue In = Op.getOperand(idx);
5424 if (In.getOpcode() == ISD::UNDEF)
5426 if (!isa<ConstantSDNode>(In))
5427 NonConstIdx.push_back(idx);
5429 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5430 HasConstElts = true;
5434 else if (In != Op.getOperand(SplatIdx))
5438 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5440 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5441 DAG.getConstant(1, dl, VT),
5442 DAG.getConstant(0, dl, VT));
5444 // insert elements one by one
5448 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5449 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5451 else if (HasConstElts)
5452 Imm = DAG.getConstant(0, dl, VT);
5454 Imm = DAG.getUNDEF(VT);
5455 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5456 DstVec = DAG.getBitcast(VT, Imm);
5458 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5459 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5460 DAG.getIntPtrConstant(0, dl));
5463 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5464 unsigned InsertIdx = NonConstIdx[i];
5465 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5466 Op.getOperand(InsertIdx),
5467 DAG.getIntPtrConstant(InsertIdx, dl));
5472 /// \brief Return true if \p N implements a horizontal binop and return the
5473 /// operands for the horizontal binop into V0 and V1.
5475 /// This is a helper function of LowerToHorizontalOp().
5476 /// This function checks that the build_vector \p N in input implements a
5477 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5478 /// operation to match.
5479 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5480 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5481 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5484 /// This function only analyzes elements of \p N whose indices are
5485 /// in range [BaseIdx, LastIdx).
5486 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5488 unsigned BaseIdx, unsigned LastIdx,
5489 SDValue &V0, SDValue &V1) {
5490 EVT VT = N->getValueType(0);
5492 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5493 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5494 "Invalid Vector in input!");
5496 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5497 bool CanFold = true;
5498 unsigned ExpectedVExtractIdx = BaseIdx;
5499 unsigned NumElts = LastIdx - BaseIdx;
5500 V0 = DAG.getUNDEF(VT);
5501 V1 = DAG.getUNDEF(VT);
5503 // Check if N implements a horizontal binop.
5504 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5505 SDValue Op = N->getOperand(i + BaseIdx);
5508 if (Op->getOpcode() == ISD::UNDEF) {
5509 // Update the expected vector extract index.
5510 if (i * 2 == NumElts)
5511 ExpectedVExtractIdx = BaseIdx;
5512 ExpectedVExtractIdx += 2;
5516 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5521 SDValue Op0 = Op.getOperand(0);
5522 SDValue Op1 = Op.getOperand(1);
5524 // Try to match the following pattern:
5525 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5526 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5527 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5528 Op0.getOperand(0) == Op1.getOperand(0) &&
5529 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5530 isa<ConstantSDNode>(Op1.getOperand(1)));
5534 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5535 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5537 if (i * 2 < NumElts) {
5538 if (V0.getOpcode() == ISD::UNDEF) {
5539 V0 = Op0.getOperand(0);
5540 if (V0.getValueType() != VT)
5544 if (V1.getOpcode() == ISD::UNDEF) {
5545 V1 = Op0.getOperand(0);
5546 if (V1.getValueType() != VT)
5549 if (i * 2 == NumElts)
5550 ExpectedVExtractIdx = BaseIdx;
5553 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5554 if (I0 == ExpectedVExtractIdx)
5555 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5556 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5557 // Try to match the following dag sequence:
5558 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5559 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5563 ExpectedVExtractIdx += 2;
5569 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5570 /// a concat_vector.
5572 /// This is a helper function of LowerToHorizontalOp().
5573 /// This function expects two 256-bit vectors called V0 and V1.
5574 /// At first, each vector is split into two separate 128-bit vectors.
5575 /// Then, the resulting 128-bit vectors are used to implement two
5576 /// horizontal binary operations.
5578 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5580 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5581 /// the two new horizontal binop.
5582 /// When Mode is set, the first horizontal binop dag node would take as input
5583 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5584 /// horizontal binop dag node would take as input the lower 128-bit of V1
5585 /// and the upper 128-bit of V1.
5587 /// HADD V0_LO, V0_HI
5588 /// HADD V1_LO, V1_HI
5590 /// Otherwise, the first horizontal binop dag node takes as input the lower
5591 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5592 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5594 /// HADD V0_LO, V1_LO
5595 /// HADD V0_HI, V1_HI
5597 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5598 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5599 /// the upper 128-bits of the result.
5600 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5601 SDLoc DL, SelectionDAG &DAG,
5602 unsigned X86Opcode, bool Mode,
5603 bool isUndefLO, bool isUndefHI) {
5604 EVT VT = V0.getValueType();
5605 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5606 "Invalid nodes in input!");
5608 unsigned NumElts = VT.getVectorNumElements();
5609 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5610 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5611 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5612 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5613 EVT NewVT = V0_LO.getValueType();
5615 SDValue LO = DAG.getUNDEF(NewVT);
5616 SDValue HI = DAG.getUNDEF(NewVT);
5619 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5620 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5621 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5622 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5623 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5625 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5626 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5627 V1_LO->getOpcode() != ISD::UNDEF))
5628 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5630 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5631 V1_HI->getOpcode() != ISD::UNDEF))
5632 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5635 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5638 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5640 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5641 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5642 EVT VT = BV->getValueType(0);
5643 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5644 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5648 unsigned NumElts = VT.getVectorNumElements();
5649 SDValue InVec0 = DAG.getUNDEF(VT);
5650 SDValue InVec1 = DAG.getUNDEF(VT);
5652 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5653 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5655 // Odd-numbered elements in the input build vector are obtained from
5656 // adding two integer/float elements.
5657 // Even-numbered elements in the input build vector are obtained from
5658 // subtracting two integer/float elements.
5659 unsigned ExpectedOpcode = ISD::FSUB;
5660 unsigned NextExpectedOpcode = ISD::FADD;
5661 bool AddFound = false;
5662 bool SubFound = false;
5664 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5665 SDValue Op = BV->getOperand(i);
5667 // Skip 'undef' values.
5668 unsigned Opcode = Op.getOpcode();
5669 if (Opcode == ISD::UNDEF) {
5670 std::swap(ExpectedOpcode, NextExpectedOpcode);
5674 // Early exit if we found an unexpected opcode.
5675 if (Opcode != ExpectedOpcode)
5678 SDValue Op0 = Op.getOperand(0);
5679 SDValue Op1 = Op.getOperand(1);
5681 // Try to match the following pattern:
5682 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5683 // Early exit if we cannot match that sequence.
5684 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5685 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5686 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5687 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5688 Op0.getOperand(1) != Op1.getOperand(1))
5691 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5695 // We found a valid add/sub node. Update the information accordingly.
5701 // Update InVec0 and InVec1.
5702 if (InVec0.getOpcode() == ISD::UNDEF) {
5703 InVec0 = Op0.getOperand(0);
5704 if (InVec0.getValueType() != VT)
5707 if (InVec1.getOpcode() == ISD::UNDEF) {
5708 InVec1 = Op1.getOperand(0);
5709 if (InVec1.getValueType() != VT)
5713 // Make sure that operands in input to each add/sub node always
5714 // come from a same pair of vectors.
5715 if (InVec0 != Op0.getOperand(0)) {
5716 if (ExpectedOpcode == ISD::FSUB)
5719 // FADD is commutable. Try to commute the operands
5720 // and then test again.
5721 std::swap(Op0, Op1);
5722 if (InVec0 != Op0.getOperand(0))
5726 if (InVec1 != Op1.getOperand(0))
5729 // Update the pair of expected opcodes.
5730 std::swap(ExpectedOpcode, NextExpectedOpcode);
5733 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5734 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5735 InVec1.getOpcode() != ISD::UNDEF)
5736 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5741 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5742 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5743 const X86Subtarget *Subtarget,
5744 SelectionDAG &DAG) {
5745 EVT VT = BV->getValueType(0);
5746 unsigned NumElts = VT.getVectorNumElements();
5747 unsigned NumUndefsLO = 0;
5748 unsigned NumUndefsHI = 0;
5749 unsigned Half = NumElts/2;
5751 // Count the number of UNDEF operands in the build_vector in input.
5752 for (unsigned i = 0, e = Half; i != e; ++i)
5753 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5756 for (unsigned i = Half, e = NumElts; i != e; ++i)
5757 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5760 // Early exit if this is either a build_vector of all UNDEFs or all the
5761 // operands but one are UNDEF.
5762 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5766 SDValue InVec0, InVec1;
5767 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5768 // Try to match an SSE3 float HADD/HSUB.
5769 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5770 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5772 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5773 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5774 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5775 // Try to match an SSSE3 integer HADD/HSUB.
5776 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5777 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5779 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5780 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5783 if (!Subtarget->hasAVX())
5786 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5787 // Try to match an AVX horizontal add/sub of packed single/double
5788 // precision floating point values from 256-bit vectors.
5789 SDValue InVec2, InVec3;
5790 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5791 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5792 ((InVec0.getOpcode() == ISD::UNDEF ||
5793 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5794 ((InVec1.getOpcode() == ISD::UNDEF ||
5795 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5796 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5798 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5799 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5800 ((InVec0.getOpcode() == ISD::UNDEF ||
5801 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5802 ((InVec1.getOpcode() == ISD::UNDEF ||
5803 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5804 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5805 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5806 // Try to match an AVX2 horizontal add/sub of signed integers.
5807 SDValue InVec2, InVec3;
5809 bool CanFold = true;
5811 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5812 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5813 ((InVec0.getOpcode() == ISD::UNDEF ||
5814 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5815 ((InVec1.getOpcode() == ISD::UNDEF ||
5816 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5817 X86Opcode = X86ISD::HADD;
5818 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5819 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5820 ((InVec0.getOpcode() == ISD::UNDEF ||
5821 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5822 ((InVec1.getOpcode() == ISD::UNDEF ||
5823 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5824 X86Opcode = X86ISD::HSUB;
5829 // Fold this build_vector into a single horizontal add/sub.
5830 // Do this only if the target has AVX2.
5831 if (Subtarget->hasAVX2())
5832 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5834 // Do not try to expand this build_vector into a pair of horizontal
5835 // add/sub if we can emit a pair of scalar add/sub.
5836 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5839 // Convert this build_vector into a pair of horizontal binop followed by
5841 bool isUndefLO = NumUndefsLO == Half;
5842 bool isUndefHI = NumUndefsHI == Half;
5843 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5844 isUndefLO, isUndefHI);
5848 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5849 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5851 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5852 X86Opcode = X86ISD::HADD;
5853 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5854 X86Opcode = X86ISD::HSUB;
5855 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5856 X86Opcode = X86ISD::FHADD;
5857 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5858 X86Opcode = X86ISD::FHSUB;
5862 // Don't try to expand this build_vector into a pair of horizontal add/sub
5863 // if we can simply emit a pair of scalar add/sub.
5864 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5867 // Convert this build_vector into two horizontal add/sub followed by
5869 bool isUndefLO = NumUndefsLO == Half;
5870 bool isUndefHI = NumUndefsHI == Half;
5871 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5872 isUndefLO, isUndefHI);
5879 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5882 MVT VT = Op.getSimpleValueType();
5883 MVT ExtVT = VT.getVectorElementType();
5884 unsigned NumElems = Op.getNumOperands();
5886 // Generate vectors for predicate vectors.
5887 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5888 return LowerBUILD_VECTORvXi1(Op, DAG);
5890 // Vectors containing all zeros can be matched by pxor and xorps later
5891 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5892 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5893 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5894 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5897 return getZeroVector(VT, Subtarget, DAG, dl);
5900 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5901 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5902 // vpcmpeqd on 256-bit vectors.
5903 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5904 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5907 if (!VT.is512BitVector())
5908 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5911 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5912 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5914 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5915 return HorizontalOp;
5916 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5919 unsigned EVTBits = ExtVT.getSizeInBits();
5921 unsigned NumZero = 0;
5922 unsigned NumNonZero = 0;
5923 unsigned NonZeros = 0;
5924 bool IsAllConstants = true;
5925 SmallSet<SDValue, 8> Values;
5926 for (unsigned i = 0; i < NumElems; ++i) {
5927 SDValue Elt = Op.getOperand(i);
5928 if (Elt.getOpcode() == ISD::UNDEF)
5931 if (Elt.getOpcode() != ISD::Constant &&
5932 Elt.getOpcode() != ISD::ConstantFP)
5933 IsAllConstants = false;
5934 if (X86::isZeroNode(Elt))
5937 NonZeros |= (1 << i);
5942 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5943 if (NumNonZero == 0)
5944 return DAG.getUNDEF(VT);
5946 // Special case for single non-zero, non-undef, element.
5947 if (NumNonZero == 1) {
5948 unsigned Idx = countTrailingZeros(NonZeros);
5949 SDValue Item = Op.getOperand(Idx);
5951 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5952 // the value are obviously zero, truncate the value to i32 and do the
5953 // insertion that way. Only do this if the value is non-constant or if the
5954 // value is a constant being inserted into element 0. It is cheaper to do
5955 // a constant pool load than it is to do a movd + shuffle.
5956 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5957 (!IsAllConstants || Idx == 0)) {
5958 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5960 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5961 EVT VecVT = MVT::v4i32;
5963 // Truncate the value (which may itself be a constant) to i32, and
5964 // convert it to a vector with movd (S2V+shuffle to zero extend).
5965 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5966 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5967 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5968 Item, Idx * 2, true, Subtarget, DAG));
5972 // If we have a constant or non-constant insertion into the low element of
5973 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5974 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5975 // depending on what the source datatype is.
5978 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5980 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5981 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5982 if (VT.is512BitVector()) {
5983 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5984 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5985 Item, DAG.getIntPtrConstant(0, dl));
5987 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5988 "Expected an SSE value type!");
5989 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5990 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5991 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5994 // We can't directly insert an i8 or i16 into a vector, so zero extend
5996 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5997 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5998 if (VT.is256BitVector()) {
5999 if (Subtarget->hasAVX()) {
6000 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6001 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6003 // Without AVX, we need to extend to a 128-bit vector and then
6004 // insert into the 256-bit vector.
6005 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6006 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6007 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6010 assert(VT.is128BitVector() && "Expected an SSE value type!");
6011 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6012 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6014 return DAG.getBitcast(VT, Item);
6018 // Is it a vector logical left shift?
6019 if (NumElems == 2 && Idx == 1 &&
6020 X86::isZeroNode(Op.getOperand(0)) &&
6021 !X86::isZeroNode(Op.getOperand(1))) {
6022 unsigned NumBits = VT.getSizeInBits();
6023 return getVShift(true, VT,
6024 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6025 VT, Op.getOperand(1)),
6026 NumBits/2, DAG, *this, dl);
6029 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6032 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6033 // is a non-constant being inserted into an element other than the low one,
6034 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6035 // movd/movss) to move this into the low element, then shuffle it into
6037 if (EVTBits == 32) {
6038 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6039 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6043 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6044 if (Values.size() == 1) {
6045 if (EVTBits == 32) {
6046 // Instead of a shuffle like this:
6047 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6048 // Check if it's possible to issue this instead.
6049 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6050 unsigned Idx = countTrailingZeros(NonZeros);
6051 SDValue Item = Op.getOperand(Idx);
6052 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6053 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6058 // A vector full of immediates; various special cases are already
6059 // handled, so this is best done with a single constant-pool load.
6063 // For AVX-length vectors, see if we can use a vector load to get all of the
6064 // elements, otherwise build the individual 128-bit pieces and use
6065 // shuffles to put them in place.
6066 if (VT.is256BitVector() || VT.is512BitVector()) {
6067 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6069 // Check for a build vector of consecutive loads.
6070 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6073 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6075 // Build both the lower and upper subvector.
6076 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6077 makeArrayRef(&V[0], NumElems/2));
6078 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6079 makeArrayRef(&V[NumElems / 2], NumElems/2));
6081 // Recreate the wider vector with the lower and upper part.
6082 if (VT.is256BitVector())
6083 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6084 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6087 // Let legalizer expand 2-wide build_vectors.
6088 if (EVTBits == 64) {
6089 if (NumNonZero == 1) {
6090 // One half is zero or undef.
6091 unsigned Idx = countTrailingZeros(NonZeros);
6092 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6093 Op.getOperand(Idx));
6094 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6099 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6100 if (EVTBits == 8 && NumElems == 16)
6101 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6105 if (EVTBits == 16 && NumElems == 8)
6106 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6110 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6111 if (EVTBits == 32 && NumElems == 4)
6112 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6115 // If element VT is == 32 bits, turn it into a number of shuffles.
6116 SmallVector<SDValue, 8> V(NumElems);
6117 if (NumElems == 4 && NumZero > 0) {
6118 for (unsigned i = 0; i < 4; ++i) {
6119 bool isZero = !(NonZeros & (1 << i));
6121 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6123 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6126 for (unsigned i = 0; i < 2; ++i) {
6127 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6130 V[i] = V[i*2]; // Must be a zero vector.
6133 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6136 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6139 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6144 bool Reverse1 = (NonZeros & 0x3) == 2;
6145 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6149 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6150 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6152 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6155 if (Values.size() > 1 && VT.is128BitVector()) {
6156 // Check for a build vector of consecutive loads.
6157 for (unsigned i = 0; i < NumElems; ++i)
6158 V[i] = Op.getOperand(i);
6160 // Check for elements which are consecutive loads.
6161 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6164 // Check for a build vector from mostly shuffle plus few inserting.
6165 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6168 // For SSE 4.1, use insertps to put the high elements into the low element.
6169 if (Subtarget->hasSSE41()) {
6171 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6172 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6174 Result = DAG.getUNDEF(VT);
6176 for (unsigned i = 1; i < NumElems; ++i) {
6177 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6178 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6179 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6184 // Otherwise, expand into a number of unpckl*, start by extending each of
6185 // our (non-undef) elements to the full vector width with the element in the
6186 // bottom slot of the vector (which generates no code for SSE).
6187 for (unsigned i = 0; i < NumElems; ++i) {
6188 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6189 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6191 V[i] = DAG.getUNDEF(VT);
6194 // Next, we iteratively mix elements, e.g. for v4f32:
6195 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6196 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6197 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6198 unsigned EltStride = NumElems >> 1;
6199 while (EltStride != 0) {
6200 for (unsigned i = 0; i < EltStride; ++i) {
6201 // If V[i+EltStride] is undef and this is the first round of mixing,
6202 // then it is safe to just drop this shuffle: V[i] is already in the
6203 // right place, the one element (since it's the first round) being
6204 // inserted as undef can be dropped. This isn't safe for successive
6205 // rounds because they will permute elements within both vectors.
6206 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6207 EltStride == NumElems/2)
6210 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6219 // 256-bit AVX can use the vinsertf128 instruction
6220 // to create 256-bit vectors from two other 128-bit ones.
6221 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6223 MVT ResVT = Op.getSimpleValueType();
6225 assert((ResVT.is256BitVector() ||
6226 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6228 SDValue V1 = Op.getOperand(0);
6229 SDValue V2 = Op.getOperand(1);
6230 unsigned NumElems = ResVT.getVectorNumElements();
6231 if (ResVT.is256BitVector())
6232 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6234 if (Op.getNumOperands() == 4) {
6235 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6236 ResVT.getVectorNumElements()/2);
6237 SDValue V3 = Op.getOperand(2);
6238 SDValue V4 = Op.getOperand(3);
6239 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6240 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6242 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6245 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6246 const X86Subtarget *Subtarget,
6247 SelectionDAG & DAG) {
6249 MVT ResVT = Op.getSimpleValueType();
6250 unsigned NumOfOperands = Op.getNumOperands();
6252 assert(isPowerOf2_32(NumOfOperands) &&
6253 "Unexpected number of operands in CONCAT_VECTORS");
6255 if (NumOfOperands > 2) {
6256 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6257 ResVT.getVectorNumElements()/2);
6258 SmallVector<SDValue, 2> Ops;
6259 for (unsigned i = 0; i < NumOfOperands/2; i++)
6260 Ops.push_back(Op.getOperand(i));
6261 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6263 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6264 Ops.push_back(Op.getOperand(i));
6265 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6266 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6269 SDValue V1 = Op.getOperand(0);
6270 SDValue V2 = Op.getOperand(1);
6271 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6272 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6274 if (IsZeroV1 && IsZeroV2)
6275 return getZeroVector(ResVT, Subtarget, DAG, dl);
6277 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6278 SDValue Undef = DAG.getUNDEF(ResVT);
6279 unsigned NumElems = ResVT.getVectorNumElements();
6280 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6282 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6283 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6287 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6288 // Zero the upper bits of V1
6289 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6290 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6293 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6296 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6297 const X86Subtarget *Subtarget,
6298 SelectionDAG &DAG) {
6299 MVT VT = Op.getSimpleValueType();
6300 if (VT.getVectorElementType() == MVT::i1)
6301 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6303 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6304 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6305 Op.getNumOperands() == 4)));
6307 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6308 // from two other 128-bit ones.
6310 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6311 return LowerAVXCONCAT_VECTORS(Op, DAG);
6315 //===----------------------------------------------------------------------===//
6316 // Vector shuffle lowering
6318 // This is an experimental code path for lowering vector shuffles on x86. It is
6319 // designed to handle arbitrary vector shuffles and blends, gracefully
6320 // degrading performance as necessary. It works hard to recognize idiomatic
6321 // shuffles and lower them to optimal instruction patterns without leaving
6322 // a framework that allows reasonably efficient handling of all vector shuffle
6324 //===----------------------------------------------------------------------===//
6326 /// \brief Tiny helper function to identify a no-op mask.
6328 /// This is a somewhat boring predicate function. It checks whether the mask
6329 /// array input, which is assumed to be a single-input shuffle mask of the kind
6330 /// used by the X86 shuffle instructions (not a fully general
6331 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6332 /// in-place shuffle are 'no-op's.
6333 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6334 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6335 if (Mask[i] != -1 && Mask[i] != i)
6340 /// \brief Helper function to classify a mask as a single-input mask.
6342 /// This isn't a generic single-input test because in the vector shuffle
6343 /// lowering we canonicalize single inputs to be the first input operand. This
6344 /// means we can more quickly test for a single input by only checking whether
6345 /// an input from the second operand exists. We also assume that the size of
6346 /// mask corresponds to the size of the input vectors which isn't true in the
6347 /// fully general case.
6348 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6350 if (M >= (int)Mask.size())
6355 /// \brief Test whether there are elements crossing 128-bit lanes in this
6358 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6359 /// and we routinely test for these.
6360 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6361 int LaneSize = 128 / VT.getScalarSizeInBits();
6362 int Size = Mask.size();
6363 for (int i = 0; i < Size; ++i)
6364 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6369 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6371 /// This checks a shuffle mask to see if it is performing the same
6372 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6373 /// that it is also not lane-crossing. It may however involve a blend from the
6374 /// same lane of a second vector.
6376 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6377 /// non-trivial to compute in the face of undef lanes. The representation is
6378 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6379 /// entries from both V1 and V2 inputs to the wider mask.
6381 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6382 SmallVectorImpl<int> &RepeatedMask) {
6383 int LaneSize = 128 / VT.getScalarSizeInBits();
6384 RepeatedMask.resize(LaneSize, -1);
6385 int Size = Mask.size();
6386 for (int i = 0; i < Size; ++i) {
6389 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6390 // This entry crosses lanes, so there is no way to model this shuffle.
6393 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6394 if (RepeatedMask[i % LaneSize] == -1)
6395 // This is the first non-undef entry in this slot of a 128-bit lane.
6396 RepeatedMask[i % LaneSize] =
6397 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6398 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6399 // Found a mismatch with the repeated mask.
6405 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6408 /// This is a fast way to test a shuffle mask against a fixed pattern:
6410 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6412 /// It returns true if the mask is exactly as wide as the argument list, and
6413 /// each element of the mask is either -1 (signifying undef) or the value given
6414 /// in the argument.
6415 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6416 ArrayRef<int> ExpectedMask) {
6417 if (Mask.size() != ExpectedMask.size())
6420 int Size = Mask.size();
6422 // If the values are build vectors, we can look through them to find
6423 // equivalent inputs that make the shuffles equivalent.
6424 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6425 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6427 for (int i = 0; i < Size; ++i)
6428 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6429 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6430 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6431 if (!MaskBV || !ExpectedBV ||
6432 MaskBV->getOperand(Mask[i] % Size) !=
6433 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6440 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6442 /// This helper function produces an 8-bit shuffle immediate corresponding to
6443 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6444 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6447 /// NB: We rely heavily on "undef" masks preserving the input lane.
6448 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6449 SelectionDAG &DAG) {
6450 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6451 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6452 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6453 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6454 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6457 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6458 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6459 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6460 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6461 return DAG.getConstant(Imm, DL, MVT::i8);
6464 /// \brief Compute whether each element of a shuffle is zeroable.
6466 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6467 /// Either it is an undef element in the shuffle mask, the element of the input
6468 /// referenced is undef, or the element of the input referenced is known to be
6469 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6470 /// as many lanes with this technique as possible to simplify the remaining
6472 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6473 SDValue V1, SDValue V2) {
6474 SmallBitVector Zeroable(Mask.size(), false);
6476 while (V1.getOpcode() == ISD::BITCAST)
6477 V1 = V1->getOperand(0);
6478 while (V2.getOpcode() == ISD::BITCAST)
6479 V2 = V2->getOperand(0);
6481 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6482 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6484 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6486 // Handle the easy cases.
6487 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6492 // If this is an index into a build_vector node (which has the same number
6493 // of elements), dig out the input value and use it.
6494 SDValue V = M < Size ? V1 : V2;
6495 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6498 SDValue Input = V.getOperand(M % Size);
6499 // The UNDEF opcode check really should be dead code here, but not quite
6500 // worth asserting on (it isn't invalid, just unexpected).
6501 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6508 /// \brief Try to emit a bitmask instruction for a shuffle.
6510 /// This handles cases where we can model a blend exactly as a bitmask due to
6511 /// one of the inputs being zeroable.
6512 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6513 SDValue V2, ArrayRef<int> Mask,
6514 SelectionDAG &DAG) {
6515 MVT EltVT = VT.getScalarType();
6516 int NumEltBits = EltVT.getSizeInBits();
6517 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6518 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6519 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6521 if (EltVT.isFloatingPoint()) {
6522 Zero = DAG.getBitcast(EltVT, Zero);
6523 AllOnes = DAG.getBitcast(EltVT, AllOnes);
6525 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6526 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6528 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6531 if (Mask[i] % Size != i)
6532 return SDValue(); // Not a blend.
6534 V = Mask[i] < Size ? V1 : V2;
6535 else if (V != (Mask[i] < Size ? V1 : V2))
6536 return SDValue(); // Can only let one input through the mask.
6538 VMaskOps[i] = AllOnes;
6541 return SDValue(); // No non-zeroable elements!
6543 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6544 V = DAG.getNode(VT.isFloatingPoint()
6545 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6550 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6552 /// This is used as a fallback approach when first class blend instructions are
6553 /// unavailable. Currently it is only suitable for integer vectors, but could
6554 /// be generalized for floating point vectors if desirable.
6555 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6556 SDValue V2, ArrayRef<int> Mask,
6557 SelectionDAG &DAG) {
6558 assert(VT.isInteger() && "Only supports integer vector types!");
6559 MVT EltVT = VT.getScalarType();
6560 int NumEltBits = EltVT.getSizeInBits();
6561 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6562 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6564 SmallVector<SDValue, 16> MaskOps;
6565 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6566 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6567 return SDValue(); // Shuffled input!
6568 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6571 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6572 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6573 // We have to cast V2 around.
6574 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6575 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6576 DAG.getBitcast(MaskVT, V1Mask),
6577 DAG.getBitcast(MaskVT, V2)));
6578 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6581 /// \brief Try to emit a blend instruction for a shuffle.
6583 /// This doesn't do any checks for the availability of instructions for blending
6584 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6585 /// be matched in the backend with the type given. What it does check for is
6586 /// that the shuffle mask is in fact a blend.
6587 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6588 SDValue V2, ArrayRef<int> Mask,
6589 const X86Subtarget *Subtarget,
6590 SelectionDAG &DAG) {
6591 unsigned BlendMask = 0;
6592 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6593 if (Mask[i] >= Size) {
6594 if (Mask[i] != i + Size)
6595 return SDValue(); // Shuffled V2 input!
6596 BlendMask |= 1u << i;
6599 if (Mask[i] >= 0 && Mask[i] != i)
6600 return SDValue(); // Shuffled V1 input!
6602 switch (VT.SimpleTy) {
6607 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6608 DAG.getConstant(BlendMask, DL, MVT::i8));
6612 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6616 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6617 // that instruction.
6618 if (Subtarget->hasAVX2()) {
6619 // Scale the blend by the number of 32-bit dwords per element.
6620 int Scale = VT.getScalarSizeInBits() / 32;
6622 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6623 if (Mask[i] >= Size)
6624 for (int j = 0; j < Scale; ++j)
6625 BlendMask |= 1u << (i * Scale + j);
6627 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6628 V1 = DAG.getBitcast(BlendVT, V1);
6629 V2 = DAG.getBitcast(BlendVT, V2);
6630 return DAG.getBitcast(
6631 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6632 DAG.getConstant(BlendMask, DL, MVT::i8)));
6636 // For integer shuffles we need to expand the mask and cast the inputs to
6637 // v8i16s prior to blending.
6638 int Scale = 8 / VT.getVectorNumElements();
6640 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6641 if (Mask[i] >= Size)
6642 for (int j = 0; j < Scale; ++j)
6643 BlendMask |= 1u << (i * Scale + j);
6645 V1 = DAG.getBitcast(MVT::v8i16, V1);
6646 V2 = DAG.getBitcast(MVT::v8i16, V2);
6647 return DAG.getBitcast(VT,
6648 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6649 DAG.getConstant(BlendMask, DL, MVT::i8)));
6653 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6654 SmallVector<int, 8> RepeatedMask;
6655 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6656 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6657 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6659 for (int i = 0; i < 8; ++i)
6660 if (RepeatedMask[i] >= 16)
6661 BlendMask |= 1u << i;
6662 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6663 DAG.getConstant(BlendMask, DL, MVT::i8));
6669 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6670 "256-bit byte-blends require AVX2 support!");
6672 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6673 if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6676 // Scale the blend by the number of bytes per element.
6677 int Scale = VT.getScalarSizeInBits() / 8;
6679 // This form of blend is always done on bytes. Compute the byte vector
6681 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6683 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6684 // mix of LLVM's code generator and the x86 backend. We tell the code
6685 // generator that boolean values in the elements of an x86 vector register
6686 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6687 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6688 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6689 // of the element (the remaining are ignored) and 0 in that high bit would
6690 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6691 // the LLVM model for boolean values in vector elements gets the relevant
6692 // bit set, it is set backwards and over constrained relative to x86's
6694 SmallVector<SDValue, 32> VSELECTMask;
6695 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6696 for (int j = 0; j < Scale; ++j)
6697 VSELECTMask.push_back(
6698 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6699 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6702 V1 = DAG.getBitcast(BlendVT, V1);
6703 V2 = DAG.getBitcast(BlendVT, V2);
6704 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6705 DAG.getNode(ISD::BUILD_VECTOR, DL,
6706 BlendVT, VSELECTMask),
6711 llvm_unreachable("Not a supported integer vector type!");
6715 /// \brief Try to lower as a blend of elements from two inputs followed by
6716 /// a single-input permutation.
6718 /// This matches the pattern where we can blend elements from two inputs and
6719 /// then reduce the shuffle to a single-input permutation.
6720 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6723 SelectionDAG &DAG) {
6724 // We build up the blend mask while checking whether a blend is a viable way
6725 // to reduce the shuffle.
6726 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6727 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6729 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6733 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6735 if (BlendMask[Mask[i] % Size] == -1)
6736 BlendMask[Mask[i] % Size] = Mask[i];
6737 else if (BlendMask[Mask[i] % Size] != Mask[i])
6738 return SDValue(); // Can't blend in the needed input!
6740 PermuteMask[i] = Mask[i] % Size;
6743 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6744 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6747 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6748 /// blends and permutes.
6750 /// This matches the extremely common pattern for handling combined
6751 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6752 /// operations. It will try to pick the best arrangement of shuffles and
6754 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6758 SelectionDAG &DAG) {
6759 // Shuffle the input elements into the desired positions in V1 and V2 and
6760 // blend them together.
6761 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6762 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6763 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6764 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6765 if (Mask[i] >= 0 && Mask[i] < Size) {
6766 V1Mask[i] = Mask[i];
6768 } else if (Mask[i] >= Size) {
6769 V2Mask[i] = Mask[i] - Size;
6770 BlendMask[i] = i + Size;
6773 // Try to lower with the simpler initial blend strategy unless one of the
6774 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6775 // shuffle may be able to fold with a load or other benefit. However, when
6776 // we'll have to do 2x as many shuffles in order to achieve this, blending
6777 // first is a better strategy.
6778 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6779 if (SDValue BlendPerm =
6780 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6783 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6784 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6785 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6788 /// \brief Try to lower a vector shuffle as a byte rotation.
6790 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6791 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6792 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6793 /// try to generically lower a vector shuffle through such an pattern. It
6794 /// does not check for the profitability of lowering either as PALIGNR or
6795 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6796 /// This matches shuffle vectors that look like:
6798 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6800 /// Essentially it concatenates V1 and V2, shifts right by some number of
6801 /// elements, and takes the low elements as the result. Note that while this is
6802 /// specified as a *right shift* because x86 is little-endian, it is a *left
6803 /// rotate* of the vector lanes.
6804 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6807 const X86Subtarget *Subtarget,
6808 SelectionDAG &DAG) {
6809 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6811 int NumElts = Mask.size();
6812 int NumLanes = VT.getSizeInBits() / 128;
6813 int NumLaneElts = NumElts / NumLanes;
6815 // We need to detect various ways of spelling a rotation:
6816 // [11, 12, 13, 14, 15, 0, 1, 2]
6817 // [-1, 12, 13, 14, -1, -1, 1, -1]
6818 // [-1, -1, -1, -1, -1, -1, 1, 2]
6819 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6820 // [-1, 4, 5, 6, -1, -1, 9, -1]
6821 // [-1, 4, 5, 6, -1, -1, -1, -1]
6824 for (int l = 0; l < NumElts; l += NumLaneElts) {
6825 for (int i = 0; i < NumLaneElts; ++i) {
6826 if (Mask[l + i] == -1)
6828 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6830 // Get the mod-Size index and lane correct it.
6831 int LaneIdx = (Mask[l + i] % NumElts) - l;
6832 // Make sure it was in this lane.
6833 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6836 // Determine where a rotated vector would have started.
6837 int StartIdx = i - LaneIdx;
6839 // The identity rotation isn't interesting, stop.
6842 // If we found the tail of a vector the rotation must be the missing
6843 // front. If we found the head of a vector, it must be how much of the
6845 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6848 Rotation = CandidateRotation;
6849 else if (Rotation != CandidateRotation)
6850 // The rotations don't match, so we can't match this mask.
6853 // Compute which value this mask is pointing at.
6854 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6856 // Compute which of the two target values this index should be assigned
6857 // to. This reflects whether the high elements are remaining or the low
6858 // elements are remaining.
6859 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6861 // Either set up this value if we've not encountered it before, or check
6862 // that it remains consistent.
6865 else if (TargetV != MaskV)
6866 // This may be a rotation, but it pulls from the inputs in some
6867 // unsupported interleaving.
6872 // Check that we successfully analyzed the mask, and normalize the results.
6873 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6874 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6880 // The actual rotate instruction rotates bytes, so we need to scale the
6881 // rotation based on how many bytes are in the vector lane.
6882 int Scale = 16 / NumLaneElts;
6884 // SSSE3 targets can use the palignr instruction.
6885 if (Subtarget->hasSSSE3()) {
6886 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6887 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6888 Lo = DAG.getBitcast(AlignVT, Lo);
6889 Hi = DAG.getBitcast(AlignVT, Hi);
6891 return DAG.getBitcast(
6892 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6893 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6896 assert(VT.getSizeInBits() == 128 &&
6897 "Rotate-based lowering only supports 128-bit lowering!");
6898 assert(Mask.size() <= 16 &&
6899 "Can shuffle at most 16 bytes in a 128-bit vector!");
6901 // Default SSE2 implementation
6902 int LoByteShift = 16 - Rotation * Scale;
6903 int HiByteShift = Rotation * Scale;
6905 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6906 Lo = DAG.getBitcast(MVT::v2i64, Lo);
6907 Hi = DAG.getBitcast(MVT::v2i64, Hi);
6909 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6910 DAG.getConstant(LoByteShift, DL, MVT::i8));
6911 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6912 DAG.getConstant(HiByteShift, DL, MVT::i8));
6913 return DAG.getBitcast(VT,
6914 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6917 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6919 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6920 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6921 /// matches elements from one of the input vectors shuffled to the left or
6922 /// right with zeroable elements 'shifted in'. It handles both the strictly
6923 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6926 /// PSHL : (little-endian) left bit shift.
6927 /// [ zz, 0, zz, 2 ]
6928 /// [ -1, 4, zz, -1 ]
6929 /// PSRL : (little-endian) right bit shift.
6931 /// [ -1, -1, 7, zz]
6932 /// PSLLDQ : (little-endian) left byte shift
6933 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6934 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6935 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6936 /// PSRLDQ : (little-endian) right byte shift
6937 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6938 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6939 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6940 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6941 SDValue V2, ArrayRef<int> Mask,
6942 SelectionDAG &DAG) {
6943 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6945 int Size = Mask.size();
6946 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6948 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6949 for (int i = 0; i < Size; i += Scale)
6950 for (int j = 0; j < Shift; ++j)
6951 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6957 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6958 for (int i = 0; i != Size; i += Scale) {
6959 unsigned Pos = Left ? i + Shift : i;
6960 unsigned Low = Left ? i : i + Shift;
6961 unsigned Len = Scale - Shift;
6962 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6963 Low + (V == V1 ? 0 : Size)))
6967 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6968 bool ByteShift = ShiftEltBits > 64;
6969 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6970 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6971 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6973 // Normalize the scale for byte shifts to still produce an i64 element
6975 Scale = ByteShift ? Scale / 2 : Scale;
6977 // We need to round trip through the appropriate type for the shift.
6978 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6979 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6980 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6981 "Illegal integer vector type");
6982 V = DAG.getBitcast(ShiftVT, V);
6984 V = DAG.getNode(OpCode, DL, ShiftVT, V,
6985 DAG.getConstant(ShiftAmt, DL, MVT::i8));
6986 return DAG.getBitcast(VT, V);
6989 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6990 // keep doubling the size of the integer elements up to that. We can
6991 // then shift the elements of the integer vector by whole multiples of
6992 // their width within the elements of the larger integer vector. Test each
6993 // multiple to see if we can find a match with the moved element indices
6994 // and that the shifted in elements are all zeroable.
6995 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6996 for (int Shift = 1; Shift != Scale; ++Shift)
6997 for (bool Left : {true, false})
6998 if (CheckZeros(Shift, Scale, Left))
6999 for (SDValue V : {V1, V2})
7000 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7007 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7008 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7009 SDValue V2, ArrayRef<int> Mask,
7010 SelectionDAG &DAG) {
7011 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7012 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7014 int Size = Mask.size();
7015 int HalfSize = Size / 2;
7016 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7018 // Upper half must be undefined.
7019 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7022 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7023 // Remainder of lower half result is zero and upper half is all undef.
7024 auto LowerAsEXTRQ = [&]() {
7025 // Determine the extraction length from the part of the
7026 // lower half that isn't zeroable.
7028 for (; Len >= 0; --Len)
7029 if (!Zeroable[Len - 1])
7031 assert(Len > 0 && "Zeroable shuffle mask");
7033 // Attempt to match first Len sequential elements from the lower half.
7036 for (int i = 0; i != Len; ++i) {
7040 SDValue &V = (M < Size ? V1 : V2);
7043 // All mask elements must be in the lower half.
7047 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7058 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7059 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7060 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7061 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7062 DAG.getConstant(BitLen, DL, MVT::i8),
7063 DAG.getConstant(BitIdx, DL, MVT::i8));
7066 if (SDValue ExtrQ = LowerAsEXTRQ())
7069 // INSERTQ: Extract lowest Len elements from lower half of second source and
7070 // insert over first source, starting at Idx.
7071 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7072 auto LowerAsInsertQ = [&]() {
7073 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7076 // Attempt to match first source from mask before insertion point.
7077 if (isUndefInRange(Mask, 0, Idx)) {
7079 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7081 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7087 // Extend the extraction length looking to match both the insertion of
7088 // the second source and the remaining elements of the first.
7089 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7094 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7096 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7102 // Match the remaining elements of the lower half.
7103 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7105 } else if ((!Base || (Base == V1)) &&
7106 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7108 } else if ((!Base || (Base == V2)) &&
7109 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7116 // We may not have a base (first source) - this can safely be undefined.
7118 Base = DAG.getUNDEF(VT);
7120 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7121 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7122 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7123 DAG.getConstant(BitLen, DL, MVT::i8),
7124 DAG.getConstant(BitIdx, DL, MVT::i8));
7131 if (SDValue InsertQ = LowerAsInsertQ())
7137 /// \brief Lower a vector shuffle as a zero or any extension.
7139 /// Given a specific number of elements, element bit width, and extension
7140 /// stride, produce either a zero or any extension based on the available
7141 /// features of the subtarget.
7142 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7143 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7144 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7145 assert(Scale > 1 && "Need a scale to extend.");
7146 int NumElements = VT.getVectorNumElements();
7147 int EltBits = VT.getScalarSizeInBits();
7148 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7149 "Only 8, 16, and 32 bit elements can be extended.");
7150 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7152 // Found a valid zext mask! Try various lowering strategies based on the
7153 // input type and available ISA extensions.
7154 if (Subtarget->hasSSE41()) {
7155 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7156 NumElements / Scale);
7157 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7160 // For any extends we can cheat for larger element sizes and use shuffle
7161 // instructions that can fold with a load and/or copy.
7162 if (AnyExt && EltBits == 32) {
7163 int PSHUFDMask[4] = {0, -1, 1, -1};
7164 return DAG.getBitcast(
7165 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7166 DAG.getBitcast(MVT::v4i32, InputV),
7167 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7169 if (AnyExt && EltBits == 16 && Scale > 2) {
7170 int PSHUFDMask[4] = {0, -1, 0, -1};
7171 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7172 DAG.getBitcast(MVT::v4i32, InputV),
7173 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7174 int PSHUFHWMask[4] = {1, -1, -1, -1};
7175 return DAG.getBitcast(
7176 VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7177 DAG.getBitcast(MVT::v8i16, InputV),
7178 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7181 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7183 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7184 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7185 assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7187 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7188 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7189 DAG.getConstant(EltBits, DL, MVT::i8),
7190 DAG.getConstant(0, DL, MVT::i8)));
7191 if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7192 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7195 DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7196 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7197 DAG.getConstant(EltBits, DL, MVT::i8),
7198 DAG.getConstant(EltBits, DL, MVT::i8)));
7199 return DAG.getNode(ISD::BITCAST, DL, VT,
7200 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7203 // If this would require more than 2 unpack instructions to expand, use
7204 // pshufb when available. We can only use more than 2 unpack instructions
7205 // when zero extending i8 elements which also makes it easier to use pshufb.
7206 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7207 assert(NumElements == 16 && "Unexpected byte vector width!");
7208 SDValue PSHUFBMask[16];
7209 for (int i = 0; i < 16; ++i)
7211 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7212 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7213 return DAG.getBitcast(VT,
7214 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7215 DAG.getNode(ISD::BUILD_VECTOR, DL,
7216 MVT::v16i8, PSHUFBMask)));
7219 // Otherwise emit a sequence of unpacks.
7221 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7222 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7223 : getZeroVector(InputVT, Subtarget, DAG, DL);
7224 InputV = DAG.getBitcast(InputVT, InputV);
7225 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7229 } while (Scale > 1);
7230 return DAG.getBitcast(VT, InputV);
7233 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7235 /// This routine will try to do everything in its power to cleverly lower
7236 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7237 /// check for the profitability of this lowering, it tries to aggressively
7238 /// match this pattern. It will use all of the micro-architectural details it
7239 /// can to emit an efficient lowering. It handles both blends with all-zero
7240 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7241 /// masking out later).
7243 /// The reason we have dedicated lowering for zext-style shuffles is that they
7244 /// are both incredibly common and often quite performance sensitive.
7245 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7246 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7247 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7248 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7250 int Bits = VT.getSizeInBits();
7251 int NumElements = VT.getVectorNumElements();
7252 assert(VT.getScalarSizeInBits() <= 32 &&
7253 "Exceeds 32-bit integer zero extension limit");
7254 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7256 // Define a helper function to check a particular ext-scale and lower to it if
7258 auto Lower = [&](int Scale) -> SDValue {
7261 for (int i = 0; i < NumElements; ++i) {
7263 continue; // Valid anywhere but doesn't tell us anything.
7264 if (i % Scale != 0) {
7265 // Each of the extended elements need to be zeroable.
7269 // We no longer are in the anyext case.
7274 // Each of the base elements needs to be consecutive indices into the
7275 // same input vector.
7276 SDValue V = Mask[i] < NumElements ? V1 : V2;
7279 else if (InputV != V)
7280 return SDValue(); // Flip-flopping inputs.
7282 if (Mask[i] % NumElements != i / Scale)
7283 return SDValue(); // Non-consecutive strided elements.
7286 // If we fail to find an input, we have a zero-shuffle which should always
7287 // have already been handled.
7288 // FIXME: Maybe handle this here in case during blending we end up with one?
7292 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7293 DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7296 // The widest scale possible for extending is to a 64-bit integer.
7297 assert(Bits % 64 == 0 &&
7298 "The number of bits in a vector must be divisible by 64 on x86!");
7299 int NumExtElements = Bits / 64;
7301 // Each iteration, try extending the elements half as much, but into twice as
7303 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7304 assert(NumElements % NumExtElements == 0 &&
7305 "The input vector size must be divisible by the extended size.");
7306 if (SDValue V = Lower(NumElements / NumExtElements))
7310 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7314 // Returns one of the source operands if the shuffle can be reduced to a
7315 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7316 auto CanZExtLowHalf = [&]() {
7317 for (int i = NumElements / 2; i != NumElements; ++i)
7320 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7322 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7327 if (SDValue V = CanZExtLowHalf()) {
7328 V = DAG.getBitcast(MVT::v2i64, V);
7329 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7330 return DAG.getBitcast(VT, V);
7333 // No viable ext lowering found.
7337 /// \brief Try to get a scalar value for a specific element of a vector.
7339 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7340 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7341 SelectionDAG &DAG) {
7342 MVT VT = V.getSimpleValueType();
7343 MVT EltVT = VT.getVectorElementType();
7344 while (V.getOpcode() == ISD::BITCAST)
7345 V = V.getOperand(0);
7346 // If the bitcasts shift the element size, we can't extract an equivalent
7348 MVT NewVT = V.getSimpleValueType();
7349 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7352 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7353 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7354 // Ensure the scalar operand is the same size as the destination.
7355 // FIXME: Add support for scalar truncation where possible.
7356 SDValue S = V.getOperand(Idx);
7357 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7358 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7364 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7366 /// This is particularly important because the set of instructions varies
7367 /// significantly based on whether the operand is a load or not.
7368 static bool isShuffleFoldableLoad(SDValue V) {
7369 while (V.getOpcode() == ISD::BITCAST)
7370 V = V.getOperand(0);
7372 return ISD::isNON_EXTLoad(V.getNode());
7375 /// \brief Try to lower insertion of a single element into a zero vector.
7377 /// This is a common pattern that we have especially efficient patterns to lower
7378 /// across all subtarget feature sets.
7379 static SDValue lowerVectorShuffleAsElementInsertion(
7380 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7381 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7382 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7384 MVT EltVT = VT.getVectorElementType();
7386 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7387 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7389 bool IsV1Zeroable = true;
7390 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7391 if (i != V2Index && !Zeroable[i]) {
7392 IsV1Zeroable = false;
7396 // Check for a single input from a SCALAR_TO_VECTOR node.
7397 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7398 // all the smarts here sunk into that routine. However, the current
7399 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7400 // vector shuffle lowering is dead.
7401 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7403 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7404 // We need to zext the scalar if it is smaller than an i32.
7405 V2S = DAG.getBitcast(EltVT, V2S);
7406 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7407 // Using zext to expand a narrow element won't work for non-zero
7412 // Zero-extend directly to i32.
7414 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7416 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7417 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7418 EltVT == MVT::i16) {
7419 // Either not inserting from the low element of the input or the input
7420 // element size is too small to use VZEXT_MOVL to clear the high bits.
7424 if (!IsV1Zeroable) {
7425 // If V1 can't be treated as a zero vector we have fewer options to lower
7426 // this. We can't support integer vectors or non-zero targets cheaply, and
7427 // the V1 elements can't be permuted in any way.
7428 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7429 if (!VT.isFloatingPoint() || V2Index != 0)
7431 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7432 V1Mask[V2Index] = -1;
7433 if (!isNoopShuffleMask(V1Mask))
7435 // This is essentially a special case blend operation, but if we have
7436 // general purpose blend operations, they are always faster. Bail and let
7437 // the rest of the lowering handle these as blends.
7438 if (Subtarget->hasSSE41())
7441 // Otherwise, use MOVSD or MOVSS.
7442 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7443 "Only two types of floating point element types to handle!");
7444 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7448 // This lowering only works for the low element with floating point vectors.
7449 if (VT.isFloatingPoint() && V2Index != 0)
7452 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7454 V2 = DAG.getBitcast(VT, V2);
7457 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7458 // the desired position. Otherwise it is more efficient to do a vector
7459 // shift left. We know that we can do a vector shift left because all
7460 // the inputs are zero.
7461 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7462 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7463 V2Shuffle[V2Index] = 0;
7464 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7466 V2 = DAG.getBitcast(MVT::v2i64, V2);
7468 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7469 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7470 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7471 DAG.getDataLayout(), VT)));
7472 V2 = DAG.getBitcast(VT, V2);
7478 /// \brief Try to lower broadcast of a single element.
7480 /// For convenience, this code also bundles all of the subtarget feature set
7481 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7482 /// a convenient way to factor it out.
7483 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7485 const X86Subtarget *Subtarget,
7486 SelectionDAG &DAG) {
7487 if (!Subtarget->hasAVX())
7489 if (VT.isInteger() && !Subtarget->hasAVX2())
7492 // Check that the mask is a broadcast.
7493 int BroadcastIdx = -1;
7495 if (M >= 0 && BroadcastIdx == -1)
7497 else if (M >= 0 && M != BroadcastIdx)
7500 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7501 "a sorted mask where the broadcast "
7504 // Go up the chain of (vector) values to find a scalar load that we can
7505 // combine with the broadcast.
7507 switch (V.getOpcode()) {
7508 case ISD::CONCAT_VECTORS: {
7509 int OperandSize = Mask.size() / V.getNumOperands();
7510 V = V.getOperand(BroadcastIdx / OperandSize);
7511 BroadcastIdx %= OperandSize;
7515 case ISD::INSERT_SUBVECTOR: {
7516 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7517 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7521 int BeginIdx = (int)ConstantIdx->getZExtValue();
7523 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7524 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7525 BroadcastIdx -= BeginIdx;
7536 // Check if this is a broadcast of a scalar. We special case lowering
7537 // for scalars so that we can more effectively fold with loads.
7538 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7539 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7540 V = V.getOperand(BroadcastIdx);
7542 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7543 // Only AVX2 has register broadcasts.
7544 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7546 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7547 // We can't broadcast from a vector register without AVX2, and we can only
7548 // broadcast from the zero-element of a vector register.
7552 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7555 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7556 // INSERTPS when the V1 elements are already in the correct locations
7557 // because otherwise we can just always use two SHUFPS instructions which
7558 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7559 // perform INSERTPS if a single V1 element is out of place and all V2
7560 // elements are zeroable.
7561 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7563 SelectionDAG &DAG) {
7564 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7565 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7566 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7567 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7569 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7572 int V1DstIndex = -1;
7573 int V2DstIndex = -1;
7574 bool V1UsedInPlace = false;
7576 for (int i = 0; i < 4; ++i) {
7577 // Synthesize a zero mask from the zeroable elements (includes undefs).
7583 // Flag if we use any V1 inputs in place.
7585 V1UsedInPlace = true;
7589 // We can only insert a single non-zeroable element.
7590 if (V1DstIndex != -1 || V2DstIndex != -1)
7594 // V1 input out of place for insertion.
7597 // V2 input for insertion.
7602 // Don't bother if we have no (non-zeroable) element for insertion.
7603 if (V1DstIndex == -1 && V2DstIndex == -1)
7606 // Determine element insertion src/dst indices. The src index is from the
7607 // start of the inserted vector, not the start of the concatenated vector.
7608 unsigned V2SrcIndex = 0;
7609 if (V1DstIndex != -1) {
7610 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7611 // and don't use the original V2 at all.
7612 V2SrcIndex = Mask[V1DstIndex];
7613 V2DstIndex = V1DstIndex;
7616 V2SrcIndex = Mask[V2DstIndex] - 4;
7619 // If no V1 inputs are used in place, then the result is created only from
7620 // the zero mask and the V2 insertion - so remove V1 dependency.
7622 V1 = DAG.getUNDEF(MVT::v4f32);
7624 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7625 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7627 // Insert the V2 element into the desired position.
7629 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7630 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7633 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7634 /// UNPCK instruction.
7636 /// This specifically targets cases where we end up with alternating between
7637 /// the two inputs, and so can permute them into something that feeds a single
7638 /// UNPCK instruction. Note that this routine only targets integer vectors
7639 /// because for floating point vectors we have a generalized SHUFPS lowering
7640 /// strategy that handles everything that doesn't *exactly* match an unpack,
7641 /// making this clever lowering unnecessary.
7642 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7643 SDValue V2, ArrayRef<int> Mask,
7644 SelectionDAG &DAG) {
7645 assert(!VT.isFloatingPoint() &&
7646 "This routine only supports integer vectors.");
7647 assert(!isSingleInputShuffleMask(Mask) &&
7648 "This routine should only be used when blending two inputs.");
7649 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7651 int Size = Mask.size();
7653 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7654 return M >= 0 && M % Size < Size / 2;
7656 int NumHiInputs = std::count_if(
7657 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7659 bool UnpackLo = NumLoInputs >= NumHiInputs;
7661 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7662 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7663 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7665 for (int i = 0; i < Size; ++i) {
7669 // Each element of the unpack contains Scale elements from this mask.
7670 int UnpackIdx = i / Scale;
7672 // We only handle the case where V1 feeds the first slots of the unpack.
7673 // We rely on canonicalization to ensure this is the case.
7674 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7677 // Setup the mask for this input. The indexing is tricky as we have to
7678 // handle the unpack stride.
7679 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7680 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7684 // If we will have to shuffle both inputs to use the unpack, check whether
7685 // we can just unpack first and shuffle the result. If so, skip this unpack.
7686 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7687 !isNoopShuffleMask(V2Mask))
7690 // Shuffle the inputs into place.
7691 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7692 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7694 // Cast the inputs to the type we will use to unpack them.
7695 V1 = DAG.getBitcast(UnpackVT, V1);
7696 V2 = DAG.getBitcast(UnpackVT, V2);
7698 // Unpack the inputs and cast the result back to the desired type.
7699 return DAG.getBitcast(
7700 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7704 // We try each unpack from the largest to the smallest to try and find one
7705 // that fits this mask.
7706 int OrigNumElements = VT.getVectorNumElements();
7707 int OrigScalarSize = VT.getScalarSizeInBits();
7708 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7709 int Scale = ScalarSize / OrigScalarSize;
7710 int NumElements = OrigNumElements / Scale;
7711 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7712 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7716 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7718 if (NumLoInputs == 0 || NumHiInputs == 0) {
7719 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7720 "We have to have *some* inputs!");
7721 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7723 // FIXME: We could consider the total complexity of the permute of each
7724 // possible unpacking. Or at the least we should consider how many
7725 // half-crossings are created.
7726 // FIXME: We could consider commuting the unpacks.
7728 SmallVector<int, 32> PermMask;
7729 PermMask.assign(Size, -1);
7730 for (int i = 0; i < Size; ++i) {
7734 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7737 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7739 return DAG.getVectorShuffle(
7740 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7742 DAG.getUNDEF(VT), PermMask);
7748 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7750 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7751 /// support for floating point shuffles but not integer shuffles. These
7752 /// instructions will incur a domain crossing penalty on some chips though so
7753 /// it is better to avoid lowering through this for integer vectors where
7755 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7756 const X86Subtarget *Subtarget,
7757 SelectionDAG &DAG) {
7759 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7760 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7761 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7762 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7763 ArrayRef<int> Mask = SVOp->getMask();
7764 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7766 if (isSingleInputShuffleMask(Mask)) {
7767 // Use low duplicate instructions for masks that match their pattern.
7768 if (Subtarget->hasSSE3())
7769 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7770 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7772 // Straight shuffle of a single input vector. Simulate this by using the
7773 // single input as both of the "inputs" to this instruction..
7774 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7776 if (Subtarget->hasAVX()) {
7777 // If we have AVX, we can use VPERMILPS which will allow folding a load
7778 // into the shuffle.
7779 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7780 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7783 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7784 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7786 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7787 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7789 // If we have a single input, insert that into V1 if we can do so cheaply.
7790 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7791 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7792 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7794 // Try inverting the insertion since for v2 masks it is easy to do and we
7795 // can't reliably sort the mask one way or the other.
7796 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7797 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7798 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7799 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7803 // Try to use one of the special instruction patterns to handle two common
7804 // blend patterns if a zero-blend above didn't work.
7805 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7806 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7807 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7808 // We can either use a special instruction to load over the low double or
7809 // to move just the low double.
7811 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7813 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7815 if (Subtarget->hasSSE41())
7816 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7820 // Use dedicated unpack instructions for masks that match their pattern.
7821 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7822 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7823 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7824 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7826 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7827 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7828 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7831 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7833 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7834 /// the integer unit to minimize domain crossing penalties. However, for blends
7835 /// it falls back to the floating point shuffle operation with appropriate bit
7837 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7838 const X86Subtarget *Subtarget,
7839 SelectionDAG &DAG) {
7841 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7842 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7843 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7844 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7845 ArrayRef<int> Mask = SVOp->getMask();
7846 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7848 if (isSingleInputShuffleMask(Mask)) {
7849 // Check for being able to broadcast a single element.
7850 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7851 Mask, Subtarget, DAG))
7854 // Straight shuffle of a single input vector. For everything from SSE2
7855 // onward this has a single fast instruction with no scary immediates.
7856 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7857 V1 = DAG.getBitcast(MVT::v4i32, V1);
7858 int WidenedMask[4] = {
7859 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7860 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7861 return DAG.getBitcast(
7863 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7864 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7866 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7867 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7868 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7869 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7871 // If we have a blend of two PACKUS operations an the blend aligns with the
7872 // low and half halves, we can just merge the PACKUS operations. This is
7873 // particularly important as it lets us merge shuffles that this routine itself
7875 auto GetPackNode = [](SDValue V) {
7876 while (V.getOpcode() == ISD::BITCAST)
7877 V = V.getOperand(0);
7879 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7881 if (SDValue V1Pack = GetPackNode(V1))
7882 if (SDValue V2Pack = GetPackNode(V2))
7883 return DAG.getBitcast(MVT::v2i64,
7884 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7885 Mask[0] == 0 ? V1Pack.getOperand(0)
7886 : V1Pack.getOperand(1),
7887 Mask[1] == 2 ? V2Pack.getOperand(0)
7888 : V2Pack.getOperand(1)));
7890 // Try to use shift instructions.
7892 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7895 // When loading a scalar and then shuffling it into a vector we can often do
7896 // the insertion cheaply.
7897 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7898 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7900 // Try inverting the insertion since for v2 masks it is easy to do and we
7901 // can't reliably sort the mask one way or the other.
7902 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7903 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7904 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7907 // We have different paths for blend lowering, but they all must use the
7908 // *exact* same predicate.
7909 bool IsBlendSupported = Subtarget->hasSSE41();
7910 if (IsBlendSupported)
7911 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7915 // Use dedicated unpack instructions for masks that match their pattern.
7916 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7917 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7918 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7919 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7921 // Try to use byte rotation instructions.
7922 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7923 if (Subtarget->hasSSSE3())
7924 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7925 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7928 // If we have direct support for blends, we should lower by decomposing into
7929 // a permute. That will be faster than the domain cross.
7930 if (IsBlendSupported)
7931 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7934 // We implement this with SHUFPD which is pretty lame because it will likely
7935 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7936 // However, all the alternatives are still more cycles and newer chips don't
7937 // have this problem. It would be really nice if x86 had better shuffles here.
7938 V1 = DAG.getBitcast(MVT::v2f64, V1);
7939 V2 = DAG.getBitcast(MVT::v2f64, V2);
7940 return DAG.getBitcast(MVT::v2i64,
7941 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7944 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7946 /// This is used to disable more specialized lowerings when the shufps lowering
7947 /// will happen to be efficient.
7948 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7949 // This routine only handles 128-bit shufps.
7950 assert(Mask.size() == 4 && "Unsupported mask size!");
7952 // To lower with a single SHUFPS we need to have the low half and high half
7953 // each requiring a single input.
7954 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7956 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7962 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7964 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7965 /// It makes no assumptions about whether this is the *best* lowering, it simply
7967 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7968 ArrayRef<int> Mask, SDValue V1,
7969 SDValue V2, SelectionDAG &DAG) {
7970 SDValue LowV = V1, HighV = V2;
7971 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7974 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7976 if (NumV2Elements == 1) {
7978 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7981 // Compute the index adjacent to V2Index and in the same half by toggling
7983 int V2AdjIndex = V2Index ^ 1;
7985 if (Mask[V2AdjIndex] == -1) {
7986 // Handles all the cases where we have a single V2 element and an undef.
7987 // This will only ever happen in the high lanes because we commute the
7988 // vector otherwise.
7990 std::swap(LowV, HighV);
7991 NewMask[V2Index] -= 4;
7993 // Handle the case where the V2 element ends up adjacent to a V1 element.
7994 // To make this work, blend them together as the first step.
7995 int V1Index = V2AdjIndex;
7996 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7997 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7998 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8000 // Now proceed to reconstruct the final blend as we have the necessary
8001 // high or low half formed.
8008 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8009 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8011 } else if (NumV2Elements == 2) {
8012 if (Mask[0] < 4 && Mask[1] < 4) {
8013 // Handle the easy case where we have V1 in the low lanes and V2 in the
8017 } else if (Mask[2] < 4 && Mask[3] < 4) {
8018 // We also handle the reversed case because this utility may get called
8019 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8020 // arrange things in the right direction.
8026 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8027 // trying to place elements directly, just blend them and set up the final
8028 // shuffle to place them.
8030 // The first two blend mask elements are for V1, the second two are for
8032 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8033 Mask[2] < 4 ? Mask[2] : Mask[3],
8034 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8035 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8036 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8037 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8039 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8042 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8043 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8044 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8045 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8048 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8049 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8052 /// \brief Lower 4-lane 32-bit floating point shuffles.
8054 /// Uses instructions exclusively from the floating point unit to minimize
8055 /// domain crossing penalties, as these are sufficient to implement all v4f32
8057 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8058 const X86Subtarget *Subtarget,
8059 SelectionDAG &DAG) {
8061 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8062 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8063 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8064 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8065 ArrayRef<int> Mask = SVOp->getMask();
8066 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8069 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8071 if (NumV2Elements == 0) {
8072 // Check for being able to broadcast a single element.
8073 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8074 Mask, Subtarget, DAG))
8077 // Use even/odd duplicate instructions for masks that match their pattern.
8078 if (Subtarget->hasSSE3()) {
8079 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8080 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8081 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8082 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8085 if (Subtarget->hasAVX()) {
8086 // If we have AVX, we can use VPERMILPS which will allow folding a load
8087 // into the shuffle.
8088 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8089 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8092 // Otherwise, use a straight shuffle of a single input vector. We pass the
8093 // input vector to both operands to simulate this with a SHUFPS.
8094 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8095 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8098 // There are special ways we can lower some single-element blends. However, we
8099 // have custom ways we can lower more complex single-element blends below that
8100 // we defer to if both this and BLENDPS fail to match, so restrict this to
8101 // when the V2 input is targeting element 0 of the mask -- that is the fast
8103 if (NumV2Elements == 1 && Mask[0] >= 4)
8104 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8105 Mask, Subtarget, DAG))
8108 if (Subtarget->hasSSE41()) {
8109 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8113 // Use INSERTPS if we can complete the shuffle efficiently.
8114 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8117 if (!isSingleSHUFPSMask(Mask))
8118 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8119 DL, MVT::v4f32, V1, V2, Mask, DAG))
8123 // Use dedicated unpack instructions for masks that match their pattern.
8124 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8125 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8126 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8127 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8128 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8129 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8130 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8131 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8133 // Otherwise fall back to a SHUFPS lowering strategy.
8134 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8137 /// \brief Lower 4-lane i32 vector shuffles.
8139 /// We try to handle these with integer-domain shuffles where we can, but for
8140 /// blends we use the floating point domain blend instructions.
8141 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8142 const X86Subtarget *Subtarget,
8143 SelectionDAG &DAG) {
8145 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8146 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8147 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8148 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8149 ArrayRef<int> Mask = SVOp->getMask();
8150 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8152 // Whenever we can lower this as a zext, that instruction is strictly faster
8153 // than any alternative. It also allows us to fold memory operands into the
8154 // shuffle in many cases.
8155 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8156 Mask, Subtarget, DAG))
8160 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8162 if (NumV2Elements == 0) {
8163 // Check for being able to broadcast a single element.
8164 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8165 Mask, Subtarget, DAG))
8168 // Straight shuffle of a single input vector. For everything from SSE2
8169 // onward this has a single fast instruction with no scary immediates.
8170 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8171 // but we aren't actually going to use the UNPCK instruction because doing
8172 // so prevents folding a load into this instruction or making a copy.
8173 const int UnpackLoMask[] = {0, 0, 1, 1};
8174 const int UnpackHiMask[] = {2, 2, 3, 3};
8175 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8176 Mask = UnpackLoMask;
8177 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8178 Mask = UnpackHiMask;
8180 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8181 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8184 // Try to use shift instructions.
8186 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8189 // There are special ways we can lower some single-element blends.
8190 if (NumV2Elements == 1)
8191 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8192 Mask, Subtarget, DAG))
8195 // We have different paths for blend lowering, but they all must use the
8196 // *exact* same predicate.
8197 bool IsBlendSupported = Subtarget->hasSSE41();
8198 if (IsBlendSupported)
8199 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8203 if (SDValue Masked =
8204 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8207 // Use dedicated unpack instructions for masks that match their pattern.
8208 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8209 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8210 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8211 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8212 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8213 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8214 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8215 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8217 // Try to use byte rotation instructions.
8218 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8219 if (Subtarget->hasSSSE3())
8220 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8221 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8224 // If we have direct support for blends, we should lower by decomposing into
8225 // a permute. That will be faster than the domain cross.
8226 if (IsBlendSupported)
8227 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8230 // Try to lower by permuting the inputs into an unpack instruction.
8231 if (SDValue Unpack =
8232 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8235 // We implement this with SHUFPS because it can blend from two vectors.
8236 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8237 // up the inputs, bypassing domain shift penalties that we would encur if we
8238 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8240 return DAG.getBitcast(
8242 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8243 DAG.getBitcast(MVT::v4f32, V2), Mask));
8246 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8247 /// shuffle lowering, and the most complex part.
8249 /// The lowering strategy is to try to form pairs of input lanes which are
8250 /// targeted at the same half of the final vector, and then use a dword shuffle
8251 /// to place them onto the right half, and finally unpack the paired lanes into
8252 /// their final position.
8254 /// The exact breakdown of how to form these dword pairs and align them on the
8255 /// correct sides is really tricky. See the comments within the function for
8256 /// more of the details.
8258 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8259 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8260 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8261 /// vector, form the analogous 128-bit 8-element Mask.
8262 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8263 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8264 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8265 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8266 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8268 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8269 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8270 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8272 SmallVector<int, 4> LoInputs;
8273 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8274 [](int M) { return M >= 0; });
8275 std::sort(LoInputs.begin(), LoInputs.end());
8276 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8277 SmallVector<int, 4> HiInputs;
8278 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8279 [](int M) { return M >= 0; });
8280 std::sort(HiInputs.begin(), HiInputs.end());
8281 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8283 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8284 int NumHToL = LoInputs.size() - NumLToL;
8286 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8287 int NumHToH = HiInputs.size() - NumLToH;
8288 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8289 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8290 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8291 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8293 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8294 // such inputs we can swap two of the dwords across the half mark and end up
8295 // with <=2 inputs to each half in each half. Once there, we can fall through
8296 // to the generic code below. For example:
8298 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8299 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8301 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8302 // and an existing 2-into-2 on the other half. In this case we may have to
8303 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8304 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8305 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8306 // because any other situation (including a 3-into-1 or 1-into-3 in the other
8307 // half than the one we target for fixing) will be fixed when we re-enter this
8308 // path. We will also combine away any sequence of PSHUFD instructions that
8309 // result into a single instruction. Here is an example of the tricky case:
8311 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8312 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8314 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8316 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8317 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8319 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8320 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8322 // The result is fine to be handled by the generic logic.
8323 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8324 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8325 int AOffset, int BOffset) {
8326 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8327 "Must call this with A having 3 or 1 inputs from the A half.");
8328 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8329 "Must call this with B having 1 or 3 inputs from the B half.");
8330 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8331 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8333 // Compute the index of dword with only one word among the three inputs in
8334 // a half by taking the sum of the half with three inputs and subtracting
8335 // the sum of the actual three inputs. The difference is the remaining
8338 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8339 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8340 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8341 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8342 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8343 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8344 int TripleNonInputIdx =
8345 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8346 TripleDWord = TripleNonInputIdx / 2;
8348 // We use xor with one to compute the adjacent DWord to whichever one the
8350 OneInputDWord = (OneInput / 2) ^ 1;
8352 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8353 // and BToA inputs. If there is also such a problem with the BToB and AToB
8354 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8355 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8356 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8357 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8358 // Compute how many inputs will be flipped by swapping these DWords. We
8360 // to balance this to ensure we don't form a 3-1 shuffle in the other
8362 int NumFlippedAToBInputs =
8363 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8364 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8365 int NumFlippedBToBInputs =
8366 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8367 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8368 if ((NumFlippedAToBInputs == 1 &&
8369 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8370 (NumFlippedBToBInputs == 1 &&
8371 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8372 // We choose whether to fix the A half or B half based on whether that
8373 // half has zero flipped inputs. At zero, we may not be able to fix it
8374 // with that half. We also bias towards fixing the B half because that
8375 // will more commonly be the high half, and we have to bias one way.
8376 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8377 ArrayRef<int> Inputs) {
8378 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8379 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8380 PinnedIdx ^ 1) != Inputs.end();
8381 // Determine whether the free index is in the flipped dword or the
8382 // unflipped dword based on where the pinned index is. We use this bit
8383 // in an xor to conditionally select the adjacent dword.
8384 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8385 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8386 FixFreeIdx) != Inputs.end();
8387 if (IsFixIdxInput == IsFixFreeIdxInput)
8389 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8390 FixFreeIdx) != Inputs.end();
8391 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8392 "We need to be changing the number of flipped inputs!");
8393 int PSHUFHalfMask[] = {0, 1, 2, 3};
8394 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8395 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8397 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8400 if (M != -1 && M == FixIdx)
8402 else if (M != -1 && M == FixFreeIdx)
8405 if (NumFlippedBToBInputs != 0) {
8407 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8408 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8410 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8412 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8413 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8418 int PSHUFDMask[] = {0, 1, 2, 3};
8419 PSHUFDMask[ADWord] = BDWord;
8420 PSHUFDMask[BDWord] = ADWord;
8423 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8424 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8426 // Adjust the mask to match the new locations of A and B.
8428 if (M != -1 && M/2 == ADWord)
8429 M = 2 * BDWord + M % 2;
8430 else if (M != -1 && M/2 == BDWord)
8431 M = 2 * ADWord + M % 2;
8433 // Recurse back into this routine to re-compute state now that this isn't
8434 // a 3 and 1 problem.
8435 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8438 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8439 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8440 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8441 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8443 // At this point there are at most two inputs to the low and high halves from
8444 // each half. That means the inputs can always be grouped into dwords and
8445 // those dwords can then be moved to the correct half with a dword shuffle.
8446 // We use at most one low and one high word shuffle to collect these paired
8447 // inputs into dwords, and finally a dword shuffle to place them.
8448 int PSHUFLMask[4] = {-1, -1, -1, -1};
8449 int PSHUFHMask[4] = {-1, -1, -1, -1};
8450 int PSHUFDMask[4] = {-1, -1, -1, -1};
8452 // First fix the masks for all the inputs that are staying in their
8453 // original halves. This will then dictate the targets of the cross-half
8455 auto fixInPlaceInputs =
8456 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8457 MutableArrayRef<int> SourceHalfMask,
8458 MutableArrayRef<int> HalfMask, int HalfOffset) {
8459 if (InPlaceInputs.empty())
8461 if (InPlaceInputs.size() == 1) {
8462 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8463 InPlaceInputs[0] - HalfOffset;
8464 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8467 if (IncomingInputs.empty()) {
8468 // Just fix all of the in place inputs.
8469 for (int Input : InPlaceInputs) {
8470 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8471 PSHUFDMask[Input / 2] = Input / 2;
8476 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8477 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8478 InPlaceInputs[0] - HalfOffset;
8479 // Put the second input next to the first so that they are packed into
8480 // a dword. We find the adjacent index by toggling the low bit.
8481 int AdjIndex = InPlaceInputs[0] ^ 1;
8482 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8483 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8484 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8486 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8487 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8489 // Now gather the cross-half inputs and place them into a free dword of
8490 // their target half.
8491 // FIXME: This operation could almost certainly be simplified dramatically to
8492 // look more like the 3-1 fixing operation.
8493 auto moveInputsToRightHalf = [&PSHUFDMask](
8494 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8495 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8496 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8498 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8499 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8501 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8503 int LowWord = Word & ~1;
8504 int HighWord = Word | 1;
8505 return isWordClobbered(SourceHalfMask, LowWord) ||
8506 isWordClobbered(SourceHalfMask, HighWord);
8509 if (IncomingInputs.empty())
8512 if (ExistingInputs.empty()) {
8513 // Map any dwords with inputs from them into the right half.
8514 for (int Input : IncomingInputs) {
8515 // If the source half mask maps over the inputs, turn those into
8516 // swaps and use the swapped lane.
8517 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8518 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8519 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8520 Input - SourceOffset;
8521 // We have to swap the uses in our half mask in one sweep.
8522 for (int &M : HalfMask)
8523 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8525 else if (M == Input)
8526 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8528 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8529 Input - SourceOffset &&
8530 "Previous placement doesn't match!");
8532 // Note that this correctly re-maps both when we do a swap and when
8533 // we observe the other side of the swap above. We rely on that to
8534 // avoid swapping the members of the input list directly.
8535 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8538 // Map the input's dword into the correct half.
8539 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8540 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8542 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8544 "Previous placement doesn't match!");
8547 // And just directly shift any other-half mask elements to be same-half
8548 // as we will have mirrored the dword containing the element into the
8549 // same position within that half.
8550 for (int &M : HalfMask)
8551 if (M >= SourceOffset && M < SourceOffset + 4) {
8552 M = M - SourceOffset + DestOffset;
8553 assert(M >= 0 && "This should never wrap below zero!");
8558 // Ensure we have the input in a viable dword of its current half. This
8559 // is particularly tricky because the original position may be clobbered
8560 // by inputs being moved and *staying* in that half.
8561 if (IncomingInputs.size() == 1) {
8562 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8563 int InputFixed = std::find(std::begin(SourceHalfMask),
8564 std::end(SourceHalfMask), -1) -
8565 std::begin(SourceHalfMask) + SourceOffset;
8566 SourceHalfMask[InputFixed - SourceOffset] =
8567 IncomingInputs[0] - SourceOffset;
8568 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8570 IncomingInputs[0] = InputFixed;
8572 } else if (IncomingInputs.size() == 2) {
8573 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8574 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8575 // We have two non-adjacent or clobbered inputs we need to extract from
8576 // the source half. To do this, we need to map them into some adjacent
8577 // dword slot in the source mask.
8578 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8579 IncomingInputs[1] - SourceOffset};
8581 // If there is a free slot in the source half mask adjacent to one of
8582 // the inputs, place the other input in it. We use (Index XOR 1) to
8583 // compute an adjacent index.
8584 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8585 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8586 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8587 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8588 InputsFixed[1] = InputsFixed[0] ^ 1;
8589 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8590 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8591 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8592 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8593 InputsFixed[0] = InputsFixed[1] ^ 1;
8594 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8595 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8596 // The two inputs are in the same DWord but it is clobbered and the
8597 // adjacent DWord isn't used at all. Move both inputs to the free
8599 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8600 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8601 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8602 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8604 // The only way we hit this point is if there is no clobbering
8605 // (because there are no off-half inputs to this half) and there is no
8606 // free slot adjacent to one of the inputs. In this case, we have to
8607 // swap an input with a non-input.
8608 for (int i = 0; i < 4; ++i)
8609 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8610 "We can't handle any clobbers here!");
8611 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8612 "Cannot have adjacent inputs here!");
8614 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8615 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8617 // We also have to update the final source mask in this case because
8618 // it may need to undo the above swap.
8619 for (int &M : FinalSourceHalfMask)
8620 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8621 M = InputsFixed[1] + SourceOffset;
8622 else if (M == InputsFixed[1] + SourceOffset)
8623 M = (InputsFixed[0] ^ 1) + SourceOffset;
8625 InputsFixed[1] = InputsFixed[0] ^ 1;
8628 // Point everything at the fixed inputs.
8629 for (int &M : HalfMask)
8630 if (M == IncomingInputs[0])
8631 M = InputsFixed[0] + SourceOffset;
8632 else if (M == IncomingInputs[1])
8633 M = InputsFixed[1] + SourceOffset;
8635 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8636 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8639 llvm_unreachable("Unhandled input size!");
8642 // Now hoist the DWord down to the right half.
8643 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8644 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8645 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8646 for (int &M : HalfMask)
8647 for (int Input : IncomingInputs)
8649 M = FreeDWord * 2 + Input % 2;
8651 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8652 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8653 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8654 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8656 // Now enact all the shuffles we've computed to move the inputs into their
8658 if (!isNoopShuffleMask(PSHUFLMask))
8659 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8660 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8661 if (!isNoopShuffleMask(PSHUFHMask))
8662 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8663 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8664 if (!isNoopShuffleMask(PSHUFDMask))
8667 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8668 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8670 // At this point, each half should contain all its inputs, and we can then
8671 // just shuffle them into their final position.
8672 assert(std::count_if(LoMask.begin(), LoMask.end(),
8673 [](int M) { return M >= 4; }) == 0 &&
8674 "Failed to lift all the high half inputs to the low mask!");
8675 assert(std::count_if(HiMask.begin(), HiMask.end(),
8676 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8677 "Failed to lift all the low half inputs to the high mask!");
8679 // Do a half shuffle for the low mask.
8680 if (!isNoopShuffleMask(LoMask))
8681 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8682 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8684 // Do a half shuffle with the high mask after shifting its values down.
8685 for (int &M : HiMask)
8688 if (!isNoopShuffleMask(HiMask))
8689 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8690 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8695 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8696 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8697 SDValue V2, ArrayRef<int> Mask,
8698 SelectionDAG &DAG, bool &V1InUse,
8700 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8706 int Size = Mask.size();
8707 int Scale = 16 / Size;
8708 for (int i = 0; i < 16; ++i) {
8709 if (Mask[i / Scale] == -1) {
8710 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8712 const int ZeroMask = 0x80;
8713 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8715 int V2Idx = Mask[i / Scale] < Size
8717 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8718 if (Zeroable[i / Scale])
8719 V1Idx = V2Idx = ZeroMask;
8720 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8721 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8722 V1InUse |= (ZeroMask != V1Idx);
8723 V2InUse |= (ZeroMask != V2Idx);
8728 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8729 DAG.getBitcast(MVT::v16i8, V1),
8730 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8732 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8733 DAG.getBitcast(MVT::v16i8, V2),
8734 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8736 // If we need shuffled inputs from both, blend the two.
8738 if (V1InUse && V2InUse)
8739 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8741 V = V1InUse ? V1 : V2;
8743 // Cast the result back to the correct type.
8744 return DAG.getBitcast(VT, V);
8747 /// \brief Generic lowering of 8-lane i16 shuffles.
8749 /// This handles both single-input shuffles and combined shuffle/blends with
8750 /// two inputs. The single input shuffles are immediately delegated to
8751 /// a dedicated lowering routine.
8753 /// The blends are lowered in one of three fundamental ways. If there are few
8754 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8755 /// of the input is significantly cheaper when lowered as an interleaving of
8756 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8757 /// halves of the inputs separately (making them have relatively few inputs)
8758 /// and then concatenate them.
8759 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8760 const X86Subtarget *Subtarget,
8761 SelectionDAG &DAG) {
8763 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8764 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8765 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8766 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8767 ArrayRef<int> OrigMask = SVOp->getMask();
8768 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8769 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8770 MutableArrayRef<int> Mask(MaskStorage);
8772 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8774 // Whenever we can lower this as a zext, that instruction is strictly faster
8775 // than any alternative.
8776 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8777 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8780 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8782 auto isV2 = [](int M) { return M >= 8; };
8784 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8786 if (NumV2Inputs == 0) {
8787 // Check for being able to broadcast a single element.
8788 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8789 Mask, Subtarget, DAG))
8792 // Try to use shift instructions.
8794 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8797 // Use dedicated unpack instructions for masks that match their pattern.
8798 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8799 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8800 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8801 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8803 // Try to use byte rotation instructions.
8804 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8805 Mask, Subtarget, DAG))
8808 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8812 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8813 "All single-input shuffles should be canonicalized to be V1-input "
8816 // Try to use shift instructions.
8818 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8821 // See if we can use SSE4A Extraction / Insertion.
8822 if (Subtarget->hasSSE4A())
8823 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8826 // There are special ways we can lower some single-element blends.
8827 if (NumV2Inputs == 1)
8828 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8829 Mask, Subtarget, DAG))
8832 // We have different paths for blend lowering, but they all must use the
8833 // *exact* same predicate.
8834 bool IsBlendSupported = Subtarget->hasSSE41();
8835 if (IsBlendSupported)
8836 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8840 if (SDValue Masked =
8841 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8844 // Use dedicated unpack instructions for masks that match their pattern.
8845 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8846 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8847 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8848 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8850 // Try to use byte rotation instructions.
8851 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8852 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8855 if (SDValue BitBlend =
8856 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8859 if (SDValue Unpack =
8860 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8863 // If we can't directly blend but can use PSHUFB, that will be better as it
8864 // can both shuffle and set up the inefficient blend.
8865 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8866 bool V1InUse, V2InUse;
8867 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8871 // We can always bit-blend if we have to so the fallback strategy is to
8872 // decompose into single-input permutes and blends.
8873 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8877 /// \brief Check whether a compaction lowering can be done by dropping even
8878 /// elements and compute how many times even elements must be dropped.
8880 /// This handles shuffles which take every Nth element where N is a power of
8881 /// two. Example shuffle masks:
8883 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8884 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8885 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8886 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8887 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8888 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8890 /// Any of these lanes can of course be undef.
8892 /// This routine only supports N <= 3.
8893 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8896 /// \returns N above, or the number of times even elements must be dropped if
8897 /// there is such a number. Otherwise returns zero.
8898 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8899 // Figure out whether we're looping over two inputs or just one.
8900 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8902 // The modulus for the shuffle vector entries is based on whether this is
8903 // a single input or not.
8904 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8905 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8906 "We should only be called with masks with a power-of-2 size!");
8908 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8910 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8911 // and 2^3 simultaneously. This is because we may have ambiguity with
8912 // partially undef inputs.
8913 bool ViableForN[3] = {true, true, true};
8915 for (int i = 0, e = Mask.size(); i < e; ++i) {
8916 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8921 bool IsAnyViable = false;
8922 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8923 if (ViableForN[j]) {
8926 // The shuffle mask must be equal to (i * 2^N) % M.
8927 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8930 ViableForN[j] = false;
8932 // Early exit if we exhaust the possible powers of two.
8937 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8941 // Return 0 as there is no viable power of two.
8945 /// \brief Generic lowering of v16i8 shuffles.
8947 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8948 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8949 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8950 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8952 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8953 const X86Subtarget *Subtarget,
8954 SelectionDAG &DAG) {
8956 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8957 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8958 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8959 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8960 ArrayRef<int> Mask = SVOp->getMask();
8961 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8963 // Try to use shift instructions.
8965 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8968 // Try to use byte rotation instructions.
8969 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8970 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8973 // Try to use a zext lowering.
8974 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8975 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8978 // See if we can use SSE4A Extraction / Insertion.
8979 if (Subtarget->hasSSE4A())
8980 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8984 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8986 // For single-input shuffles, there are some nicer lowering tricks we can use.
8987 if (NumV2Elements == 0) {
8988 // Check for being able to broadcast a single element.
8989 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8990 Mask, Subtarget, DAG))
8993 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8994 // Notably, this handles splat and partial-splat shuffles more efficiently.
8995 // However, it only makes sense if the pre-duplication shuffle simplifies
8996 // things significantly. Currently, this means we need to be able to
8997 // express the pre-duplication shuffle as an i16 shuffle.
8999 // FIXME: We should check for other patterns which can be widened into an
9000 // i16 shuffle as well.
9001 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9002 for (int i = 0; i < 16; i += 2)
9003 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9008 auto tryToWidenViaDuplication = [&]() -> SDValue {
9009 if (!canWidenViaDuplication(Mask))
9011 SmallVector<int, 4> LoInputs;
9012 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9013 [](int M) { return M >= 0 && M < 8; });
9014 std::sort(LoInputs.begin(), LoInputs.end());
9015 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9017 SmallVector<int, 4> HiInputs;
9018 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9019 [](int M) { return M >= 8; });
9020 std::sort(HiInputs.begin(), HiInputs.end());
9021 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9024 bool TargetLo = LoInputs.size() >= HiInputs.size();
9025 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9026 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9028 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9029 SmallDenseMap<int, int, 8> LaneMap;
9030 for (int I : InPlaceInputs) {
9031 PreDupI16Shuffle[I/2] = I/2;
9034 int j = TargetLo ? 0 : 4, je = j + 4;
9035 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9036 // Check if j is already a shuffle of this input. This happens when
9037 // there are two adjacent bytes after we move the low one.
9038 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9039 // If we haven't yet mapped the input, search for a slot into which
9041 while (j < je && PreDupI16Shuffle[j] != -1)
9045 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9048 // Map this input with the i16 shuffle.
9049 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9052 // Update the lane map based on the mapping we ended up with.
9053 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9055 V1 = DAG.getBitcast(
9057 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9058 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9060 // Unpack the bytes to form the i16s that will be shuffled into place.
9061 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9062 MVT::v16i8, V1, V1);
9064 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9065 for (int i = 0; i < 16; ++i)
9066 if (Mask[i] != -1) {
9067 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9068 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9069 if (PostDupI16Shuffle[i / 2] == -1)
9070 PostDupI16Shuffle[i / 2] = MappedMask;
9072 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9073 "Conflicting entrties in the original shuffle!");
9075 return DAG.getBitcast(
9077 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9078 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9080 if (SDValue V = tryToWidenViaDuplication())
9084 if (SDValue Masked =
9085 lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9088 // Use dedicated unpack instructions for masks that match their pattern.
9089 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9090 0, 16, 1, 17, 2, 18, 3, 19,
9092 4, 20, 5, 21, 6, 22, 7, 23}))
9093 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9094 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9095 8, 24, 9, 25, 10, 26, 11, 27,
9097 12, 28, 13, 29, 14, 30, 15, 31}))
9098 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9100 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9101 // with PSHUFB. It is important to do this before we attempt to generate any
9102 // blends but after all of the single-input lowerings. If the single input
9103 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9104 // want to preserve that and we can DAG combine any longer sequences into
9105 // a PSHUFB in the end. But once we start blending from multiple inputs,
9106 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9107 // and there are *very* few patterns that would actually be faster than the
9108 // PSHUFB approach because of its ability to zero lanes.
9110 // FIXME: The only exceptions to the above are blends which are exact
9111 // interleavings with direct instructions supporting them. We currently don't
9112 // handle those well here.
9113 if (Subtarget->hasSSSE3()) {
9114 bool V1InUse = false;
9115 bool V2InUse = false;
9117 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9118 DAG, V1InUse, V2InUse);
9120 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9121 // do so. This avoids using them to handle blends-with-zero which is
9122 // important as a single pshufb is significantly faster for that.
9123 if (V1InUse && V2InUse) {
9124 if (Subtarget->hasSSE41())
9125 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9126 Mask, Subtarget, DAG))
9129 // We can use an unpack to do the blending rather than an or in some
9130 // cases. Even though the or may be (very minorly) more efficient, we
9131 // preference this lowering because there are common cases where part of
9132 // the complexity of the shuffles goes away when we do the final blend as
9134 // FIXME: It might be worth trying to detect if the unpack-feeding
9135 // shuffles will both be pshufb, in which case we shouldn't bother with
9137 if (SDValue Unpack =
9138 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9145 // There are special ways we can lower some single-element blends.
9146 if (NumV2Elements == 1)
9147 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9148 Mask, Subtarget, DAG))
9151 if (SDValue BitBlend =
9152 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9155 // Check whether a compaction lowering can be done. This handles shuffles
9156 // which take every Nth element for some even N. See the helper function for
9159 // We special case these as they can be particularly efficiently handled with
9160 // the PACKUSB instruction on x86 and they show up in common patterns of
9161 // rearranging bytes to truncate wide elements.
9162 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9163 // NumEvenDrops is the power of two stride of the elements. Another way of
9164 // thinking about it is that we need to drop the even elements this many
9165 // times to get the original input.
9166 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9168 // First we need to zero all the dropped bytes.
9169 assert(NumEvenDrops <= 3 &&
9170 "No support for dropping even elements more than 3 times.");
9171 // We use the mask type to pick which bytes are preserved based on how many
9172 // elements are dropped.
9173 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9174 SDValue ByteClearMask = DAG.getBitcast(
9175 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9176 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9178 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9180 // Now pack things back together.
9181 V1 = DAG.getBitcast(MVT::v8i16, V1);
9182 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9183 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9184 for (int i = 1; i < NumEvenDrops; ++i) {
9185 Result = DAG.getBitcast(MVT::v8i16, Result);
9186 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9192 // Handle multi-input cases by blending single-input shuffles.
9193 if (NumV2Elements > 0)
9194 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9197 // The fallback path for single-input shuffles widens this into two v8i16
9198 // vectors with unpacks, shuffles those, and then pulls them back together
9202 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9203 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9204 for (int i = 0; i < 16; ++i)
9206 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9208 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9210 SDValue VLoHalf, VHiHalf;
9211 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9212 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9214 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9215 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9216 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9217 [](int M) { return M >= 0 && M % 2 == 1; })) {
9218 // Use a mask to drop the high bytes.
9219 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9220 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9221 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9223 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9224 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9226 // Squash the masks to point directly into VLoHalf.
9227 for (int &M : LoBlendMask)
9230 for (int &M : HiBlendMask)
9234 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9235 // VHiHalf so that we can blend them as i16s.
9236 VLoHalf = DAG.getBitcast(
9237 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9238 VHiHalf = DAG.getBitcast(
9239 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9242 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9243 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9245 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9248 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9250 /// This routine breaks down the specific type of 128-bit shuffle and
9251 /// dispatches to the lowering routines accordingly.
9252 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9253 MVT VT, const X86Subtarget *Subtarget,
9254 SelectionDAG &DAG) {
9255 switch (VT.SimpleTy) {
9257 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9259 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9261 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9263 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9265 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9267 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9270 llvm_unreachable("Unimplemented!");
9274 /// \brief Helper function to test whether a shuffle mask could be
9275 /// simplified by widening the elements being shuffled.
9277 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9278 /// leaves it in an unspecified state.
9280 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9281 /// shuffle masks. The latter have the special property of a '-2' representing
9282 /// a zero-ed lane of a vector.
9283 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9284 SmallVectorImpl<int> &WidenedMask) {
9285 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9286 // If both elements are undef, its trivial.
9287 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9288 WidenedMask.push_back(SM_SentinelUndef);
9292 // Check for an undef mask and a mask value properly aligned to fit with
9293 // a pair of values. If we find such a case, use the non-undef mask's value.
9294 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9295 WidenedMask.push_back(Mask[i + 1] / 2);
9298 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9299 WidenedMask.push_back(Mask[i] / 2);
9303 // When zeroing, we need to spread the zeroing across both lanes to widen.
9304 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9305 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9306 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9307 WidenedMask.push_back(SM_SentinelZero);
9313 // Finally check if the two mask values are adjacent and aligned with
9315 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9316 WidenedMask.push_back(Mask[i] / 2);
9320 // Otherwise we can't safely widen the elements used in this shuffle.
9323 assert(WidenedMask.size() == Mask.size() / 2 &&
9324 "Incorrect size of mask after widening the elements!");
9329 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9331 /// This routine just extracts two subvectors, shuffles them independently, and
9332 /// then concatenates them back together. This should work effectively with all
9333 /// AVX vector shuffle types.
9334 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9335 SDValue V2, ArrayRef<int> Mask,
9336 SelectionDAG &DAG) {
9337 assert(VT.getSizeInBits() >= 256 &&
9338 "Only for 256-bit or wider vector shuffles!");
9339 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9340 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9342 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9343 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9345 int NumElements = VT.getVectorNumElements();
9346 int SplitNumElements = NumElements / 2;
9347 MVT ScalarVT = VT.getScalarType();
9348 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9350 // Rather than splitting build-vectors, just build two narrower build
9351 // vectors. This helps shuffling with splats and zeros.
9352 auto SplitVector = [&](SDValue V) {
9353 while (V.getOpcode() == ISD::BITCAST)
9354 V = V->getOperand(0);
9356 MVT OrigVT = V.getSimpleValueType();
9357 int OrigNumElements = OrigVT.getVectorNumElements();
9358 int OrigSplitNumElements = OrigNumElements / 2;
9359 MVT OrigScalarVT = OrigVT.getScalarType();
9360 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9364 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9366 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9367 DAG.getIntPtrConstant(0, DL));
9368 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9369 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9372 SmallVector<SDValue, 16> LoOps, HiOps;
9373 for (int i = 0; i < OrigSplitNumElements; ++i) {
9374 LoOps.push_back(BV->getOperand(i));
9375 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9377 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9378 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9380 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9381 DAG.getBitcast(SplitVT, HiV));
9384 SDValue LoV1, HiV1, LoV2, HiV2;
9385 std::tie(LoV1, HiV1) = SplitVector(V1);
9386 std::tie(LoV2, HiV2) = SplitVector(V2);
9388 // Now create two 4-way blends of these half-width vectors.
9389 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9390 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9391 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9392 for (int i = 0; i < SplitNumElements; ++i) {
9393 int M = HalfMask[i];
9394 if (M >= NumElements) {
9395 if (M >= NumElements + SplitNumElements)
9399 V2BlendMask.push_back(M - NumElements);
9400 V1BlendMask.push_back(-1);
9401 BlendMask.push_back(SplitNumElements + i);
9402 } else if (M >= 0) {
9403 if (M >= SplitNumElements)
9407 V2BlendMask.push_back(-1);
9408 V1BlendMask.push_back(M);
9409 BlendMask.push_back(i);
9411 V2BlendMask.push_back(-1);
9412 V1BlendMask.push_back(-1);
9413 BlendMask.push_back(-1);
9417 // Because the lowering happens after all combining takes place, we need to
9418 // manually combine these blend masks as much as possible so that we create
9419 // a minimal number of high-level vector shuffle nodes.
9421 // First try just blending the halves of V1 or V2.
9422 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9423 return DAG.getUNDEF(SplitVT);
9424 if (!UseLoV2 && !UseHiV2)
9425 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9426 if (!UseLoV1 && !UseHiV1)
9427 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9429 SDValue V1Blend, V2Blend;
9430 if (UseLoV1 && UseHiV1) {
9432 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9434 // We only use half of V1 so map the usage down into the final blend mask.
9435 V1Blend = UseLoV1 ? LoV1 : HiV1;
9436 for (int i = 0; i < SplitNumElements; ++i)
9437 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9438 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9440 if (UseLoV2 && UseHiV2) {
9442 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9444 // We only use half of V2 so map the usage down into the final blend mask.
9445 V2Blend = UseLoV2 ? LoV2 : HiV2;
9446 for (int i = 0; i < SplitNumElements; ++i)
9447 if (BlendMask[i] >= SplitNumElements)
9448 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9450 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9452 SDValue Lo = HalfBlend(LoMask);
9453 SDValue Hi = HalfBlend(HiMask);
9454 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9457 /// \brief Either split a vector in halves or decompose the shuffles and the
9460 /// This is provided as a good fallback for many lowerings of non-single-input
9461 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9462 /// between splitting the shuffle into 128-bit components and stitching those
9463 /// back together vs. extracting the single-input shuffles and blending those
9465 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9466 SDValue V2, ArrayRef<int> Mask,
9467 SelectionDAG &DAG) {
9468 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9469 "lower single-input shuffles as it "
9470 "could then recurse on itself.");
9471 int Size = Mask.size();
9473 // If this can be modeled as a broadcast of two elements followed by a blend,
9474 // prefer that lowering. This is especially important because broadcasts can
9475 // often fold with memory operands.
9476 auto DoBothBroadcast = [&] {
9477 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9480 if (V2BroadcastIdx == -1)
9481 V2BroadcastIdx = M - Size;
9482 else if (M - Size != V2BroadcastIdx)
9484 } else if (M >= 0) {
9485 if (V1BroadcastIdx == -1)
9487 else if (M != V1BroadcastIdx)
9492 if (DoBothBroadcast())
9493 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9496 // If the inputs all stem from a single 128-bit lane of each input, then we
9497 // split them rather than blending because the split will decompose to
9498 // unusually few instructions.
9499 int LaneCount = VT.getSizeInBits() / 128;
9500 int LaneSize = Size / LaneCount;
9501 SmallBitVector LaneInputs[2];
9502 LaneInputs[0].resize(LaneCount, false);
9503 LaneInputs[1].resize(LaneCount, false);
9504 for (int i = 0; i < Size; ++i)
9506 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9507 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9508 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9510 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9511 // that the decomposed single-input shuffles don't end up here.
9512 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9515 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9516 /// a permutation and blend of those lanes.
9518 /// This essentially blends the out-of-lane inputs to each lane into the lane
9519 /// from a permuted copy of the vector. This lowering strategy results in four
9520 /// instructions in the worst case for a single-input cross lane shuffle which
9521 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9522 /// of. Special cases for each particular shuffle pattern should be handled
9523 /// prior to trying this lowering.
9524 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9525 SDValue V1, SDValue V2,
9527 SelectionDAG &DAG) {
9528 // FIXME: This should probably be generalized for 512-bit vectors as well.
9529 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9530 int LaneSize = Mask.size() / 2;
9532 // If there are only inputs from one 128-bit lane, splitting will in fact be
9533 // less expensive. The flags track whether the given lane contains an element
9534 // that crosses to another lane.
9535 bool LaneCrossing[2] = {false, false};
9536 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9537 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9538 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9539 if (!LaneCrossing[0] || !LaneCrossing[1])
9540 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9542 if (isSingleInputShuffleMask(Mask)) {
9543 SmallVector<int, 32> FlippedBlendMask;
9544 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9545 FlippedBlendMask.push_back(
9546 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9548 : Mask[i] % LaneSize +
9549 (i / LaneSize) * LaneSize + Size));
9551 // Flip the vector, and blend the results which should now be in-lane. The
9552 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9553 // 5 for the high source. The value 3 selects the high half of source 2 and
9554 // the value 2 selects the low half of source 2. We only use source 2 to
9555 // allow folding it into a memory operand.
9556 unsigned PERMMask = 3 | 2 << 4;
9557 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9558 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9559 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9562 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9563 // will be handled by the above logic and a blend of the results, much like
9564 // other patterns in AVX.
9565 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9568 /// \brief Handle lowering 2-lane 128-bit shuffles.
9569 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9570 SDValue V2, ArrayRef<int> Mask,
9571 const X86Subtarget *Subtarget,
9572 SelectionDAG &DAG) {
9573 // TODO: If minimizing size and one of the inputs is a zero vector and the
9574 // the zero vector has only one use, we could use a VPERM2X128 to save the
9575 // instruction bytes needed to explicitly generate the zero vector.
9577 // Blends are faster and handle all the non-lane-crossing cases.
9578 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9582 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9583 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9585 // If either input operand is a zero vector, use VPERM2X128 because its mask
9586 // allows us to replace the zero input with an implicit zero.
9587 if (!IsV1Zero && !IsV2Zero) {
9588 // Check for patterns which can be matched with a single insert of a 128-bit
9590 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9591 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9592 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9593 VT.getVectorNumElements() / 2);
9594 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9595 DAG.getIntPtrConstant(0, DL));
9596 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9597 OnlyUsesV1 ? V1 : V2,
9598 DAG.getIntPtrConstant(0, DL));
9599 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9603 // Otherwise form a 128-bit permutation. After accounting for undefs,
9604 // convert the 64-bit shuffle mask selection values into 128-bit
9605 // selection bits by dividing the indexes by 2 and shifting into positions
9606 // defined by a vperm2*128 instruction's immediate control byte.
9608 // The immediate permute control byte looks like this:
9609 // [1:0] - select 128 bits from sources for low half of destination
9611 // [3] - zero low half of destination
9612 // [5:4] - select 128 bits from sources for high half of destination
9614 // [7] - zero high half of destination
9616 int MaskLO = Mask[0];
9617 if (MaskLO == SM_SentinelUndef)
9618 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9620 int MaskHI = Mask[2];
9621 if (MaskHI == SM_SentinelUndef)
9622 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9624 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9626 // If either input is a zero vector, replace it with an undef input.
9627 // Shuffle mask values < 4 are selecting elements of V1.
9628 // Shuffle mask values >= 4 are selecting elements of V2.
9629 // Adjust each half of the permute mask by clearing the half that was
9630 // selecting the zero vector and setting the zero mask bit.
9632 V1 = DAG.getUNDEF(VT);
9634 PermMask = (PermMask & 0xf0) | 0x08;
9636 PermMask = (PermMask & 0x0f) | 0x80;
9639 V2 = DAG.getUNDEF(VT);
9641 PermMask = (PermMask & 0xf0) | 0x08;
9643 PermMask = (PermMask & 0x0f) | 0x80;
9646 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9647 DAG.getConstant(PermMask, DL, MVT::i8));
9650 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9651 /// shuffling each lane.
9653 /// This will only succeed when the result of fixing the 128-bit lanes results
9654 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9655 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9656 /// the lane crosses early and then use simpler shuffles within each lane.
9658 /// FIXME: It might be worthwhile at some point to support this without
9659 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9660 /// in x86 only floating point has interesting non-repeating shuffles, and even
9661 /// those are still *marginally* more expensive.
9662 static SDValue lowerVectorShuffleByMerging128BitLanes(
9663 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9664 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9665 assert(!isSingleInputShuffleMask(Mask) &&
9666 "This is only useful with multiple inputs.");
9668 int Size = Mask.size();
9669 int LaneSize = 128 / VT.getScalarSizeInBits();
9670 int NumLanes = Size / LaneSize;
9671 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9673 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9674 // check whether the in-128-bit lane shuffles share a repeating pattern.
9675 SmallVector<int, 4> Lanes;
9676 Lanes.resize(NumLanes, -1);
9677 SmallVector<int, 4> InLaneMask;
9678 InLaneMask.resize(LaneSize, -1);
9679 for (int i = 0; i < Size; ++i) {
9683 int j = i / LaneSize;
9686 // First entry we've seen for this lane.
9687 Lanes[j] = Mask[i] / LaneSize;
9688 } else if (Lanes[j] != Mask[i] / LaneSize) {
9689 // This doesn't match the lane selected previously!
9693 // Check that within each lane we have a consistent shuffle mask.
9694 int k = i % LaneSize;
9695 if (InLaneMask[k] < 0) {
9696 InLaneMask[k] = Mask[i] % LaneSize;
9697 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9698 // This doesn't fit a repeating in-lane mask.
9703 // First shuffle the lanes into place.
9704 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9705 VT.getSizeInBits() / 64);
9706 SmallVector<int, 8> LaneMask;
9707 LaneMask.resize(NumLanes * 2, -1);
9708 for (int i = 0; i < NumLanes; ++i)
9709 if (Lanes[i] >= 0) {
9710 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9711 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9714 V1 = DAG.getBitcast(LaneVT, V1);
9715 V2 = DAG.getBitcast(LaneVT, V2);
9716 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9718 // Cast it back to the type we actually want.
9719 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9721 // Now do a simple shuffle that isn't lane crossing.
9722 SmallVector<int, 8> NewMask;
9723 NewMask.resize(Size, -1);
9724 for (int i = 0; i < Size; ++i)
9726 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9727 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9728 "Must not introduce lane crosses at this point!");
9730 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9733 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9736 /// This returns true if the elements from a particular input are already in the
9737 /// slot required by the given mask and require no permutation.
9738 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9739 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9740 int Size = Mask.size();
9741 for (int i = 0; i < Size; ++i)
9742 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9748 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9749 ArrayRef<int> Mask, SDValue V1,
9750 SDValue V2, SelectionDAG &DAG) {
9752 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
9753 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
9754 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9755 int NumElts = VT.getVectorNumElements();
9756 bool ShufpdMask = true;
9757 bool CommutableMask = true;
9758 unsigned Immediate = 0;
9759 for (int i = 0; i < NumElts; ++i) {
9762 int Val = (i & 6) + NumElts * (i & 1);
9763 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9764 if (Mask[i] < Val || Mask[i] > Val + 1)
9766 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
9767 CommutableMask = false;
9768 Immediate |= (Mask[i] % 2) << i;
9771 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9772 DAG.getConstant(Immediate, DL, MVT::i8));
9774 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9775 DAG.getConstant(Immediate, DL, MVT::i8));
9779 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9781 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9782 /// isn't available.
9783 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9784 const X86Subtarget *Subtarget,
9785 SelectionDAG &DAG) {
9787 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9788 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9789 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9790 ArrayRef<int> Mask = SVOp->getMask();
9791 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9793 SmallVector<int, 4> WidenedMask;
9794 if (canWidenShuffleElements(Mask, WidenedMask))
9795 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9798 if (isSingleInputShuffleMask(Mask)) {
9799 // Check for being able to broadcast a single element.
9800 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9801 Mask, Subtarget, DAG))
9804 // Use low duplicate instructions for masks that match their pattern.
9805 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9806 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9808 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9809 // Non-half-crossing single input shuffles can be lowerid with an
9810 // interleaved permutation.
9811 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9812 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9813 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9814 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9817 // With AVX2 we have direct support for this permutation.
9818 if (Subtarget->hasAVX2())
9819 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9820 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9822 // Otherwise, fall back.
9823 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9827 // X86 has dedicated unpack instructions that can handle specific blend
9828 // operations: UNPCKH and UNPCKL.
9829 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9830 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9831 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9832 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9833 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9834 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9835 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9836 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9838 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9842 // Check if the blend happens to exactly fit that of SHUFPD.
9844 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9847 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9848 // shuffle. However, if we have AVX2 and either inputs are already in place,
9849 // we will be able to shuffle even across lanes the other input in a single
9850 // instruction so skip this pattern.
9851 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9852 isShuffleMaskInputInPlace(1, Mask))))
9853 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9854 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9857 // If we have AVX2 then we always want to lower with a blend because an v4 we
9858 // can fully permute the elements.
9859 if (Subtarget->hasAVX2())
9860 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9863 // Otherwise fall back on generic lowering.
9864 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9867 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9869 /// This routine is only called when we have AVX2 and thus a reasonable
9870 /// instruction set for v4i64 shuffling..
9871 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9872 const X86Subtarget *Subtarget,
9873 SelectionDAG &DAG) {
9875 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9876 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9877 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9878 ArrayRef<int> Mask = SVOp->getMask();
9879 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9880 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9882 SmallVector<int, 4> WidenedMask;
9883 if (canWidenShuffleElements(Mask, WidenedMask))
9884 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9887 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9891 // Check for being able to broadcast a single element.
9892 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9893 Mask, Subtarget, DAG))
9896 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9897 // use lower latency instructions that will operate on both 128-bit lanes.
9898 SmallVector<int, 2> RepeatedMask;
9899 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9900 if (isSingleInputShuffleMask(Mask)) {
9901 int PSHUFDMask[] = {-1, -1, -1, -1};
9902 for (int i = 0; i < 2; ++i)
9903 if (RepeatedMask[i] >= 0) {
9904 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9905 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9907 return DAG.getBitcast(
9909 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9910 DAG.getBitcast(MVT::v8i32, V1),
9911 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9915 // AVX2 provides a direct instruction for permuting a single input across
9917 if (isSingleInputShuffleMask(Mask))
9918 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9919 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9921 // Try to use shift instructions.
9923 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9926 // Use dedicated unpack instructions for masks that match their pattern.
9927 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9928 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9929 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9930 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9931 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9932 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9933 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9934 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9936 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9937 // shuffle. However, if we have AVX2 and either inputs are already in place,
9938 // we will be able to shuffle even across lanes the other input in a single
9939 // instruction so skip this pattern.
9940 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9941 isShuffleMaskInputInPlace(1, Mask))))
9942 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9943 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9946 // Otherwise fall back on generic blend lowering.
9947 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9951 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9953 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9954 /// isn't available.
9955 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9956 const X86Subtarget *Subtarget,
9957 SelectionDAG &DAG) {
9959 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9960 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9961 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9962 ArrayRef<int> Mask = SVOp->getMask();
9963 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9965 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9969 // Check for being able to broadcast a single element.
9970 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9971 Mask, Subtarget, DAG))
9974 // If the shuffle mask is repeated in each 128-bit lane, we have many more
9975 // options to efficiently lower the shuffle.
9976 SmallVector<int, 4> RepeatedMask;
9977 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9978 assert(RepeatedMask.size() == 4 &&
9979 "Repeated masks must be half the mask width!");
9981 // Use even/odd duplicate instructions for masks that match their pattern.
9982 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9983 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9984 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9985 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9987 if (isSingleInputShuffleMask(Mask))
9988 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9989 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9991 // Use dedicated unpack instructions for masks that match their pattern.
9992 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9993 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9994 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9995 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9996 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9997 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9998 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9999 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10001 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10002 // have already handled any direct blends. We also need to squash the
10003 // repeated mask into a simulated v4f32 mask.
10004 for (int i = 0; i < 4; ++i)
10005 if (RepeatedMask[i] >= 8)
10006 RepeatedMask[i] -= 4;
10007 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10010 // If we have a single input shuffle with different shuffle patterns in the
10011 // two 128-bit lanes use the variable mask to VPERMILPS.
10012 if (isSingleInputShuffleMask(Mask)) {
10013 SDValue VPermMask[8];
10014 for (int i = 0; i < 8; ++i)
10015 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10016 : DAG.getConstant(Mask[i], DL, MVT::i32);
10017 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10018 return DAG.getNode(
10019 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10020 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10022 if (Subtarget->hasAVX2())
10023 return DAG.getNode(
10024 X86ISD::VPERMV, DL, MVT::v8f32,
10025 DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10026 MVT::v8i32, VPermMask)),
10029 // Otherwise, fall back.
10030 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10034 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10036 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10037 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10040 // If we have AVX2 then we always want to lower with a blend because at v8 we
10041 // can fully permute the elements.
10042 if (Subtarget->hasAVX2())
10043 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10046 // Otherwise fall back on generic lowering.
10047 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10050 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10052 /// This routine is only called when we have AVX2 and thus a reasonable
10053 /// instruction set for v8i32 shuffling..
10054 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10055 const X86Subtarget *Subtarget,
10056 SelectionDAG &DAG) {
10058 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10059 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10060 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10061 ArrayRef<int> Mask = SVOp->getMask();
10062 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10063 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10065 // Whenever we can lower this as a zext, that instruction is strictly faster
10066 // than any alternative. It also allows us to fold memory operands into the
10067 // shuffle in many cases.
10068 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10069 Mask, Subtarget, DAG))
10072 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10076 // Check for being able to broadcast a single element.
10077 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10078 Mask, Subtarget, DAG))
10081 // If the shuffle mask is repeated in each 128-bit lane we can use more
10082 // efficient instructions that mirror the shuffles across the two 128-bit
10084 SmallVector<int, 4> RepeatedMask;
10085 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10086 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10087 if (isSingleInputShuffleMask(Mask))
10088 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10089 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10091 // Use dedicated unpack instructions for masks that match their pattern.
10092 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10093 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10094 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10095 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10096 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10097 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10098 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10099 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10102 // Try to use shift instructions.
10103 if (SDValue Shift =
10104 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10107 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10108 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10111 // If the shuffle patterns aren't repeated but it is a single input, directly
10112 // generate a cross-lane VPERMD instruction.
10113 if (isSingleInputShuffleMask(Mask)) {
10114 SDValue VPermMask[8];
10115 for (int i = 0; i < 8; ++i)
10116 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10117 : DAG.getConstant(Mask[i], DL, MVT::i32);
10118 return DAG.getNode(
10119 X86ISD::VPERMV, DL, MVT::v8i32,
10120 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10123 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10125 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10126 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10129 // Otherwise fall back on generic blend lowering.
10130 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10134 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10136 /// This routine is only called when we have AVX2 and thus a reasonable
10137 /// instruction set for v16i16 shuffling..
10138 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10139 const X86Subtarget *Subtarget,
10140 SelectionDAG &DAG) {
10142 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10143 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10144 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10145 ArrayRef<int> Mask = SVOp->getMask();
10146 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10147 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10149 // Whenever we can lower this as a zext, that instruction is strictly faster
10150 // than any alternative. It also allows us to fold memory operands into the
10151 // shuffle in many cases.
10152 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10153 Mask, Subtarget, DAG))
10156 // Check for being able to broadcast a single element.
10157 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10158 Mask, Subtarget, DAG))
10161 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10165 // Use dedicated unpack instructions for masks that match their pattern.
10166 if (isShuffleEquivalent(V1, V2, Mask,
10167 {// First 128-bit lane:
10168 0, 16, 1, 17, 2, 18, 3, 19,
10169 // Second 128-bit lane:
10170 8, 24, 9, 25, 10, 26, 11, 27}))
10171 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10172 if (isShuffleEquivalent(V1, V2, Mask,
10173 {// First 128-bit lane:
10174 4, 20, 5, 21, 6, 22, 7, 23,
10175 // Second 128-bit lane:
10176 12, 28, 13, 29, 14, 30, 15, 31}))
10177 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10179 // Try to use shift instructions.
10180 if (SDValue Shift =
10181 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10184 // Try to use byte rotation instructions.
10185 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10186 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10189 if (isSingleInputShuffleMask(Mask)) {
10190 // There are no generalized cross-lane shuffle operations available on i16
10192 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10193 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10196 SmallVector<int, 8> RepeatedMask;
10197 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10198 // As this is a single-input shuffle, the repeated mask should be
10199 // a strictly valid v8i16 mask that we can pass through to the v8i16
10200 // lowering to handle even the v16 case.
10201 return lowerV8I16GeneralSingleInputVectorShuffle(
10202 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10205 SDValue PSHUFBMask[32];
10206 for (int i = 0; i < 16; ++i) {
10207 if (Mask[i] == -1) {
10208 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10212 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10213 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10214 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10215 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10217 return DAG.getBitcast(MVT::v16i16,
10218 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10219 DAG.getBitcast(MVT::v32i8, V1),
10220 DAG.getNode(ISD::BUILD_VECTOR, DL,
10221 MVT::v32i8, PSHUFBMask)));
10224 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10226 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10227 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10230 // Otherwise fall back on generic lowering.
10231 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10234 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10236 /// This routine is only called when we have AVX2 and thus a reasonable
10237 /// instruction set for v32i8 shuffling..
10238 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10239 const X86Subtarget *Subtarget,
10240 SelectionDAG &DAG) {
10242 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10243 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10244 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10245 ArrayRef<int> Mask = SVOp->getMask();
10246 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10247 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10249 // Whenever we can lower this as a zext, that instruction is strictly faster
10250 // than any alternative. It also allows us to fold memory operands into the
10251 // shuffle in many cases.
10252 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10253 Mask, Subtarget, DAG))
10256 // Check for being able to broadcast a single element.
10257 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10258 Mask, Subtarget, DAG))
10261 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10265 // Use dedicated unpack instructions for masks that match their pattern.
10266 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10268 if (isShuffleEquivalent(
10270 {// First 128-bit lane:
10271 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10272 // Second 128-bit lane:
10273 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10274 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10275 if (isShuffleEquivalent(
10277 {// First 128-bit lane:
10278 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10279 // Second 128-bit lane:
10280 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10281 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10283 // Try to use shift instructions.
10284 if (SDValue Shift =
10285 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10288 // Try to use byte rotation instructions.
10289 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10290 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10293 if (isSingleInputShuffleMask(Mask)) {
10294 // There are no generalized cross-lane shuffle operations available on i8
10296 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10297 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10300 SDValue PSHUFBMask[32];
10301 for (int i = 0; i < 32; ++i)
10304 ? DAG.getUNDEF(MVT::i8)
10305 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10308 return DAG.getNode(
10309 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10310 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10313 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10315 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10316 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10319 // Otherwise fall back on generic lowering.
10320 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10323 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10325 /// This routine either breaks down the specific type of a 256-bit x86 vector
10326 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10327 /// together based on the available instructions.
10328 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10329 MVT VT, const X86Subtarget *Subtarget,
10330 SelectionDAG &DAG) {
10332 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10333 ArrayRef<int> Mask = SVOp->getMask();
10335 // If we have a single input to the zero element, insert that into V1 if we
10336 // can do so cheaply.
10337 int NumElts = VT.getVectorNumElements();
10338 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10339 return M >= NumElts;
10342 if (NumV2Elements == 1 && Mask[0] >= NumElts)
10343 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10344 DL, VT, V1, V2, Mask, Subtarget, DAG))
10347 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10348 // check for those subtargets here and avoid much of the subtarget querying in
10349 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10350 // ability to manipulate a 256-bit vector with integer types. Since we'll use
10351 // floating point types there eventually, just immediately cast everything to
10352 // a float and operate entirely in that domain.
10353 if (VT.isInteger() && !Subtarget->hasAVX2()) {
10354 int ElementBits = VT.getScalarSizeInBits();
10355 if (ElementBits < 32)
10356 // No floating point type available, decompose into 128-bit vectors.
10357 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10359 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10360 VT.getVectorNumElements());
10361 V1 = DAG.getBitcast(FpVT, V1);
10362 V2 = DAG.getBitcast(FpVT, V2);
10363 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10366 switch (VT.SimpleTy) {
10368 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10370 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10372 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10374 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10376 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10378 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10381 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10385 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10386 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10387 const X86Subtarget *Subtarget,
10388 SelectionDAG &DAG) {
10390 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10391 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10392 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10393 ArrayRef<int> Mask = SVOp->getMask();
10394 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10396 // X86 has dedicated unpack instructions that can handle specific blend
10397 // operations: UNPCKH and UNPCKL.
10398 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10399 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10400 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10401 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10403 // FIXME: Implement direct support for this type!
10404 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10407 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10408 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10409 const X86Subtarget *Subtarget,
10410 SelectionDAG &DAG) {
10412 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10413 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10414 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10415 ArrayRef<int> Mask = SVOp->getMask();
10416 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10418 // Use dedicated unpack instructions for masks that match their pattern.
10419 if (isShuffleEquivalent(V1, V2, Mask,
10420 {// First 128-bit lane.
10421 0, 16, 1, 17, 4, 20, 5, 21,
10422 // Second 128-bit lane.
10423 8, 24, 9, 25, 12, 28, 13, 29}))
10424 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10425 if (isShuffleEquivalent(V1, V2, Mask,
10426 {// First 128-bit lane.
10427 2, 18, 3, 19, 6, 22, 7, 23,
10428 // Second 128-bit lane.
10429 10, 26, 11, 27, 14, 30, 15, 31}))
10430 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10432 // FIXME: Implement direct support for this type!
10433 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10436 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10437 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10438 const X86Subtarget *Subtarget,
10439 SelectionDAG &DAG) {
10441 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10442 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10443 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10444 ArrayRef<int> Mask = SVOp->getMask();
10445 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10447 // X86 has dedicated unpack instructions that can handle specific blend
10448 // operations: UNPCKH and UNPCKL.
10449 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10450 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10451 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10452 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10454 // FIXME: Implement direct support for this type!
10455 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10458 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10459 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10460 const X86Subtarget *Subtarget,
10461 SelectionDAG &DAG) {
10463 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10464 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10465 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10466 ArrayRef<int> Mask = SVOp->getMask();
10467 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10469 // Use dedicated unpack instructions for masks that match their pattern.
10470 if (isShuffleEquivalent(V1, V2, Mask,
10471 {// First 128-bit lane.
10472 0, 16, 1, 17, 4, 20, 5, 21,
10473 // Second 128-bit lane.
10474 8, 24, 9, 25, 12, 28, 13, 29}))
10475 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10476 if (isShuffleEquivalent(V1, V2, Mask,
10477 {// First 128-bit lane.
10478 2, 18, 3, 19, 6, 22, 7, 23,
10479 // Second 128-bit lane.
10480 10, 26, 11, 27, 14, 30, 15, 31}))
10481 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10483 // FIXME: Implement direct support for this type!
10484 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10487 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10488 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10489 const X86Subtarget *Subtarget,
10490 SelectionDAG &DAG) {
10492 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10493 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10494 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10495 ArrayRef<int> Mask = SVOp->getMask();
10496 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10497 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10499 // FIXME: Implement direct support for this type!
10500 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10503 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10504 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10505 const X86Subtarget *Subtarget,
10506 SelectionDAG &DAG) {
10508 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10509 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10510 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10511 ArrayRef<int> Mask = SVOp->getMask();
10512 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10513 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10515 // FIXME: Implement direct support for this type!
10516 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10519 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10521 /// This routine either breaks down the specific type of a 512-bit x86 vector
10522 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10523 /// together based on the available instructions.
10524 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10525 MVT VT, const X86Subtarget *Subtarget,
10526 SelectionDAG &DAG) {
10528 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10529 ArrayRef<int> Mask = SVOp->getMask();
10530 assert(Subtarget->hasAVX512() &&
10531 "Cannot lower 512-bit vectors w/ basic ISA!");
10533 // Check for being able to broadcast a single element.
10534 if (SDValue Broadcast =
10535 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10538 // Dispatch to each element type for lowering. If we don't have supprot for
10539 // specific element type shuffles at 512 bits, immediately split them and
10540 // lower them. Each lowering routine of a given type is allowed to assume that
10541 // the requisite ISA extensions for that element type are available.
10542 switch (VT.SimpleTy) {
10544 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10546 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10548 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10550 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10552 if (Subtarget->hasBWI())
10553 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10556 if (Subtarget->hasBWI())
10557 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10561 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10564 // Otherwise fall back on splitting.
10565 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10568 /// \brief Top-level lowering for x86 vector shuffles.
10570 /// This handles decomposition, canonicalization, and lowering of all x86
10571 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10572 /// above in helper routines. The canonicalization attempts to widen shuffles
10573 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10574 /// s.t. only one of the two inputs needs to be tested, etc.
10575 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10576 SelectionDAG &DAG) {
10577 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10578 ArrayRef<int> Mask = SVOp->getMask();
10579 SDValue V1 = Op.getOperand(0);
10580 SDValue V2 = Op.getOperand(1);
10581 MVT VT = Op.getSimpleValueType();
10582 int NumElements = VT.getVectorNumElements();
10585 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10587 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10588 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10589 if (V1IsUndef && V2IsUndef)
10590 return DAG.getUNDEF(VT);
10592 // When we create a shuffle node we put the UNDEF node to second operand,
10593 // but in some cases the first operand may be transformed to UNDEF.
10594 // In this case we should just commute the node.
10596 return DAG.getCommutedVectorShuffle(*SVOp);
10598 // Check for non-undef masks pointing at an undef vector and make the masks
10599 // undef as well. This makes it easier to match the shuffle based solely on
10603 if (M >= NumElements) {
10604 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10605 for (int &M : NewMask)
10606 if (M >= NumElements)
10608 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10611 // We actually see shuffles that are entirely re-arrangements of a set of
10612 // zero inputs. This mostly happens while decomposing complex shuffles into
10613 // simple ones. Directly lower these as a buildvector of zeros.
10614 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10615 if (Zeroable.all())
10616 return getZeroVector(VT, Subtarget, DAG, dl);
10618 // Try to collapse shuffles into using a vector type with fewer elements but
10619 // wider element types. We cap this to not form integers or floating point
10620 // elements wider than 64 bits, but it might be interesting to form i128
10621 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10622 SmallVector<int, 16> WidenedMask;
10623 if (VT.getScalarSizeInBits() < 64 &&
10624 canWidenShuffleElements(Mask, WidenedMask)) {
10625 MVT NewEltVT = VT.isFloatingPoint()
10626 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10627 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10628 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10629 // Make sure that the new vector type is legal. For example, v2f64 isn't
10631 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10632 V1 = DAG.getBitcast(NewVT, V1);
10633 V2 = DAG.getBitcast(NewVT, V2);
10634 return DAG.getBitcast(
10635 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10639 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10640 for (int M : SVOp->getMask())
10642 ++NumUndefElements;
10643 else if (M < NumElements)
10648 // Commute the shuffle as needed such that more elements come from V1 than
10649 // V2. This allows us to match the shuffle pattern strictly on how many
10650 // elements come from V1 without handling the symmetric cases.
10651 if (NumV2Elements > NumV1Elements)
10652 return DAG.getCommutedVectorShuffle(*SVOp);
10654 // When the number of V1 and V2 elements are the same, try to minimize the
10655 // number of uses of V2 in the low half of the vector. When that is tied,
10656 // ensure that the sum of indices for V1 is equal to or lower than the sum
10657 // indices for V2. When those are equal, try to ensure that the number of odd
10658 // indices for V1 is lower than the number of odd indices for V2.
10659 if (NumV1Elements == NumV2Elements) {
10660 int LowV1Elements = 0, LowV2Elements = 0;
10661 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10662 if (M >= NumElements)
10666 if (LowV2Elements > LowV1Elements) {
10667 return DAG.getCommutedVectorShuffle(*SVOp);
10668 } else if (LowV2Elements == LowV1Elements) {
10669 int SumV1Indices = 0, SumV2Indices = 0;
10670 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10671 if (SVOp->getMask()[i] >= NumElements)
10673 else if (SVOp->getMask()[i] >= 0)
10675 if (SumV2Indices < SumV1Indices) {
10676 return DAG.getCommutedVectorShuffle(*SVOp);
10677 } else if (SumV2Indices == SumV1Indices) {
10678 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10679 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10680 if (SVOp->getMask()[i] >= NumElements)
10681 NumV2OddIndices += i % 2;
10682 else if (SVOp->getMask()[i] >= 0)
10683 NumV1OddIndices += i % 2;
10684 if (NumV2OddIndices < NumV1OddIndices)
10685 return DAG.getCommutedVectorShuffle(*SVOp);
10690 // For each vector width, delegate to a specialized lowering routine.
10691 if (VT.getSizeInBits() == 128)
10692 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10694 if (VT.getSizeInBits() == 256)
10695 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10697 // Force AVX-512 vectors to be scalarized for now.
10698 // FIXME: Implement AVX-512 support!
10699 if (VT.getSizeInBits() == 512)
10700 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10702 llvm_unreachable("Unimplemented!");
10705 // This function assumes its argument is a BUILD_VECTOR of constants or
10706 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10708 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10709 unsigned &MaskValue) {
10711 unsigned NumElems = BuildVector->getNumOperands();
10712 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10713 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10714 unsigned NumElemsInLane = NumElems / NumLanes;
10716 // Blend for v16i16 should be symetric for the both lanes.
10717 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10718 SDValue EltCond = BuildVector->getOperand(i);
10719 SDValue SndLaneEltCond =
10720 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10722 int Lane1Cond = -1, Lane2Cond = -1;
10723 if (isa<ConstantSDNode>(EltCond))
10724 Lane1Cond = !isZero(EltCond);
10725 if (isa<ConstantSDNode>(SndLaneEltCond))
10726 Lane2Cond = !isZero(SndLaneEltCond);
10728 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10729 // Lane1Cond != 0, means we want the first argument.
10730 // Lane1Cond == 0, means we want the second argument.
10731 // The encoding of this argument is 0 for the first argument, 1
10732 // for the second. Therefore, invert the condition.
10733 MaskValue |= !Lane1Cond << i;
10734 else if (Lane1Cond < 0)
10735 MaskValue |= !Lane2Cond << i;
10742 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10743 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10744 const X86Subtarget *Subtarget,
10745 SelectionDAG &DAG) {
10746 SDValue Cond = Op.getOperand(0);
10747 SDValue LHS = Op.getOperand(1);
10748 SDValue RHS = Op.getOperand(2);
10750 MVT VT = Op.getSimpleValueType();
10752 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10754 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10756 // Only non-legal VSELECTs reach this lowering, convert those into generic
10757 // shuffles and re-use the shuffle lowering path for blends.
10758 SmallVector<int, 32> Mask;
10759 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10760 SDValue CondElt = CondBV->getOperand(i);
10762 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10764 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10767 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10768 // A vselect where all conditions and data are constants can be optimized into
10769 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10770 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10771 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10772 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10775 // Try to lower this to a blend-style vector shuffle. This can handle all
10776 // constant condition cases.
10777 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10780 // Variable blends are only legal from SSE4.1 onward.
10781 if (!Subtarget->hasSSE41())
10784 // Only some types will be legal on some subtargets. If we can emit a legal
10785 // VSELECT-matching blend, return Op, and but if we need to expand, return
10787 switch (Op.getSimpleValueType().SimpleTy) {
10789 // Most of the vector types have blends past SSE4.1.
10793 // The byte blends for AVX vectors were introduced only in AVX2.
10794 if (Subtarget->hasAVX2())
10801 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10802 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10805 // FIXME: We should custom lower this by fixing the condition and using i8
10811 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10812 MVT VT = Op.getSimpleValueType();
10815 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10818 if (VT.getSizeInBits() == 8) {
10819 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10820 Op.getOperand(0), Op.getOperand(1));
10821 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10822 DAG.getValueType(VT));
10823 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10826 if (VT.getSizeInBits() == 16) {
10827 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10828 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10830 return DAG.getNode(
10831 ISD::TRUNCATE, dl, MVT::i16,
10832 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10833 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10834 Op.getOperand(1)));
10835 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10836 Op.getOperand(0), Op.getOperand(1));
10837 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10838 DAG.getValueType(VT));
10839 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10842 if (VT == MVT::f32) {
10843 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10844 // the result back to FR32 register. It's only worth matching if the
10845 // result has a single use which is a store or a bitcast to i32. And in
10846 // the case of a store, it's not worth it if the index is a constant 0,
10847 // because a MOVSSmr can be used instead, which is smaller and faster.
10848 if (!Op.hasOneUse())
10850 SDNode *User = *Op.getNode()->use_begin();
10851 if ((User->getOpcode() != ISD::STORE ||
10852 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10853 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10854 (User->getOpcode() != ISD::BITCAST ||
10855 User->getValueType(0) != MVT::i32))
10857 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10858 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10860 return DAG.getBitcast(MVT::f32, Extract);
10863 if (VT == MVT::i32 || VT == MVT::i64) {
10864 // ExtractPS/pextrq works with constant index.
10865 if (isa<ConstantSDNode>(Op.getOperand(1)))
10871 /// Extract one bit from mask vector, like v16i1 or v8i1.
10872 /// AVX-512 feature.
10874 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10875 SDValue Vec = Op.getOperand(0);
10877 MVT VecVT = Vec.getSimpleValueType();
10878 SDValue Idx = Op.getOperand(1);
10879 MVT EltVT = Op.getSimpleValueType();
10881 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10882 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10883 "Unexpected vector type in ExtractBitFromMaskVector");
10885 // variable index can't be handled in mask registers,
10886 // extend vector to VR512
10887 if (!isa<ConstantSDNode>(Idx)) {
10888 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10889 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10890 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10891 ExtVT.getVectorElementType(), Ext, Idx);
10892 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10895 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10896 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10897 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10898 rc = getRegClassFor(MVT::v16i1);
10899 unsigned MaxSift = rc->getSize()*8 - 1;
10900 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10901 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10902 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10903 DAG.getConstant(MaxSift, dl, MVT::i8));
10904 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10905 DAG.getIntPtrConstant(0, dl));
10909 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10910 SelectionDAG &DAG) const {
10912 SDValue Vec = Op.getOperand(0);
10913 MVT VecVT = Vec.getSimpleValueType();
10914 SDValue Idx = Op.getOperand(1);
10916 if (Op.getSimpleValueType() == MVT::i1)
10917 return ExtractBitFromMaskVector(Op, DAG);
10919 if (!isa<ConstantSDNode>(Idx)) {
10920 if (VecVT.is512BitVector() ||
10921 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10922 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10925 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10926 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10927 MaskEltVT.getSizeInBits());
10929 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10930 auto PtrVT = getPointerTy(DAG.getDataLayout());
10931 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10932 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10933 DAG.getConstant(0, dl, PtrVT));
10934 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10935 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10936 DAG.getConstant(0, dl, PtrVT));
10941 // If this is a 256-bit vector result, first extract the 128-bit vector and
10942 // then extract the element from the 128-bit vector.
10943 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10945 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10946 // Get the 128-bit vector.
10947 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10948 MVT EltVT = VecVT.getVectorElementType();
10950 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10952 //if (IdxVal >= NumElems/2)
10953 // IdxVal -= NumElems/2;
10954 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10955 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10956 DAG.getConstant(IdxVal, dl, MVT::i32));
10959 assert(VecVT.is128BitVector() && "Unexpected vector length");
10961 if (Subtarget->hasSSE41())
10962 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10965 MVT VT = Op.getSimpleValueType();
10966 // TODO: handle v16i8.
10967 if (VT.getSizeInBits() == 16) {
10968 SDValue Vec = Op.getOperand(0);
10969 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10971 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10972 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10973 DAG.getBitcast(MVT::v4i32, Vec),
10974 Op.getOperand(1)));
10975 // Transform it so it match pextrw which produces a 32-bit result.
10976 MVT EltVT = MVT::i32;
10977 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10978 Op.getOperand(0), Op.getOperand(1));
10979 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10980 DAG.getValueType(VT));
10981 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10984 if (VT.getSizeInBits() == 32) {
10985 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10989 // SHUFPS the element to the lowest double word, then movss.
10990 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10991 MVT VVT = Op.getOperand(0).getSimpleValueType();
10992 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10993 DAG.getUNDEF(VVT), Mask);
10994 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10995 DAG.getIntPtrConstant(0, dl));
10998 if (VT.getSizeInBits() == 64) {
10999 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11000 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11001 // to match extract_elt for f64.
11002 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11006 // UNPCKHPD the element to the lowest double word, then movsd.
11007 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11008 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11009 int Mask[2] = { 1, -1 };
11010 MVT VVT = Op.getOperand(0).getSimpleValueType();
11011 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11012 DAG.getUNDEF(VVT), Mask);
11013 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11014 DAG.getIntPtrConstant(0, dl));
11020 /// Insert one bit to mask vector, like v16i1 or v8i1.
11021 /// AVX-512 feature.
11023 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11025 SDValue Vec = Op.getOperand(0);
11026 SDValue Elt = Op.getOperand(1);
11027 SDValue Idx = Op.getOperand(2);
11028 MVT VecVT = Vec.getSimpleValueType();
11030 if (!isa<ConstantSDNode>(Idx)) {
11031 // Non constant index. Extend source and destination,
11032 // insert element and then truncate the result.
11033 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11034 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
11035 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11036 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11037 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11038 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11041 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11042 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11044 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11045 DAG.getConstant(IdxVal, dl, MVT::i8));
11046 if (Vec.getOpcode() == ISD::UNDEF)
11048 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11051 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11052 SelectionDAG &DAG) const {
11053 MVT VT = Op.getSimpleValueType();
11054 MVT EltVT = VT.getVectorElementType();
11056 if (EltVT == MVT::i1)
11057 return InsertBitToMaskVector(Op, DAG);
11060 SDValue N0 = Op.getOperand(0);
11061 SDValue N1 = Op.getOperand(1);
11062 SDValue N2 = Op.getOperand(2);
11063 if (!isa<ConstantSDNode>(N2))
11065 auto *N2C = cast<ConstantSDNode>(N2);
11066 unsigned IdxVal = N2C->getZExtValue();
11068 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11069 // into that, and then insert the subvector back into the result.
11070 if (VT.is256BitVector() || VT.is512BitVector()) {
11071 // With a 256-bit vector, we can insert into the zero element efficiently
11072 // using a blend if we have AVX or AVX2 and the right data type.
11073 if (VT.is256BitVector() && IdxVal == 0) {
11074 // TODO: It is worthwhile to cast integer to floating point and back
11075 // and incur a domain crossing penalty if that's what we'll end up
11076 // doing anyway after extracting to a 128-bit vector.
11077 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11078 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11079 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11080 N2 = DAG.getIntPtrConstant(1, dl);
11081 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11085 // Get the desired 128-bit vector chunk.
11086 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11088 // Insert the element into the desired chunk.
11089 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11090 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11092 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11093 DAG.getConstant(IdxIn128, dl, MVT::i32));
11095 // Insert the changed part back into the bigger vector
11096 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11098 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11100 if (Subtarget->hasSSE41()) {
11101 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11103 if (VT == MVT::v8i16) {
11104 Opc = X86ISD::PINSRW;
11106 assert(VT == MVT::v16i8);
11107 Opc = X86ISD::PINSRB;
11110 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11112 if (N1.getValueType() != MVT::i32)
11113 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11114 if (N2.getValueType() != MVT::i32)
11115 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11116 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11119 if (EltVT == MVT::f32) {
11120 // Bits [7:6] of the constant are the source select. This will always be
11121 // zero here. The DAG Combiner may combine an extract_elt index into
11122 // these bits. For example (insert (extract, 3), 2) could be matched by
11123 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11124 // Bits [5:4] of the constant are the destination select. This is the
11125 // value of the incoming immediate.
11126 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11127 // combine either bitwise AND or insert of float 0.0 to set these bits.
11129 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11130 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11131 // If this is an insertion of 32-bits into the low 32-bits of
11132 // a vector, we prefer to generate a blend with immediate rather
11133 // than an insertps. Blends are simpler operations in hardware and so
11134 // will always have equal or better performance than insertps.
11135 // But if optimizing for size and there's a load folding opportunity,
11136 // generate insertps because blendps does not have a 32-bit memory
11138 N2 = DAG.getIntPtrConstant(1, dl);
11139 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11140 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11142 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11143 // Create this as a scalar to vector..
11144 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11145 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11148 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11149 // PINSR* works with constant index.
11154 if (EltVT == MVT::i8)
11157 if (EltVT.getSizeInBits() == 16) {
11158 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11159 // as its second argument.
11160 if (N1.getValueType() != MVT::i32)
11161 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11162 if (N2.getValueType() != MVT::i32)
11163 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11164 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11169 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11171 MVT OpVT = Op.getSimpleValueType();
11173 // If this is a 256-bit vector result, first insert into a 128-bit
11174 // vector and then insert into the 256-bit vector.
11175 if (!OpVT.is128BitVector()) {
11176 // Insert into a 128-bit vector.
11177 unsigned SizeFactor = OpVT.getSizeInBits()/128;
11178 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11179 OpVT.getVectorNumElements() / SizeFactor);
11181 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11183 // Insert the 128-bit vector.
11184 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11187 if (OpVT == MVT::v1i64 &&
11188 Op.getOperand(0).getValueType() == MVT::i64)
11189 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11191 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11192 assert(OpVT.is128BitVector() && "Expected an SSE type!");
11193 return DAG.getBitcast(
11194 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11197 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
11198 // a simple subregister reference or explicit instructions to grab
11199 // upper bits of a vector.
11200 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11201 SelectionDAG &DAG) {
11203 SDValue In = Op.getOperand(0);
11204 SDValue Idx = Op.getOperand(1);
11205 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11206 MVT ResVT = Op.getSimpleValueType();
11207 MVT InVT = In.getSimpleValueType();
11209 if (Subtarget->hasFp256()) {
11210 if (ResVT.is128BitVector() &&
11211 (InVT.is256BitVector() || InVT.is512BitVector()) &&
11212 isa<ConstantSDNode>(Idx)) {
11213 return Extract128BitVector(In, IdxVal, DAG, dl);
11215 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11216 isa<ConstantSDNode>(Idx)) {
11217 return Extract256BitVector(In, IdxVal, DAG, dl);
11223 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
11224 // simple superregister reference or explicit instructions to insert
11225 // the upper bits of a vector.
11226 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11227 SelectionDAG &DAG) {
11228 if (!Subtarget->hasAVX())
11232 SDValue Vec = Op.getOperand(0);
11233 SDValue SubVec = Op.getOperand(1);
11234 SDValue Idx = Op.getOperand(2);
11236 if (!isa<ConstantSDNode>(Idx))
11239 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11240 MVT OpVT = Op.getSimpleValueType();
11241 MVT SubVecVT = SubVec.getSimpleValueType();
11243 // Fold two 16-byte subvector loads into one 32-byte load:
11244 // (insert_subvector (insert_subvector undef, (load addr), 0),
11245 // (load addr + 16), Elts/2)
11247 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11248 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11249 OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11250 !Subtarget->isUnalignedMem32Slow()) {
11251 SDValue SubVec2 = Vec.getOperand(1);
11252 if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11253 if (Idx2->getZExtValue() == 0) {
11254 SDValue Ops[] = { SubVec2, SubVec };
11255 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11261 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11262 SubVecVT.is128BitVector())
11263 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11265 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11266 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11268 if (OpVT.getVectorElementType() == MVT::i1) {
11269 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11271 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11272 SDValue Undef = DAG.getUNDEF(OpVT);
11273 unsigned NumElems = OpVT.getVectorNumElements();
11274 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11276 if (IdxVal == OpVT.getVectorNumElements() / 2) {
11277 // Zero upper bits of the Vec
11278 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11279 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11281 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11283 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11284 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11287 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11289 // Zero upper bits of the Vec2
11290 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11291 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11292 // Zero lower bits of the Vec
11293 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11294 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11295 // Merge them together
11296 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11302 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11303 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11304 // one of the above mentioned nodes. It has to be wrapped because otherwise
11305 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11306 // be used to form addressing mode. These wrapped nodes will be selected
11309 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11310 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11312 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11313 // global base reg.
11314 unsigned char OpFlag = 0;
11315 unsigned WrapperKind = X86ISD::Wrapper;
11316 CodeModel::Model M = DAG.getTarget().getCodeModel();
11318 if (Subtarget->isPICStyleRIPRel() &&
11319 (M == CodeModel::Small || M == CodeModel::Kernel))
11320 WrapperKind = X86ISD::WrapperRIP;
11321 else if (Subtarget->isPICStyleGOT())
11322 OpFlag = X86II::MO_GOTOFF;
11323 else if (Subtarget->isPICStyleStubPIC())
11324 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11326 auto PtrVT = getPointerTy(DAG.getDataLayout());
11327 SDValue Result = DAG.getTargetConstantPool(
11328 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11330 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11331 // With PIC, the address is actually $g + Offset.
11334 DAG.getNode(ISD::ADD, DL, PtrVT,
11335 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11341 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11342 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11344 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11345 // global base reg.
11346 unsigned char OpFlag = 0;
11347 unsigned WrapperKind = X86ISD::Wrapper;
11348 CodeModel::Model M = DAG.getTarget().getCodeModel();
11350 if (Subtarget->isPICStyleRIPRel() &&
11351 (M == CodeModel::Small || M == CodeModel::Kernel))
11352 WrapperKind = X86ISD::WrapperRIP;
11353 else if (Subtarget->isPICStyleGOT())
11354 OpFlag = X86II::MO_GOTOFF;
11355 else if (Subtarget->isPICStyleStubPIC())
11356 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11358 auto PtrVT = getPointerTy(DAG.getDataLayout());
11359 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11361 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11363 // With PIC, the address is actually $g + Offset.
11366 DAG.getNode(ISD::ADD, DL, PtrVT,
11367 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11373 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11374 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11376 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11377 // global base reg.
11378 unsigned char OpFlag = 0;
11379 unsigned WrapperKind = X86ISD::Wrapper;
11380 CodeModel::Model M = DAG.getTarget().getCodeModel();
11382 if (Subtarget->isPICStyleRIPRel() &&
11383 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11384 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11385 OpFlag = X86II::MO_GOTPCREL;
11386 WrapperKind = X86ISD::WrapperRIP;
11387 } else if (Subtarget->isPICStyleGOT()) {
11388 OpFlag = X86II::MO_GOT;
11389 } else if (Subtarget->isPICStyleStubPIC()) {
11390 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11391 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11392 OpFlag = X86II::MO_DARWIN_NONLAZY;
11395 auto PtrVT = getPointerTy(DAG.getDataLayout());
11396 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11399 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11401 // With PIC, the address is actually $g + Offset.
11402 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11403 !Subtarget->is64Bit()) {
11405 DAG.getNode(ISD::ADD, DL, PtrVT,
11406 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11409 // For symbols that require a load from a stub to get the address, emit the
11411 if (isGlobalStubReference(OpFlag))
11412 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11413 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11414 false, false, false, 0);
11420 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11421 // Create the TargetBlockAddressAddress node.
11422 unsigned char OpFlags =
11423 Subtarget->ClassifyBlockAddressReference();
11424 CodeModel::Model M = DAG.getTarget().getCodeModel();
11425 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11426 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11428 auto PtrVT = getPointerTy(DAG.getDataLayout());
11429 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11431 if (Subtarget->isPICStyleRIPRel() &&
11432 (M == CodeModel::Small || M == CodeModel::Kernel))
11433 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11435 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11437 // With PIC, the address is actually $g + Offset.
11438 if (isGlobalRelativeToPICBase(OpFlags)) {
11439 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11440 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11447 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11448 int64_t Offset, SelectionDAG &DAG) const {
11449 // Create the TargetGlobalAddress node, folding in the constant
11450 // offset if it is legal.
11451 unsigned char OpFlags =
11452 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11453 CodeModel::Model M = DAG.getTarget().getCodeModel();
11454 auto PtrVT = getPointerTy(DAG.getDataLayout());
11456 if (OpFlags == X86II::MO_NO_FLAG &&
11457 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11458 // A direct static reference to a global.
11459 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11462 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11465 if (Subtarget->isPICStyleRIPRel() &&
11466 (M == CodeModel::Small || M == CodeModel::Kernel))
11467 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11469 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11471 // With PIC, the address is actually $g + Offset.
11472 if (isGlobalRelativeToPICBase(OpFlags)) {
11473 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11474 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11477 // For globals that require a load from a stub to get the address, emit the
11479 if (isGlobalStubReference(OpFlags))
11480 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11481 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11482 false, false, false, 0);
11484 // If there was a non-zero offset that we didn't fold, create an explicit
11485 // addition for it.
11487 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11488 DAG.getConstant(Offset, dl, PtrVT));
11494 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11495 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11496 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11497 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11501 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11502 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11503 unsigned char OperandFlags, bool LocalDynamic = false) {
11504 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11505 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11507 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11508 GA->getValueType(0),
11512 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11516 SDValue Ops[] = { Chain, TGA, *InFlag };
11517 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11519 SDValue Ops[] = { Chain, TGA };
11520 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11523 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11524 MFI->setAdjustsStack(true);
11525 MFI->setHasCalls(true);
11527 SDValue Flag = Chain.getValue(1);
11528 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11531 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11533 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11536 SDLoc dl(GA); // ? function entry point might be better
11537 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11538 DAG.getNode(X86ISD::GlobalBaseReg,
11539 SDLoc(), PtrVT), InFlag);
11540 InFlag = Chain.getValue(1);
11542 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11545 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11547 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11549 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11550 X86::RAX, X86II::MO_TLSGD);
11553 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11559 // Get the start address of the TLS block for this module.
11560 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11561 .getInfo<X86MachineFunctionInfo>();
11562 MFI->incNumLocalDynamicTLSAccesses();
11566 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11567 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11570 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11571 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11572 InFlag = Chain.getValue(1);
11573 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11574 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11577 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11581 unsigned char OperandFlags = X86II::MO_DTPOFF;
11582 unsigned WrapperKind = X86ISD::Wrapper;
11583 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11584 GA->getValueType(0),
11585 GA->getOffset(), OperandFlags);
11586 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11588 // Add x@dtpoff with the base.
11589 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11592 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11593 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11594 const EVT PtrVT, TLSModel::Model model,
11595 bool is64Bit, bool isPIC) {
11598 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11599 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11600 is64Bit ? 257 : 256));
11602 SDValue ThreadPointer =
11603 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11604 MachinePointerInfo(Ptr), false, false, false, 0);
11606 unsigned char OperandFlags = 0;
11607 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11609 unsigned WrapperKind = X86ISD::Wrapper;
11610 if (model == TLSModel::LocalExec) {
11611 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11612 } else if (model == TLSModel::InitialExec) {
11614 OperandFlags = X86II::MO_GOTTPOFF;
11615 WrapperKind = X86ISD::WrapperRIP;
11617 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11620 llvm_unreachable("Unexpected model");
11623 // emit "addl x@ntpoff,%eax" (local exec)
11624 // or "addl x@indntpoff,%eax" (initial exec)
11625 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11627 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11628 GA->getOffset(), OperandFlags);
11629 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11631 if (model == TLSModel::InitialExec) {
11632 if (isPIC && !is64Bit) {
11633 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11634 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11638 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11639 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11640 false, false, false, 0);
11643 // The address of the thread local variable is the add of the thread
11644 // pointer with the offset of the variable.
11645 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11649 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11651 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11652 const GlobalValue *GV = GA->getGlobal();
11653 auto PtrVT = getPointerTy(DAG.getDataLayout());
11655 if (Subtarget->isTargetELF()) {
11656 if (DAG.getTarget().Options.EmulatedTLS)
11657 return LowerToTLSEmulatedModel(GA, DAG);
11658 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11660 case TLSModel::GeneralDynamic:
11661 if (Subtarget->is64Bit())
11662 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11663 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11664 case TLSModel::LocalDynamic:
11665 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11666 Subtarget->is64Bit());
11667 case TLSModel::InitialExec:
11668 case TLSModel::LocalExec:
11669 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11670 DAG.getTarget().getRelocationModel() ==
11673 llvm_unreachable("Unknown TLS model.");
11676 if (Subtarget->isTargetDarwin()) {
11677 // Darwin only has one model of TLS. Lower to that.
11678 unsigned char OpFlag = 0;
11679 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11680 X86ISD::WrapperRIP : X86ISD::Wrapper;
11682 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11683 // global base reg.
11684 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11685 !Subtarget->is64Bit();
11687 OpFlag = X86II::MO_TLVP_PIC_BASE;
11689 OpFlag = X86II::MO_TLVP;
11691 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11692 GA->getValueType(0),
11693 GA->getOffset(), OpFlag);
11694 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11696 // With PIC32, the address is actually $g + Offset.
11698 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11699 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11702 // Lowering the machine isd will make sure everything is in the right
11704 SDValue Chain = DAG.getEntryNode();
11705 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11706 SDValue Args[] = { Chain, Offset };
11707 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11709 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11710 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11711 MFI->setAdjustsStack(true);
11713 // And our return value (tls address) is in the standard call return value
11715 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11716 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11719 if (Subtarget->isTargetKnownWindowsMSVC() ||
11720 Subtarget->isTargetWindowsGNU()) {
11721 // Just use the implicit TLS architecture
11722 // Need to generate someting similar to:
11723 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11725 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11726 // mov rcx, qword [rdx+rcx*8]
11727 // mov eax, .tls$:tlsvar
11728 // [rax+rcx] contains the address
11729 // Windows 64bit: gs:0x58
11730 // Windows 32bit: fs:__tls_array
11733 SDValue Chain = DAG.getEntryNode();
11735 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11736 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11737 // use its literal value of 0x2C.
11738 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11739 ? Type::getInt8PtrTy(*DAG.getContext(),
11741 : Type::getInt32PtrTy(*DAG.getContext(),
11744 SDValue TlsArray = Subtarget->is64Bit()
11745 ? DAG.getIntPtrConstant(0x58, dl)
11746 : (Subtarget->isTargetWindowsGNU()
11747 ? DAG.getIntPtrConstant(0x2C, dl)
11748 : DAG.getExternalSymbol("_tls_array", PtrVT));
11750 SDValue ThreadPointer =
11751 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11755 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11756 res = ThreadPointer;
11758 // Load the _tls_index variable
11759 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11760 if (Subtarget->is64Bit())
11761 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11762 MachinePointerInfo(), MVT::i32, false, false,
11765 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11768 auto &DL = DAG.getDataLayout();
11770 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11771 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11773 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11776 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11779 // Get the offset of start of .tls section
11780 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11781 GA->getValueType(0),
11782 GA->getOffset(), X86II::MO_SECREL);
11783 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11785 // The address of the thread local variable is the add of the thread
11786 // pointer with the offset of the variable.
11787 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11790 llvm_unreachable("TLS not implemented for this target.");
11793 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11794 /// and take a 2 x i32 value to shift plus a shift amount.
11795 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11796 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11797 MVT VT = Op.getSimpleValueType();
11798 unsigned VTBits = VT.getSizeInBits();
11800 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11801 SDValue ShOpLo = Op.getOperand(0);
11802 SDValue ShOpHi = Op.getOperand(1);
11803 SDValue ShAmt = Op.getOperand(2);
11804 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11805 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11807 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11808 DAG.getConstant(VTBits - 1, dl, MVT::i8));
11809 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11810 DAG.getConstant(VTBits - 1, dl, MVT::i8))
11811 : DAG.getConstant(0, dl, VT);
11813 SDValue Tmp2, Tmp3;
11814 if (Op.getOpcode() == ISD::SHL_PARTS) {
11815 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11816 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11818 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11819 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11822 // If the shift amount is larger or equal than the width of a part we can't
11823 // rely on the results of shld/shrd. Insert a test and select the appropriate
11824 // values for large shift amounts.
11825 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11826 DAG.getConstant(VTBits, dl, MVT::i8));
11827 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11828 AndNode, DAG.getConstant(0, dl, MVT::i8));
11831 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11832 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11833 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11835 if (Op.getOpcode() == ISD::SHL_PARTS) {
11836 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11837 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11839 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11840 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11843 SDValue Ops[2] = { Lo, Hi };
11844 return DAG.getMergeValues(Ops, dl);
11847 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11848 SelectionDAG &DAG) const {
11849 SDValue Src = Op.getOperand(0);
11850 MVT SrcVT = Src.getSimpleValueType();
11851 MVT VT = Op.getSimpleValueType();
11854 if (SrcVT.isVector()) {
11855 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11856 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11857 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11858 DAG.getUNDEF(SrcVT)));
11860 if (SrcVT.getVectorElementType() == MVT::i1) {
11861 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11862 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11863 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11868 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11869 "Unknown SINT_TO_FP to lower!");
11871 // These are really Legal; return the operand so the caller accepts it as
11873 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11875 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11876 Subtarget->is64Bit()) {
11880 unsigned Size = SrcVT.getSizeInBits()/8;
11881 MachineFunction &MF = DAG.getMachineFunction();
11882 auto PtrVT = getPointerTy(MF.getDataLayout());
11883 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11884 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11885 SDValue Chain = DAG.getStore(
11886 DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
11887 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
11889 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11892 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11894 SelectionDAG &DAG) const {
11898 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11900 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11902 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11904 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11906 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11907 MachineMemOperand *MMO;
11909 int SSFI = FI->getIndex();
11910 MMO = DAG.getMachineFunction().getMachineMemOperand(
11911 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11912 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11914 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11915 StackSlot = StackSlot.getOperand(1);
11917 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11918 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11920 Tys, Ops, SrcVT, MMO);
11923 Chain = Result.getValue(1);
11924 SDValue InFlag = Result.getValue(2);
11926 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11927 // shouldn't be necessary except that RFP cannot be live across
11928 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11929 MachineFunction &MF = DAG.getMachineFunction();
11930 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11931 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11932 auto PtrVT = getPointerTy(MF.getDataLayout());
11933 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11934 Tys = DAG.getVTList(MVT::Other);
11936 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11938 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
11939 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11940 MachineMemOperand::MOStore, SSFISize, SSFISize);
11942 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11943 Ops, Op.getValueType(), MMO);
11944 Result = DAG.getLoad(
11945 Op.getValueType(), DL, Chain, StackSlot,
11946 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11947 false, false, false, 0);
11953 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11954 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11955 SelectionDAG &DAG) const {
11956 // This algorithm is not obvious. Here it is what we're trying to output:
11959 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11960 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11962 haddpd %xmm0, %xmm0
11964 pshufd $0x4e, %xmm0, %xmm1
11970 LLVMContext *Context = DAG.getContext();
11972 // Build some magic constants.
11973 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11974 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11975 auto PtrVT = getPointerTy(DAG.getDataLayout());
11976 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
11978 SmallVector<Constant*,2> CV1;
11980 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11981 APInt(64, 0x4330000000000000ULL))));
11983 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11984 APInt(64, 0x4530000000000000ULL))));
11985 Constant *C1 = ConstantVector::get(CV1);
11986 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
11988 // Load the 64-bit value into an XMM register.
11989 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11992 DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11993 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
11994 false, false, false, 16);
11996 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11999 DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12000 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12001 false, false, false, 16);
12002 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12003 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12006 if (Subtarget->hasSSE3()) {
12007 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12008 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12010 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12011 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12013 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12014 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12017 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12018 DAG.getIntPtrConstant(0, dl));
12021 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12022 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12023 SelectionDAG &DAG) const {
12025 // FP constant to bias correct the final result.
12026 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12029 // Load the 32-bit value into an XMM register.
12030 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12033 // Zero out the upper parts of the register.
12034 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12036 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12037 DAG.getBitcast(MVT::v2f64, Load),
12038 DAG.getIntPtrConstant(0, dl));
12040 // Or the load with the bias.
12041 SDValue Or = DAG.getNode(
12042 ISD::OR, dl, MVT::v2i64,
12043 DAG.getBitcast(MVT::v2i64,
12044 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12045 DAG.getBitcast(MVT::v2i64,
12046 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12048 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12049 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12051 // Subtract the bias.
12052 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12054 // Handle final rounding.
12055 EVT DestVT = Op.getValueType();
12057 if (DestVT.bitsLT(MVT::f64))
12058 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12059 DAG.getIntPtrConstant(0, dl));
12060 if (DestVT.bitsGT(MVT::f64))
12061 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12063 // Handle final rounding.
12067 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12068 const X86Subtarget &Subtarget) {
12069 // The algorithm is the following:
12070 // #ifdef __SSE4_1__
12071 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12072 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12073 // (uint4) 0x53000000, 0xaa);
12075 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12076 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12078 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12079 // return (float4) lo + fhi;
12082 SDValue V = Op->getOperand(0);
12083 EVT VecIntVT = V.getValueType();
12084 bool Is128 = VecIntVT == MVT::v4i32;
12085 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12086 // If we convert to something else than the supported type, e.g., to v4f64,
12088 if (VecFloatVT != Op->getValueType(0))
12091 unsigned NumElts = VecIntVT.getVectorNumElements();
12092 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12093 "Unsupported custom type");
12094 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12096 // In the #idef/#else code, we have in common:
12097 // - The vector of constants:
12103 // Create the splat vector for 0x4b000000.
12104 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12105 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12106 CstLow, CstLow, CstLow, CstLow};
12107 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12108 makeArrayRef(&CstLowArray[0], NumElts));
12109 // Create the splat vector for 0x53000000.
12110 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12111 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12112 CstHigh, CstHigh, CstHigh, CstHigh};
12113 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12114 makeArrayRef(&CstHighArray[0], NumElts));
12116 // Create the right shift.
12117 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12118 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12119 CstShift, CstShift, CstShift, CstShift};
12120 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12121 makeArrayRef(&CstShiftArray[0], NumElts));
12122 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12125 if (Subtarget.hasSSE41()) {
12126 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12127 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12128 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12129 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12130 // Low will be bitcasted right away, so do not bother bitcasting back to its
12132 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12133 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12134 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12135 // (uint4) 0x53000000, 0xaa);
12136 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12137 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12138 // High will be bitcasted right away, so do not bother bitcasting back to
12139 // its original type.
12140 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12141 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12143 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12144 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12145 CstMask, CstMask, CstMask);
12146 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12147 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12148 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12150 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12151 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12154 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12155 SDValue CstFAdd = DAG.getConstantFP(
12156 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12157 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12158 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12159 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12160 makeArrayRef(&CstFAddArray[0], NumElts));
12162 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12163 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12165 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12166 // return (float4) lo + fhi;
12167 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12168 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12171 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12172 SelectionDAG &DAG) const {
12173 SDValue N0 = Op.getOperand(0);
12174 MVT SVT = N0.getSimpleValueType();
12177 switch (SVT.SimpleTy) {
12179 llvm_unreachable("Custom UINT_TO_FP is not supported!");
12184 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12185 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12186 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12190 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12193 if (Subtarget->hasAVX512())
12194 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12195 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12197 llvm_unreachable(nullptr);
12200 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12201 SelectionDAG &DAG) const {
12202 SDValue N0 = Op.getOperand(0);
12204 auto PtrVT = getPointerTy(DAG.getDataLayout());
12206 if (Op.getValueType().isVector())
12207 return lowerUINT_TO_FP_vec(Op, DAG);
12209 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12210 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12211 // the optimization here.
12212 if (DAG.SignBitIsZero(N0))
12213 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12215 MVT SrcVT = N0.getSimpleValueType();
12216 MVT DstVT = Op.getSimpleValueType();
12217 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12218 return LowerUINT_TO_FP_i64(Op, DAG);
12219 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12220 return LowerUINT_TO_FP_i32(Op, DAG);
12221 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12224 // Make a 64-bit buffer, and use it to build an FILD.
12225 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12226 if (SrcVT == MVT::i32) {
12227 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12228 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12229 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12230 StackSlot, MachinePointerInfo(),
12232 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12233 OffsetSlot, MachinePointerInfo(),
12235 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12239 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12240 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12241 StackSlot, MachinePointerInfo(),
12243 // For i64 source, we need to add the appropriate power of 2 if the input
12244 // was negative. This is the same as the optimization in
12245 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12246 // we must be careful to do the computation in x87 extended precision, not
12247 // in SSE. (The generic code can't know it's OK to do this, or how to.)
12248 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12249 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12250 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12251 MachineMemOperand::MOLoad, 8, 8);
12253 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12254 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12255 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12258 APInt FF(32, 0x5F800000ULL);
12260 // Check whether the sign bit is set.
12261 SDValue SignSet = DAG.getSetCC(
12262 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12263 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12265 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12266 SDValue FudgePtr = DAG.getConstantPool(
12267 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12269 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12270 SDValue Zero = DAG.getIntPtrConstant(0, dl);
12271 SDValue Four = DAG.getIntPtrConstant(4, dl);
12272 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12274 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12276 // Load the value out, extending it from f32 to f80.
12277 // FIXME: Avoid the extend by constructing the right constant pool?
12278 SDValue Fudge = DAG.getExtLoad(
12279 ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12280 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12281 false, false, false, 4);
12282 // Extend everything to 80 bits to force it to be done on x87.
12283 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12284 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12285 DAG.getIntPtrConstant(0, dl));
12288 std::pair<SDValue,SDValue>
12289 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12290 bool IsSigned, bool IsReplace) const {
12293 EVT DstTy = Op.getValueType();
12294 auto PtrVT = getPointerTy(DAG.getDataLayout());
12296 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12297 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12301 assert(DstTy.getSimpleVT() <= MVT::i64 &&
12302 DstTy.getSimpleVT() >= MVT::i16 &&
12303 "Unknown FP_TO_INT to lower!");
12305 // These are really Legal.
12306 if (DstTy == MVT::i32 &&
12307 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12308 return std::make_pair(SDValue(), SDValue());
12309 if (Subtarget->is64Bit() &&
12310 DstTy == MVT::i64 &&
12311 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12312 return std::make_pair(SDValue(), SDValue());
12314 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12315 // stack slot, or into the FTOL runtime function.
12316 MachineFunction &MF = DAG.getMachineFunction();
12317 unsigned MemSize = DstTy.getSizeInBits()/8;
12318 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12319 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12322 if (!IsSigned && isIntegerTypeFTOL(DstTy))
12323 Opc = X86ISD::WIN_FTOL;
12325 switch (DstTy.getSimpleVT().SimpleTy) {
12326 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12327 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12328 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12329 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12332 SDValue Chain = DAG.getEntryNode();
12333 SDValue Value = Op.getOperand(0);
12334 EVT TheVT = Op.getOperand(0).getValueType();
12335 // FIXME This causes a redundant load/store if the SSE-class value is already
12336 // in memory, such as if it is on the callstack.
12337 if (isScalarFPTypeInSSEReg(TheVT)) {
12338 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12339 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12340 MachinePointerInfo::getFixedStack(MF, SSFI), false,
12342 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12344 Chain, StackSlot, DAG.getValueType(TheVT)
12347 MachineMemOperand *MMO =
12348 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12349 MachineMemOperand::MOLoad, MemSize, MemSize);
12350 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12351 Chain = Value.getValue(1);
12352 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12353 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12356 MachineMemOperand *MMO =
12357 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12358 MachineMemOperand::MOStore, MemSize, MemSize);
12360 if (Opc != X86ISD::WIN_FTOL) {
12361 // Build the FP_TO_INT*_IN_MEM
12362 SDValue Ops[] = { Chain, Value, StackSlot };
12363 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12365 return std::make_pair(FIST, StackSlot);
12367 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12368 DAG.getVTList(MVT::Other, MVT::Glue),
12370 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12371 MVT::i32, ftol.getValue(1));
12372 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12373 MVT::i32, eax.getValue(2));
12374 SDValue Ops[] = { eax, edx };
12375 SDValue pair = IsReplace
12376 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12377 : DAG.getMergeValues(Ops, DL);
12378 return std::make_pair(pair, SDValue());
12382 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12383 const X86Subtarget *Subtarget) {
12384 MVT VT = Op->getSimpleValueType(0);
12385 SDValue In = Op->getOperand(0);
12386 MVT InVT = In.getSimpleValueType();
12389 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12390 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12392 // Optimize vectors in AVX mode:
12395 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12396 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12397 // Concat upper and lower parts.
12400 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12401 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12402 // Concat upper and lower parts.
12405 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12406 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12407 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12410 if (Subtarget->hasInt256())
12411 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12413 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12414 SDValue Undef = DAG.getUNDEF(InVT);
12415 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12416 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12417 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12419 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12420 VT.getVectorNumElements()/2);
12422 OpLo = DAG.getBitcast(HVT, OpLo);
12423 OpHi = DAG.getBitcast(HVT, OpHi);
12425 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12428 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12429 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12430 MVT VT = Op->getSimpleValueType(0);
12431 SDValue In = Op->getOperand(0);
12432 MVT InVT = In.getSimpleValueType();
12434 unsigned int NumElts = VT.getVectorNumElements();
12435 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12438 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12439 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12441 assert(InVT.getVectorElementType() == MVT::i1);
12442 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12444 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12446 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12448 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12449 if (VT.is512BitVector())
12451 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12454 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12455 SelectionDAG &DAG) {
12456 if (Subtarget->hasFp256())
12457 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12463 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12464 SelectionDAG &DAG) {
12466 MVT VT = Op.getSimpleValueType();
12467 SDValue In = Op.getOperand(0);
12468 MVT SVT = In.getSimpleValueType();
12470 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12471 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12473 if (Subtarget->hasFp256())
12474 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12477 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12478 VT.getVectorNumElements() != SVT.getVectorNumElements());
12482 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12484 MVT VT = Op.getSimpleValueType();
12485 SDValue In = Op.getOperand(0);
12486 MVT InVT = In.getSimpleValueType();
12488 if (VT == MVT::i1) {
12489 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12490 "Invalid scalar TRUNCATE operation");
12491 if (InVT.getSizeInBits() >= 32)
12493 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12494 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12496 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12497 "Invalid TRUNCATE operation");
12499 // move vector to mask - truncate solution for SKX
12500 if (VT.getVectorElementType() == MVT::i1) {
12501 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12502 Subtarget->hasBWI())
12503 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12504 if ((InVT.is256BitVector() || InVT.is128BitVector())
12505 && InVT.getScalarSizeInBits() <= 16 &&
12506 Subtarget->hasBWI() && Subtarget->hasVLX())
12507 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12508 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12509 Subtarget->hasDQI())
12510 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12511 if ((InVT.is256BitVector() || InVT.is128BitVector())
12512 && InVT.getScalarSizeInBits() >= 32 &&
12513 Subtarget->hasDQI() && Subtarget->hasVLX())
12514 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12517 if (VT.getVectorElementType() == MVT::i1) {
12518 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12519 unsigned NumElts = InVT.getVectorNumElements();
12520 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12521 if (InVT.getSizeInBits() < 512) {
12522 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12523 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12528 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12529 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12530 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12533 // vpmovqb/w/d, vpmovdb/w, vpmovwb
12534 if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12535 (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12536 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12538 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12539 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12540 if (Subtarget->hasInt256()) {
12541 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12542 In = DAG.getBitcast(MVT::v8i32, In);
12543 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12545 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12546 DAG.getIntPtrConstant(0, DL));
12549 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12550 DAG.getIntPtrConstant(0, DL));
12551 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12552 DAG.getIntPtrConstant(2, DL));
12553 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12554 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12555 static const int ShufMask[] = {0, 2, 4, 6};
12556 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12559 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12560 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12561 if (Subtarget->hasInt256()) {
12562 In = DAG.getBitcast(MVT::v32i8, In);
12564 SmallVector<SDValue,32> pshufbMask;
12565 for (unsigned i = 0; i < 2; ++i) {
12566 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12567 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12568 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12569 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12570 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12571 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12572 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12573 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12574 for (unsigned j = 0; j < 8; ++j)
12575 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12577 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12578 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12579 In = DAG.getBitcast(MVT::v4i64, In);
12581 static const int ShufMask[] = {0, 2, -1, -1};
12582 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12584 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12585 DAG.getIntPtrConstant(0, DL));
12586 return DAG.getBitcast(VT, In);
12589 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12590 DAG.getIntPtrConstant(0, DL));
12592 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12593 DAG.getIntPtrConstant(4, DL));
12595 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12596 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12598 // The PSHUFB mask:
12599 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12600 -1, -1, -1, -1, -1, -1, -1, -1};
12602 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12603 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12604 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12606 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12607 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12609 // The MOVLHPS Mask:
12610 static const int ShufMask2[] = {0, 1, 4, 5};
12611 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12612 return DAG.getBitcast(MVT::v8i16, res);
12615 // Handle truncation of V256 to V128 using shuffles.
12616 if (!VT.is128BitVector() || !InVT.is256BitVector())
12619 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12621 unsigned NumElems = VT.getVectorNumElements();
12622 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12624 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12625 // Prepare truncation shuffle mask
12626 for (unsigned i = 0; i != NumElems; ++i)
12627 MaskVec[i] = i * 2;
12628 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12629 DAG.getUNDEF(NVT), &MaskVec[0]);
12630 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12631 DAG.getIntPtrConstant(0, DL));
12634 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12635 SelectionDAG &DAG) const {
12636 assert(!Op.getSimpleValueType().isVector());
12638 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12639 /*IsSigned=*/ true, /*IsReplace=*/ false);
12640 SDValue FIST = Vals.first, StackSlot = Vals.second;
12641 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12642 if (!FIST.getNode()) return Op;
12644 if (StackSlot.getNode())
12645 // Load the result.
12646 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12647 FIST, StackSlot, MachinePointerInfo(),
12648 false, false, false, 0);
12650 // The node is the result.
12654 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12655 SelectionDAG &DAG) const {
12656 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12657 /*IsSigned=*/ false, /*IsReplace=*/ false);
12658 SDValue FIST = Vals.first, StackSlot = Vals.second;
12659 assert(FIST.getNode() && "Unexpected failure");
12661 if (StackSlot.getNode())
12662 // Load the result.
12663 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12664 FIST, StackSlot, MachinePointerInfo(),
12665 false, false, false, 0);
12667 // The node is the result.
12671 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12673 MVT VT = Op.getSimpleValueType();
12674 SDValue In = Op.getOperand(0);
12675 MVT SVT = In.getSimpleValueType();
12677 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12679 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12680 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12681 In, DAG.getUNDEF(SVT)));
12684 /// The only differences between FABS and FNEG are the mask and the logic op.
12685 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12686 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12687 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12688 "Wrong opcode for lowering FABS or FNEG.");
12690 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12692 // If this is a FABS and it has an FNEG user, bail out to fold the combination
12693 // into an FNABS. We'll lower the FABS after that if it is still in use.
12695 for (SDNode *User : Op->uses())
12696 if (User->getOpcode() == ISD::FNEG)
12700 MVT VT = Op.getSimpleValueType();
12702 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12703 // decide if we should generate a 16-byte constant mask when we only need 4 or
12704 // 8 bytes for the scalar case.
12710 if (VT.isVector()) {
12712 EltVT = VT.getVectorElementType();
12713 NumElts = VT.getVectorNumElements();
12715 // There are no scalar bitwise logical SSE/AVX instructions, so we
12716 // generate a 16-byte vector constant and logic op even for the scalar case.
12717 // Using a 16-byte mask allows folding the load of the mask with
12718 // the logic op, so it can save (~4 bytes) on code size.
12719 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12721 NumElts = (VT == MVT::f64) ? 2 : 4;
12724 unsigned EltBits = EltVT.getSizeInBits();
12725 LLVMContext *Context = DAG.getContext();
12726 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12728 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12729 Constant *C = ConstantInt::get(*Context, MaskElt);
12730 C = ConstantVector::getSplat(NumElts, C);
12731 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12732 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12733 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12735 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12736 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12737 false, false, false, Alignment);
12739 SDValue Op0 = Op.getOperand(0);
12740 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12742 IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12743 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12746 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12748 // For the scalar case extend to a 128-bit vector, perform the logic op,
12749 // and extract the scalar result back out.
12750 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
12751 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12752 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
12753 DAG.getIntPtrConstant(0, dl));
12756 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12757 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12758 LLVMContext *Context = DAG.getContext();
12759 SDValue Op0 = Op.getOperand(0);
12760 SDValue Op1 = Op.getOperand(1);
12762 MVT VT = Op.getSimpleValueType();
12763 MVT SrcVT = Op1.getSimpleValueType();
12765 // If second operand is smaller, extend it first.
12766 if (SrcVT.bitsLT(VT)) {
12767 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12770 // And if it is bigger, shrink it first.
12771 if (SrcVT.bitsGT(VT)) {
12772 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12776 // At this point the operands and the result should have the same
12777 // type, and that won't be f80 since that is not custom lowered.
12779 const fltSemantics &Sem =
12780 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12781 const unsigned SizeInBits = VT.getSizeInBits();
12783 SmallVector<Constant *, 4> CV(
12784 VT == MVT::f64 ? 2 : 4,
12785 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12787 // First, clear all bits but the sign bit from the second operand (sign).
12788 CV[0] = ConstantFP::get(*Context,
12789 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12790 Constant *C = ConstantVector::get(CV);
12791 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12792 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12794 // Perform all logic operations as 16-byte vectors because there are no
12795 // scalar FP logic instructions in SSE. This allows load folding of the
12796 // constants into the logic instructions.
12797 MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12799 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12800 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12801 false, false, false, 16);
12802 Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
12803 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
12805 // Next, clear the sign bit from the first operand (magnitude).
12806 // If it's a constant, we can clear it here.
12807 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12808 APFloat APF = Op0CN->getValueAPF();
12809 // If the magnitude is a positive zero, the sign bit alone is enough.
12810 if (APF.isPosZero())
12811 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
12812 DAG.getIntPtrConstant(0, dl));
12814 CV[0] = ConstantFP::get(*Context, APF);
12816 CV[0] = ConstantFP::get(
12818 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12820 C = ConstantVector::get(CV);
12821 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12823 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12824 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12825 false, false, false, 16);
12826 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12827 if (!isa<ConstantFPSDNode>(Op0)) {
12828 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
12829 Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
12831 // OR the magnitude value with the sign bit.
12832 Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
12833 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
12834 DAG.getIntPtrConstant(0, dl));
12837 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12838 SDValue N0 = Op.getOperand(0);
12840 MVT VT = Op.getSimpleValueType();
12842 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12843 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12844 DAG.getConstant(1, dl, VT));
12845 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12848 // Check whether an OR'd tree is PTEST-able.
12849 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12850 SelectionDAG &DAG) {
12851 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12853 if (!Subtarget->hasSSE41())
12856 if (!Op->hasOneUse())
12859 SDNode *N = Op.getNode();
12862 SmallVector<SDValue, 8> Opnds;
12863 DenseMap<SDValue, unsigned> VecInMap;
12864 SmallVector<SDValue, 8> VecIns;
12865 EVT VT = MVT::Other;
12867 // Recognize a special case where a vector is casted into wide integer to
12869 Opnds.push_back(N->getOperand(0));
12870 Opnds.push_back(N->getOperand(1));
12872 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12873 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12874 // BFS traverse all OR'd operands.
12875 if (I->getOpcode() == ISD::OR) {
12876 Opnds.push_back(I->getOperand(0));
12877 Opnds.push_back(I->getOperand(1));
12878 // Re-evaluate the number of nodes to be traversed.
12879 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12883 // Quit if a non-EXTRACT_VECTOR_ELT
12884 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12887 // Quit if without a constant index.
12888 SDValue Idx = I->getOperand(1);
12889 if (!isa<ConstantSDNode>(Idx))
12892 SDValue ExtractedFromVec = I->getOperand(0);
12893 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12894 if (M == VecInMap.end()) {
12895 VT = ExtractedFromVec.getValueType();
12896 // Quit if not 128/256-bit vector.
12897 if (!VT.is128BitVector() && !VT.is256BitVector())
12899 // Quit if not the same type.
12900 if (VecInMap.begin() != VecInMap.end() &&
12901 VT != VecInMap.begin()->first.getValueType())
12903 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12904 VecIns.push_back(ExtractedFromVec);
12906 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12909 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12910 "Not extracted from 128-/256-bit vector.");
12912 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12914 for (DenseMap<SDValue, unsigned>::const_iterator
12915 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12916 // Quit if not all elements are used.
12917 if (I->second != FullMask)
12921 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12923 // Cast all vectors into TestVT for PTEST.
12924 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12925 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12927 // If more than one full vectors are evaluated, OR them first before PTEST.
12928 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12929 // Each iteration will OR 2 nodes and append the result until there is only
12930 // 1 node left, i.e. the final OR'd value of all vectors.
12931 SDValue LHS = VecIns[Slot];
12932 SDValue RHS = VecIns[Slot + 1];
12933 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12936 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12937 VecIns.back(), VecIns.back());
12940 /// \brief return true if \c Op has a use that doesn't just read flags.
12941 static bool hasNonFlagsUse(SDValue Op) {
12942 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12944 SDNode *User = *UI;
12945 unsigned UOpNo = UI.getOperandNo();
12946 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12947 // Look pass truncate.
12948 UOpNo = User->use_begin().getOperandNo();
12949 User = *User->use_begin();
12952 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12953 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12959 /// Emit nodes that will be selected as "test Op0,Op0", or something
12961 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12962 SelectionDAG &DAG) const {
12963 if (Op.getValueType() == MVT::i1) {
12964 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12965 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12966 DAG.getConstant(0, dl, MVT::i8));
12968 // CF and OF aren't always set the way we want. Determine which
12969 // of these we need.
12970 bool NeedCF = false;
12971 bool NeedOF = false;
12974 case X86::COND_A: case X86::COND_AE:
12975 case X86::COND_B: case X86::COND_BE:
12978 case X86::COND_G: case X86::COND_GE:
12979 case X86::COND_L: case X86::COND_LE:
12980 case X86::COND_O: case X86::COND_NO: {
12981 // Check if we really need to set the
12982 // Overflow flag. If NoSignedWrap is present
12983 // that is not actually needed.
12984 switch (Op->getOpcode()) {
12989 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12990 if (BinNode->Flags.hasNoSignedWrap())
13000 // See if we can use the EFLAGS value from the operand instead of
13001 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13002 // we prove that the arithmetic won't overflow, we can't use OF or CF.
13003 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13004 // Emit a CMP with 0, which is the TEST pattern.
13005 //if (Op.getValueType() == MVT::i1)
13006 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13007 // DAG.getConstant(0, MVT::i1));
13008 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13009 DAG.getConstant(0, dl, Op.getValueType()));
13011 unsigned Opcode = 0;
13012 unsigned NumOperands = 0;
13014 // Truncate operations may prevent the merge of the SETCC instruction
13015 // and the arithmetic instruction before it. Attempt to truncate the operands
13016 // of the arithmetic instruction and use a reduced bit-width instruction.
13017 bool NeedTruncation = false;
13018 SDValue ArithOp = Op;
13019 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13020 SDValue Arith = Op->getOperand(0);
13021 // Both the trunc and the arithmetic op need to have one user each.
13022 if (Arith->hasOneUse())
13023 switch (Arith.getOpcode()) {
13030 NeedTruncation = true;
13036 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13037 // which may be the result of a CAST. We use the variable 'Op', which is the
13038 // non-casted variable when we check for possible users.
13039 switch (ArithOp.getOpcode()) {
13041 // Due to an isel shortcoming, be conservative if this add is likely to be
13042 // selected as part of a load-modify-store instruction. When the root node
13043 // in a match is a store, isel doesn't know how to remap non-chain non-flag
13044 // uses of other nodes in the match, such as the ADD in this case. This
13045 // leads to the ADD being left around and reselected, with the result being
13046 // two adds in the output. Alas, even if none our users are stores, that
13047 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
13048 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
13049 // climbing the DAG back to the root, and it doesn't seem to be worth the
13051 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13052 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13053 if (UI->getOpcode() != ISD::CopyToReg &&
13054 UI->getOpcode() != ISD::SETCC &&
13055 UI->getOpcode() != ISD::STORE)
13058 if (ConstantSDNode *C =
13059 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13060 // An add of one will be selected as an INC.
13061 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13062 Opcode = X86ISD::INC;
13067 // An add of negative one (subtract of one) will be selected as a DEC.
13068 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13069 Opcode = X86ISD::DEC;
13075 // Otherwise use a regular EFLAGS-setting add.
13076 Opcode = X86ISD::ADD;
13081 // If we have a constant logical shift that's only used in a comparison
13082 // against zero turn it into an equivalent AND. This allows turning it into
13083 // a TEST instruction later.
13084 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13085 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13086 EVT VT = Op.getValueType();
13087 unsigned BitWidth = VT.getSizeInBits();
13088 unsigned ShAmt = Op->getConstantOperandVal(1);
13089 if (ShAmt >= BitWidth) // Avoid undefined shifts.
13091 APInt Mask = ArithOp.getOpcode() == ISD::SRL
13092 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13093 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13094 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13096 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13097 DAG.getConstant(Mask, dl, VT));
13098 DAG.ReplaceAllUsesWith(Op, New);
13104 // If the primary and result isn't used, don't bother using X86ISD::AND,
13105 // because a TEST instruction will be better.
13106 if (!hasNonFlagsUse(Op))
13112 // Due to the ISEL shortcoming noted above, be conservative if this op is
13113 // likely to be selected as part of a load-modify-store instruction.
13114 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13115 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13116 if (UI->getOpcode() == ISD::STORE)
13119 // Otherwise use a regular EFLAGS-setting instruction.
13120 switch (ArithOp.getOpcode()) {
13121 default: llvm_unreachable("unexpected operator!");
13122 case ISD::SUB: Opcode = X86ISD::SUB; break;
13123 case ISD::XOR: Opcode = X86ISD::XOR; break;
13124 case ISD::AND: Opcode = X86ISD::AND; break;
13126 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13127 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13128 if (EFLAGS.getNode())
13131 Opcode = X86ISD::OR;
13145 return SDValue(Op.getNode(), 1);
13151 // If we found that truncation is beneficial, perform the truncation and
13153 if (NeedTruncation) {
13154 EVT VT = Op.getValueType();
13155 SDValue WideVal = Op->getOperand(0);
13156 EVT WideVT = WideVal.getValueType();
13157 unsigned ConvertedOp = 0;
13158 // Use a target machine opcode to prevent further DAGCombine
13159 // optimizations that may separate the arithmetic operations
13160 // from the setcc node.
13161 switch (WideVal.getOpcode()) {
13163 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13164 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13165 case ISD::AND: ConvertedOp = X86ISD::AND; break;
13166 case ISD::OR: ConvertedOp = X86ISD::OR; break;
13167 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13171 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13172 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13173 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13174 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13175 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13181 // Emit a CMP with 0, which is the TEST pattern.
13182 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13183 DAG.getConstant(0, dl, Op.getValueType()));
13185 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13186 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13188 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13189 DAG.ReplaceAllUsesWith(Op, New);
13190 return SDValue(New.getNode(), 1);
13193 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13195 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13196 SDLoc dl, SelectionDAG &DAG) const {
13197 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13198 if (C->getAPIntValue() == 0)
13199 return EmitTest(Op0, X86CC, dl, DAG);
13201 if (Op0.getValueType() == MVT::i1)
13202 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13205 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13206 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13207 // Do the comparison at i32 if it's smaller, besides the Atom case.
13208 // This avoids subregister aliasing issues. Keep the smaller reference
13209 // if we're optimizing for size, however, as that'll allow better folding
13210 // of memory operations.
13211 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13212 !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13213 !Subtarget->isAtom()) {
13214 unsigned ExtendOp =
13215 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13216 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13217 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13219 // Use SUB instead of CMP to enable CSE between SUB and CMP.
13220 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13221 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13223 return SDValue(Sub.getNode(), 1);
13225 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13228 /// Convert a comparison if required by the subtarget.
13229 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13230 SelectionDAG &DAG) const {
13231 // If the subtarget does not support the FUCOMI instruction, floating-point
13232 // comparisons have to be converted.
13233 if (Subtarget->hasCMov() ||
13234 Cmp.getOpcode() != X86ISD::CMP ||
13235 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13236 !Cmp.getOperand(1).getValueType().isFloatingPoint())
13239 // The instruction selector will select an FUCOM instruction instead of
13240 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13241 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13242 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13244 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13245 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13246 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13247 DAG.getConstant(8, dl, MVT::i8));
13248 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13249 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13252 /// The minimum architected relative accuracy is 2^-12. We need one
13253 /// Newton-Raphson step to have a good float result (24 bits of precision).
13254 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13255 DAGCombinerInfo &DCI,
13256 unsigned &RefinementSteps,
13257 bool &UseOneConstNR) const {
13258 EVT VT = Op.getValueType();
13259 const char *RecipOp;
13261 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13262 // TODO: Add support for AVX512 (v16f32).
13263 // It is likely not profitable to do this for f64 because a double-precision
13264 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13265 // instructions: convert to single, rsqrtss, convert back to double, refine
13266 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13267 // along with FMA, this could be a throughput win.
13268 if (VT == MVT::f32 && Subtarget->hasSSE1())
13270 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13271 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13272 RecipOp = "vec-sqrtf";
13276 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13277 if (!Recips.isEnabled(RecipOp))
13280 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13281 UseOneConstNR = false;
13282 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13285 /// The minimum architected relative accuracy is 2^-12. We need one
13286 /// Newton-Raphson step to have a good float result (24 bits of precision).
13287 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13288 DAGCombinerInfo &DCI,
13289 unsigned &RefinementSteps) const {
13290 EVT VT = Op.getValueType();
13291 const char *RecipOp;
13293 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13294 // TODO: Add support for AVX512 (v16f32).
13295 // It is likely not profitable to do this for f64 because a double-precision
13296 // reciprocal estimate with refinement on x86 prior to FMA requires
13297 // 15 instructions: convert to single, rcpss, convert back to double, refine
13298 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13299 // along with FMA, this could be a throughput win.
13300 if (VT == MVT::f32 && Subtarget->hasSSE1())
13302 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13303 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13304 RecipOp = "vec-divf";
13308 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13309 if (!Recips.isEnabled(RecipOp))
13312 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13313 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13316 /// If we have at least two divisions that use the same divisor, convert to
13317 /// multplication by a reciprocal. This may need to be adjusted for a given
13318 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13319 /// This is because we still need one division to calculate the reciprocal and
13320 /// then we need two multiplies by that reciprocal as replacements for the
13321 /// original divisions.
13322 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13326 static bool isAllOnes(SDValue V) {
13327 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13328 return C && C->isAllOnesValue();
13331 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13332 /// if it's possible.
13333 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13334 SDLoc dl, SelectionDAG &DAG) const {
13335 SDValue Op0 = And.getOperand(0);
13336 SDValue Op1 = And.getOperand(1);
13337 if (Op0.getOpcode() == ISD::TRUNCATE)
13338 Op0 = Op0.getOperand(0);
13339 if (Op1.getOpcode() == ISD::TRUNCATE)
13340 Op1 = Op1.getOperand(0);
13343 if (Op1.getOpcode() == ISD::SHL)
13344 std::swap(Op0, Op1);
13345 if (Op0.getOpcode() == ISD::SHL) {
13346 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13347 if (And00C->getZExtValue() == 1) {
13348 // If we looked past a truncate, check that it's only truncating away
13350 unsigned BitWidth = Op0.getValueSizeInBits();
13351 unsigned AndBitWidth = And.getValueSizeInBits();
13352 if (BitWidth > AndBitWidth) {
13354 DAG.computeKnownBits(Op0, Zeros, Ones);
13355 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13359 RHS = Op0.getOperand(1);
13361 } else if (Op1.getOpcode() == ISD::Constant) {
13362 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13363 uint64_t AndRHSVal = AndRHS->getZExtValue();
13364 SDValue AndLHS = Op0;
13366 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13367 LHS = AndLHS.getOperand(0);
13368 RHS = AndLHS.getOperand(1);
13371 // Use BT if the immediate can't be encoded in a TEST instruction.
13372 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13374 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13378 if (LHS.getNode()) {
13379 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
13380 // instruction. Since the shift amount is in-range-or-undefined, we know
13381 // that doing a bittest on the i32 value is ok. We extend to i32 because
13382 // the encoding for the i16 version is larger than the i32 version.
13383 // Also promote i16 to i32 for performance / code size reason.
13384 if (LHS.getValueType() == MVT::i8 ||
13385 LHS.getValueType() == MVT::i16)
13386 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13388 // If the operand types disagree, extend the shift amount to match. Since
13389 // BT ignores high bits (like shifts) we can use anyextend.
13390 if (LHS.getValueType() != RHS.getValueType())
13391 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13393 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13394 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13395 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13396 DAG.getConstant(Cond, dl, MVT::i8), BT);
13402 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13404 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13409 // SSE Condition code mapping:
13418 switch (SetCCOpcode) {
13419 default: llvm_unreachable("Unexpected SETCC condition");
13421 case ISD::SETEQ: SSECC = 0; break;
13423 case ISD::SETGT: Swap = true; // Fallthrough
13425 case ISD::SETOLT: SSECC = 1; break;
13427 case ISD::SETGE: Swap = true; // Fallthrough
13429 case ISD::SETOLE: SSECC = 2; break;
13430 case ISD::SETUO: SSECC = 3; break;
13432 case ISD::SETNE: SSECC = 4; break;
13433 case ISD::SETULE: Swap = true; // Fallthrough
13434 case ISD::SETUGE: SSECC = 5; break;
13435 case ISD::SETULT: Swap = true; // Fallthrough
13436 case ISD::SETUGT: SSECC = 6; break;
13437 case ISD::SETO: SSECC = 7; break;
13439 case ISD::SETONE: SSECC = 8; break;
13442 std::swap(Op0, Op1);
13447 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13448 // ones, and then concatenate the result back.
13449 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13450 MVT VT = Op.getSimpleValueType();
13452 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13453 "Unsupported value type for operation");
13455 unsigned NumElems = VT.getVectorNumElements();
13457 SDValue CC = Op.getOperand(2);
13459 // Extract the LHS vectors
13460 SDValue LHS = Op.getOperand(0);
13461 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13462 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13464 // Extract the RHS vectors
13465 SDValue RHS = Op.getOperand(1);
13466 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13467 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13469 // Issue the operation on the smaller types and concatenate the result back
13470 MVT EltVT = VT.getVectorElementType();
13471 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13472 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13473 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13474 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13477 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13478 SDValue Op0 = Op.getOperand(0);
13479 SDValue Op1 = Op.getOperand(1);
13480 SDValue CC = Op.getOperand(2);
13481 MVT VT = Op.getSimpleValueType();
13484 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13485 "Unexpected type for boolean compare operation");
13486 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13487 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13488 DAG.getConstant(-1, dl, VT));
13489 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13490 DAG.getConstant(-1, dl, VT));
13491 switch (SetCCOpcode) {
13492 default: llvm_unreachable("Unexpected SETCC condition");
13494 // (x == y) -> ~(x ^ y)
13495 return DAG.getNode(ISD::XOR, dl, VT,
13496 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13497 DAG.getConstant(-1, dl, VT));
13499 // (x != y) -> (x ^ y)
13500 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13503 // (x > y) -> (x & ~y)
13504 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13507 // (x < y) -> (~x & y)
13508 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13511 // (x <= y) -> (~x | y)
13512 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13515 // (x >=y) -> (x | ~y)
13516 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13520 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13521 const X86Subtarget *Subtarget) {
13522 SDValue Op0 = Op.getOperand(0);
13523 SDValue Op1 = Op.getOperand(1);
13524 SDValue CC = Op.getOperand(2);
13525 MVT VT = Op.getSimpleValueType();
13528 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13529 Op.getValueType().getScalarType() == MVT::i1 &&
13530 "Cannot set masked compare for this operation");
13532 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13534 bool Unsigned = false;
13537 switch (SetCCOpcode) {
13538 default: llvm_unreachable("Unexpected SETCC condition");
13539 case ISD::SETNE: SSECC = 4; break;
13540 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
13541 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13542 case ISD::SETLT: Swap = true; //fall-through
13543 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
13544 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13545 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13546 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
13547 case ISD::SETULE: Unsigned = true; //fall-through
13548 case ISD::SETLE: SSECC = 2; break;
13552 std::swap(Op0, Op1);
13554 return DAG.getNode(Opc, dl, VT, Op0, Op1);
13555 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13556 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13557 DAG.getConstant(SSECC, dl, MVT::i8));
13560 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13561 /// operand \p Op1. If non-trivial (for example because it's not constant)
13562 /// return an empty value.
13563 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13565 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13569 MVT VT = Op1.getSimpleValueType();
13570 MVT EVT = VT.getVectorElementType();
13571 unsigned n = VT.getVectorNumElements();
13572 SmallVector<SDValue, 8> ULTOp1;
13574 for (unsigned i = 0; i < n; ++i) {
13575 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13576 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13579 // Avoid underflow.
13580 APInt Val = Elt->getAPIntValue();
13584 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13587 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13590 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13591 SelectionDAG &DAG) {
13592 SDValue Op0 = Op.getOperand(0);
13593 SDValue Op1 = Op.getOperand(1);
13594 SDValue CC = Op.getOperand(2);
13595 MVT VT = Op.getSimpleValueType();
13596 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13597 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13602 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13603 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13606 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13607 unsigned Opc = X86ISD::CMPP;
13608 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13609 assert(VT.getVectorNumElements() <= 16);
13610 Opc = X86ISD::CMPM;
13612 // In the two special cases we can't handle, emit two comparisons.
13615 unsigned CombineOpc;
13616 if (SetCCOpcode == ISD::SETUEQ) {
13617 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13619 assert(SetCCOpcode == ISD::SETONE);
13620 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13623 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13624 DAG.getConstant(CC0, dl, MVT::i8));
13625 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13626 DAG.getConstant(CC1, dl, MVT::i8));
13627 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13629 // Handle all other FP comparisons here.
13630 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13631 DAG.getConstant(SSECC, dl, MVT::i8));
13634 // Break 256-bit integer vector compare into smaller ones.
13635 if (VT.is256BitVector() && !Subtarget->hasInt256())
13636 return Lower256IntVSETCC(Op, DAG);
13638 EVT OpVT = Op1.getValueType();
13639 if (OpVT.getVectorElementType() == MVT::i1)
13640 return LowerBoolVSETCC_AVX512(Op, DAG);
13642 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13643 if (Subtarget->hasAVX512()) {
13644 if (Op1.getValueType().is512BitVector() ||
13645 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13646 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13647 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13649 // In AVX-512 architecture setcc returns mask with i1 elements,
13650 // But there is no compare instruction for i8 and i16 elements in KNL.
13651 // We are not talking about 512-bit operands in this case, these
13652 // types are illegal.
13654 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13655 OpVT.getVectorElementType().getSizeInBits() >= 8))
13656 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13657 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13660 // We are handling one of the integer comparisons here. Since SSE only has
13661 // GT and EQ comparisons for integer, swapping operands and multiple
13662 // operations may be required for some comparisons.
13664 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13665 bool Subus = false;
13667 switch (SetCCOpcode) {
13668 default: llvm_unreachable("Unexpected SETCC condition");
13669 case ISD::SETNE: Invert = true;
13670 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
13671 case ISD::SETLT: Swap = true;
13672 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
13673 case ISD::SETGE: Swap = true;
13674 case ISD::SETLE: Opc = X86ISD::PCMPGT;
13675 Invert = true; break;
13676 case ISD::SETULT: Swap = true;
13677 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13678 FlipSigns = true; break;
13679 case ISD::SETUGE: Swap = true;
13680 case ISD::SETULE: Opc = X86ISD::PCMPGT;
13681 FlipSigns = true; Invert = true; break;
13684 // Special case: Use min/max operations for SETULE/SETUGE
13685 MVT VET = VT.getVectorElementType();
13687 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13688 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13691 switch (SetCCOpcode) {
13693 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13694 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13697 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13700 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13701 if (!MinMax && hasSubus) {
13702 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13704 // t = psubus Op0, Op1
13705 // pcmpeq t, <0..0>
13706 switch (SetCCOpcode) {
13708 case ISD::SETULT: {
13709 // If the comparison is against a constant we can turn this into a
13710 // setule. With psubus, setule does not require a swap. This is
13711 // beneficial because the constant in the register is no longer
13712 // destructed as the destination so it can be hoisted out of a loop.
13713 // Only do this pre-AVX since vpcmp* is no longer destructive.
13714 if (Subtarget->hasAVX())
13716 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13717 if (ULEOp1.getNode()) {
13719 Subus = true; Invert = false; Swap = false;
13723 // Psubus is better than flip-sign because it requires no inversion.
13724 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13725 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13729 Opc = X86ISD::SUBUS;
13735 std::swap(Op0, Op1);
13737 // Check that the operation in question is available (most are plain SSE2,
13738 // but PCMPGTQ and PCMPEQQ have different requirements).
13739 if (VT == MVT::v2i64) {
13740 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13741 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13743 // First cast everything to the right type.
13744 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13745 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13747 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13748 // bits of the inputs before performing those operations. The lower
13749 // compare is always unsigned.
13752 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13754 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13755 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13756 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13757 Sign, Zero, Sign, Zero);
13759 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13760 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13762 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13763 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13764 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13766 // Create masks for only the low parts/high parts of the 64 bit integers.
13767 static const int MaskHi[] = { 1, 1, 3, 3 };
13768 static const int MaskLo[] = { 0, 0, 2, 2 };
13769 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13770 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13771 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13773 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13774 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13777 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13779 return DAG.getBitcast(VT, Result);
13782 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13783 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13784 // pcmpeqd + pshufd + pand.
13785 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13787 // First cast everything to the right type.
13788 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13789 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13792 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13794 // Make sure the lower and upper halves are both all-ones.
13795 static const int Mask[] = { 1, 0, 3, 2 };
13796 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13797 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13800 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13802 return DAG.getBitcast(VT, Result);
13806 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13807 // bits of the inputs before performing those operations.
13809 EVT EltVT = VT.getVectorElementType();
13810 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13812 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13813 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13816 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13818 // If the logical-not of the result is required, perform that now.
13820 Result = DAG.getNOT(dl, Result, VT);
13823 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13826 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13827 getZeroVector(VT, Subtarget, DAG, dl));
13832 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13834 MVT VT = Op.getSimpleValueType();
13836 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13838 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13839 && "SetCC type must be 8-bit or 1-bit integer");
13840 SDValue Op0 = Op.getOperand(0);
13841 SDValue Op1 = Op.getOperand(1);
13843 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13845 // Optimize to BT if possible.
13846 // Lower (X & (1 << N)) == 0 to BT(X, N).
13847 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13848 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13849 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13850 Op1.getOpcode() == ISD::Constant &&
13851 cast<ConstantSDNode>(Op1)->isNullValue() &&
13852 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13853 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13854 if (NewSetCC.getNode()) {
13856 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13861 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13863 if (Op1.getOpcode() == ISD::Constant &&
13864 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13865 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13866 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13868 // If the input is a setcc, then reuse the input setcc or use a new one with
13869 // the inverted condition.
13870 if (Op0.getOpcode() == X86ISD::SETCC) {
13871 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13872 bool Invert = (CC == ISD::SETNE) ^
13873 cast<ConstantSDNode>(Op1)->isNullValue();
13877 CCode = X86::GetOppositeBranchCondition(CCode);
13878 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13879 DAG.getConstant(CCode, dl, MVT::i8),
13880 Op0.getOperand(1));
13882 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13886 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13887 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13888 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13890 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13891 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13894 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13895 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13896 if (X86CC == X86::COND_INVALID)
13899 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13900 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13901 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13902 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13904 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13908 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13909 static bool isX86LogicalCmp(SDValue Op) {
13910 unsigned Opc = Op.getNode()->getOpcode();
13911 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13912 Opc == X86ISD::SAHF)
13914 if (Op.getResNo() == 1 &&
13915 (Opc == X86ISD::ADD ||
13916 Opc == X86ISD::SUB ||
13917 Opc == X86ISD::ADC ||
13918 Opc == X86ISD::SBB ||
13919 Opc == X86ISD::SMUL ||
13920 Opc == X86ISD::UMUL ||
13921 Opc == X86ISD::INC ||
13922 Opc == X86ISD::DEC ||
13923 Opc == X86ISD::OR ||
13924 Opc == X86ISD::XOR ||
13925 Opc == X86ISD::AND))
13928 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13934 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13935 if (V.getOpcode() != ISD::TRUNCATE)
13938 SDValue VOp0 = V.getOperand(0);
13939 unsigned InBits = VOp0.getValueSizeInBits();
13940 unsigned Bits = V.getValueSizeInBits();
13941 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13944 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13945 bool addTest = true;
13946 SDValue Cond = Op.getOperand(0);
13947 SDValue Op1 = Op.getOperand(1);
13948 SDValue Op2 = Op.getOperand(2);
13950 EVT VT = Op1.getValueType();
13953 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13954 // are available or VBLENDV if AVX is available.
13955 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13956 if (Cond.getOpcode() == ISD::SETCC &&
13957 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13958 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13959 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13960 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13961 int SSECC = translateX86FSETCC(
13962 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13965 if (Subtarget->hasAVX512()) {
13966 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13967 DAG.getConstant(SSECC, DL, MVT::i8));
13968 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13971 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13972 DAG.getConstant(SSECC, DL, MVT::i8));
13974 // If we have AVX, we can use a variable vector select (VBLENDV) instead
13975 // of 3 logic instructions for size savings and potentially speed.
13976 // Unfortunately, there is no scalar form of VBLENDV.
13978 // If either operand is a constant, don't try this. We can expect to
13979 // optimize away at least one of the logic instructions later in that
13980 // case, so that sequence would be faster than a variable blend.
13982 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13983 // uses XMM0 as the selection register. That may need just as many
13984 // instructions as the AND/ANDN/OR sequence due to register moves, so
13987 if (Subtarget->hasAVX() &&
13988 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13990 // Convert to vectors, do a VSELECT, and convert back to scalar.
13991 // All of the conversions should be optimized away.
13993 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13994 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13995 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13996 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13998 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13999 VCmp = DAG.getBitcast(VCmpVT, VCmp);
14001 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14003 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14004 VSel, DAG.getIntPtrConstant(0, DL));
14006 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14007 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14008 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14012 if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14014 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14015 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14016 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14017 Op1Scalar = Op1.getOperand(0);
14019 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14020 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14021 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14022 Op2Scalar = Op2.getOperand(0);
14023 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14024 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14025 Op1Scalar.getValueType(),
14026 Cond, Op1Scalar, Op2Scalar);
14027 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14028 return DAG.getBitcast(VT, newSelect);
14029 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14030 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14031 DAG.getIntPtrConstant(0, DL));
14035 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14036 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14037 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14038 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14039 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14040 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14041 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14043 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14046 if (Cond.getOpcode() == ISD::SETCC) {
14047 SDValue NewCond = LowerSETCC(Cond, DAG);
14048 if (NewCond.getNode())
14052 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14053 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14054 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14055 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14056 if (Cond.getOpcode() == X86ISD::SETCC &&
14057 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14058 isZero(Cond.getOperand(1).getOperand(1))) {
14059 SDValue Cmp = Cond.getOperand(1);
14061 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14063 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14064 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14065 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14067 SDValue CmpOp0 = Cmp.getOperand(0);
14068 // Apply further optimizations for special cases
14069 // (select (x != 0), -1, 0) -> neg & sbb
14070 // (select (x == 0), 0, -1) -> neg & sbb
14071 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14072 if (YC->isNullValue() &&
14073 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14074 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14075 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14076 DAG.getConstant(0, DL,
14077 CmpOp0.getValueType()),
14079 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14080 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14081 SDValue(Neg.getNode(), 1));
14085 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14086 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14087 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14089 SDValue Res = // Res = 0 or -1.
14090 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14091 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14093 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14094 Res = DAG.getNOT(DL, Res, Res.getValueType());
14096 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14097 if (!N2C || !N2C->isNullValue())
14098 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14103 // Look past (and (setcc_carry (cmp ...)), 1).
14104 if (Cond.getOpcode() == ISD::AND &&
14105 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14106 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14107 if (C && C->getAPIntValue() == 1)
14108 Cond = Cond.getOperand(0);
14111 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14112 // setting operand in place of the X86ISD::SETCC.
14113 unsigned CondOpcode = Cond.getOpcode();
14114 if (CondOpcode == X86ISD::SETCC ||
14115 CondOpcode == X86ISD::SETCC_CARRY) {
14116 CC = Cond.getOperand(0);
14118 SDValue Cmp = Cond.getOperand(1);
14119 unsigned Opc = Cmp.getOpcode();
14120 MVT VT = Op.getSimpleValueType();
14122 bool IllegalFPCMov = false;
14123 if (VT.isFloatingPoint() && !VT.isVector() &&
14124 !isScalarFPTypeInSSEReg(VT)) // FPStack?
14125 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14127 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14128 Opc == X86ISD::BT) { // FIXME
14132 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14133 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14134 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14135 Cond.getOperand(0).getValueType() != MVT::i8)) {
14136 SDValue LHS = Cond.getOperand(0);
14137 SDValue RHS = Cond.getOperand(1);
14138 unsigned X86Opcode;
14141 switch (CondOpcode) {
14142 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14143 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14144 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14145 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14146 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14147 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14148 default: llvm_unreachable("unexpected overflowing operator");
14150 if (CondOpcode == ISD::UMULO)
14151 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14154 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14156 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14158 if (CondOpcode == ISD::UMULO)
14159 Cond = X86Op.getValue(2);
14161 Cond = X86Op.getValue(1);
14163 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14168 // Look past the truncate if the high bits are known zero.
14169 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14170 Cond = Cond.getOperand(0);
14172 // We know the result of AND is compared against zero. Try to match
14174 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14175 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14176 if (NewSetCC.getNode()) {
14177 CC = NewSetCC.getOperand(0);
14178 Cond = NewSetCC.getOperand(1);
14185 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14186 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14189 // a < b ? -1 : 0 -> RES = ~setcc_carry
14190 // a < b ? 0 : -1 -> RES = setcc_carry
14191 // a >= b ? -1 : 0 -> RES = setcc_carry
14192 // a >= b ? 0 : -1 -> RES = ~setcc_carry
14193 if (Cond.getOpcode() == X86ISD::SUB) {
14194 Cond = ConvertCmpIfNecessary(Cond, DAG);
14195 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14197 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14198 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14199 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14200 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14202 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14203 return DAG.getNOT(DL, Res, Res.getValueType());
14208 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14209 // widen the cmov and push the truncate through. This avoids introducing a new
14210 // branch during isel and doesn't add any extensions.
14211 if (Op.getValueType() == MVT::i8 &&
14212 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14213 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14214 if (T1.getValueType() == T2.getValueType() &&
14215 // Blacklist CopyFromReg to avoid partial register stalls.
14216 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14217 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14218 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14219 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14223 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14224 // condition is true.
14225 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14226 SDValue Ops[] = { Op2, Op1, CC, Cond };
14227 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14230 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14231 const X86Subtarget *Subtarget,
14232 SelectionDAG &DAG) {
14233 MVT VT = Op->getSimpleValueType(0);
14234 SDValue In = Op->getOperand(0);
14235 MVT InVT = In.getSimpleValueType();
14236 MVT VTElt = VT.getVectorElementType();
14237 MVT InVTElt = InVT.getVectorElementType();
14241 if ((InVTElt == MVT::i1) &&
14242 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14243 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14245 ((Subtarget->hasBWI() && VT.is512BitVector() &&
14246 VTElt.getSizeInBits() <= 16)) ||
14248 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14249 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14251 ((Subtarget->hasDQI() && VT.is512BitVector() &&
14252 VTElt.getSizeInBits() >= 32))))
14253 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14255 unsigned int NumElts = VT.getVectorNumElements();
14257 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14260 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14261 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14262 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14263 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14266 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14267 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14269 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14272 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14274 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14275 if (VT.is512BitVector())
14277 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14280 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14281 const X86Subtarget *Subtarget,
14282 SelectionDAG &DAG) {
14283 SDValue In = Op->getOperand(0);
14284 MVT VT = Op->getSimpleValueType(0);
14285 MVT InVT = In.getSimpleValueType();
14286 assert(VT.getSizeInBits() == InVT.getSizeInBits());
14288 MVT InSVT = InVT.getScalarType();
14289 assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14291 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14293 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14298 // SSE41 targets can use the pmovsx* instructions directly.
14299 if (Subtarget->hasSSE41())
14300 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14302 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14306 // As SRAI is only available on i16/i32 types, we expand only up to i32
14307 // and handle i64 separately.
14308 while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14309 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14310 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14311 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14312 Curr = DAG.getBitcast(CurrVT, Curr);
14315 SDValue SignExt = Curr;
14316 if (CurrVT != InVT) {
14317 unsigned SignExtShift =
14318 CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14319 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14320 DAG.getConstant(SignExtShift, dl, MVT::i8));
14326 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14327 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14328 DAG.getConstant(31, dl, MVT::i8));
14329 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14330 return DAG.getBitcast(VT, Ext);
14336 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14337 SelectionDAG &DAG) {
14338 MVT VT = Op->getSimpleValueType(0);
14339 SDValue In = Op->getOperand(0);
14340 MVT InVT = In.getSimpleValueType();
14343 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14344 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14346 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14347 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14348 (VT != MVT::v16i16 || InVT != MVT::v16i8))
14351 if (Subtarget->hasInt256())
14352 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14354 // Optimize vectors in AVX mode
14355 // Sign extend v8i16 to v8i32 and
14358 // Divide input vector into two parts
14359 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14360 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14361 // concat the vectors to original VT
14363 unsigned NumElems = InVT.getVectorNumElements();
14364 SDValue Undef = DAG.getUNDEF(InVT);
14366 SmallVector<int,8> ShufMask1(NumElems, -1);
14367 for (unsigned i = 0; i != NumElems/2; ++i)
14370 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14372 SmallVector<int,8> ShufMask2(NumElems, -1);
14373 for (unsigned i = 0; i != NumElems/2; ++i)
14374 ShufMask2[i] = i + NumElems/2;
14376 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14378 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14379 VT.getVectorNumElements()/2);
14381 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14382 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14384 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14387 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14388 // may emit an illegal shuffle but the expansion is still better than scalar
14389 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14390 // we'll emit a shuffle and a arithmetic shift.
14391 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14392 // TODO: It is possible to support ZExt by zeroing the undef values during
14393 // the shuffle phase or after the shuffle.
14394 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14395 SelectionDAG &DAG) {
14396 MVT RegVT = Op.getSimpleValueType();
14397 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14398 assert(RegVT.isInteger() &&
14399 "We only custom lower integer vector sext loads.");
14401 // Nothing useful we can do without SSE2 shuffles.
14402 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14404 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14406 EVT MemVT = Ld->getMemoryVT();
14407 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14408 unsigned RegSz = RegVT.getSizeInBits();
14410 ISD::LoadExtType Ext = Ld->getExtensionType();
14412 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14413 && "Only anyext and sext are currently implemented.");
14414 assert(MemVT != RegVT && "Cannot extend to the same type");
14415 assert(MemVT.isVector() && "Must load a vector from memory");
14417 unsigned NumElems = RegVT.getVectorNumElements();
14418 unsigned MemSz = MemVT.getSizeInBits();
14419 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14421 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14422 // The only way in which we have a legal 256-bit vector result but not the
14423 // integer 256-bit operations needed to directly lower a sextload is if we
14424 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14425 // a 128-bit vector and a normal sign_extend to 256-bits that should get
14426 // correctly legalized. We do this late to allow the canonical form of
14427 // sextload to persist throughout the rest of the DAG combiner -- it wants
14428 // to fold together any extensions it can, and so will fuse a sign_extend
14429 // of an sextload into a sextload targeting a wider value.
14431 if (MemSz == 128) {
14432 // Just switch this to a normal load.
14433 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14434 "it must be a legal 128-bit vector "
14436 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14437 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14438 Ld->isInvariant(), Ld->getAlignment());
14440 assert(MemSz < 128 &&
14441 "Can't extend a type wider than 128 bits to a 256 bit vector!");
14442 // Do an sext load to a 128-bit vector type. We want to use the same
14443 // number of elements, but elements half as wide. This will end up being
14444 // recursively lowered by this routine, but will succeed as we definitely
14445 // have all the necessary features if we're using AVX1.
14447 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14448 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14450 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14451 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14452 Ld->isNonTemporal(), Ld->isInvariant(),
14453 Ld->getAlignment());
14456 // Replace chain users with the new chain.
14457 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14458 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14460 // Finally, do a normal sign-extend to the desired register.
14461 return DAG.getSExtOrTrunc(Load, dl, RegVT);
14464 // All sizes must be a power of two.
14465 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14466 "Non-power-of-two elements are not custom lowered!");
14468 // Attempt to load the original value using scalar loads.
14469 // Find the largest scalar type that divides the total loaded size.
14470 MVT SclrLoadTy = MVT::i8;
14471 for (MVT Tp : MVT::integer_valuetypes()) {
14472 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14477 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14478 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14480 SclrLoadTy = MVT::f64;
14482 // Calculate the number of scalar loads that we need to perform
14483 // in order to load our vector from memory.
14484 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14486 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14487 "Can only lower sext loads with a single scalar load!");
14489 unsigned loadRegZize = RegSz;
14490 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14493 // Represent our vector as a sequence of elements which are the
14494 // largest scalar that we can load.
14495 EVT LoadUnitVecVT = EVT::getVectorVT(
14496 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14498 // Represent the data using the same element type that is stored in
14499 // memory. In practice, we ''widen'' MemVT.
14501 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14502 loadRegZize / MemVT.getScalarType().getSizeInBits());
14504 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14505 "Invalid vector type");
14507 // We can't shuffle using an illegal type.
14508 assert(TLI.isTypeLegal(WideVecVT) &&
14509 "We only lower types that form legal widened vector types");
14511 SmallVector<SDValue, 8> Chains;
14512 SDValue Ptr = Ld->getBasePtr();
14513 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14514 TLI.getPointerTy(DAG.getDataLayout()));
14515 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14517 for (unsigned i = 0; i < NumLoads; ++i) {
14518 // Perform a single load.
14519 SDValue ScalarLoad =
14520 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14521 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14522 Ld->getAlignment());
14523 Chains.push_back(ScalarLoad.getValue(1));
14524 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14525 // another round of DAGCombining.
14527 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14529 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14530 ScalarLoad, DAG.getIntPtrConstant(i, dl));
14532 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14535 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14537 // Bitcast the loaded value to a vector of the original element type, in
14538 // the size of the target vector type.
14539 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14540 unsigned SizeRatio = RegSz / MemSz;
14542 if (Ext == ISD::SEXTLOAD) {
14543 // If we have SSE4.1, we can directly emit a VSEXT node.
14544 if (Subtarget->hasSSE41()) {
14545 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14546 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14550 // Otherwise we'll shuffle the small elements in the high bits of the
14551 // larger type and perform an arithmetic shift. If the shift is not legal
14552 // it's better to scalarize.
14553 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14554 "We can't implement a sext load without an arithmetic right shift!");
14556 // Redistribute the loaded elements into the different locations.
14557 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14558 for (unsigned i = 0; i != NumElems; ++i)
14559 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14561 SDValue Shuff = DAG.getVectorShuffle(
14562 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14564 Shuff = DAG.getBitcast(RegVT, Shuff);
14566 // Build the arithmetic shift.
14567 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14568 MemVT.getVectorElementType().getSizeInBits();
14570 DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14571 DAG.getConstant(Amt, dl, RegVT));
14573 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14577 // Redistribute the loaded elements into the different locations.
14578 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14579 for (unsigned i = 0; i != NumElems; ++i)
14580 ShuffleVec[i * SizeRatio] = i;
14582 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14583 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14585 // Bitcast to the requested type.
14586 Shuff = DAG.getBitcast(RegVT, Shuff);
14587 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14591 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14592 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14593 // from the AND / OR.
14594 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14595 Opc = Op.getOpcode();
14596 if (Opc != ISD::OR && Opc != ISD::AND)
14598 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14599 Op.getOperand(0).hasOneUse() &&
14600 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14601 Op.getOperand(1).hasOneUse());
14604 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14605 // 1 and that the SETCC node has a single use.
14606 static bool isXor1OfSetCC(SDValue Op) {
14607 if (Op.getOpcode() != ISD::XOR)
14609 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14610 if (N1C && N1C->getAPIntValue() == 1) {
14611 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14612 Op.getOperand(0).hasOneUse();
14617 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14618 bool addTest = true;
14619 SDValue Chain = Op.getOperand(0);
14620 SDValue Cond = Op.getOperand(1);
14621 SDValue Dest = Op.getOperand(2);
14624 bool Inverted = false;
14626 if (Cond.getOpcode() == ISD::SETCC) {
14627 // Check for setcc([su]{add,sub,mul}o == 0).
14628 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14629 isa<ConstantSDNode>(Cond.getOperand(1)) &&
14630 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14631 Cond.getOperand(0).getResNo() == 1 &&
14632 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14633 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14634 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14635 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14636 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14637 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14639 Cond = Cond.getOperand(0);
14641 SDValue NewCond = LowerSETCC(Cond, DAG);
14642 if (NewCond.getNode())
14647 // FIXME: LowerXALUO doesn't handle these!!
14648 else if (Cond.getOpcode() == X86ISD::ADD ||
14649 Cond.getOpcode() == X86ISD::SUB ||
14650 Cond.getOpcode() == X86ISD::SMUL ||
14651 Cond.getOpcode() == X86ISD::UMUL)
14652 Cond = LowerXALUO(Cond, DAG);
14655 // Look pass (and (setcc_carry (cmp ...)), 1).
14656 if (Cond.getOpcode() == ISD::AND &&
14657 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14658 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14659 if (C && C->getAPIntValue() == 1)
14660 Cond = Cond.getOperand(0);
14663 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14664 // setting operand in place of the X86ISD::SETCC.
14665 unsigned CondOpcode = Cond.getOpcode();
14666 if (CondOpcode == X86ISD::SETCC ||
14667 CondOpcode == X86ISD::SETCC_CARRY) {
14668 CC = Cond.getOperand(0);
14670 SDValue Cmp = Cond.getOperand(1);
14671 unsigned Opc = Cmp.getOpcode();
14672 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14673 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14677 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14681 // These can only come from an arithmetic instruction with overflow,
14682 // e.g. SADDO, UADDO.
14683 Cond = Cond.getNode()->getOperand(1);
14689 CondOpcode = Cond.getOpcode();
14690 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14691 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14692 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14693 Cond.getOperand(0).getValueType() != MVT::i8)) {
14694 SDValue LHS = Cond.getOperand(0);
14695 SDValue RHS = Cond.getOperand(1);
14696 unsigned X86Opcode;
14699 // Keep this in sync with LowerXALUO, otherwise we might create redundant
14700 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14702 switch (CondOpcode) {
14703 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14705 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14707 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14710 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14711 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14713 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14715 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14718 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14719 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14720 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14721 default: llvm_unreachable("unexpected overflowing operator");
14724 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14725 if (CondOpcode == ISD::UMULO)
14726 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14729 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14731 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14733 if (CondOpcode == ISD::UMULO)
14734 Cond = X86Op.getValue(2);
14736 Cond = X86Op.getValue(1);
14738 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14742 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14743 SDValue Cmp = Cond.getOperand(0).getOperand(1);
14744 if (CondOpc == ISD::OR) {
14745 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14746 // two branches instead of an explicit OR instruction with a
14748 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14749 isX86LogicalCmp(Cmp)) {
14750 CC = Cond.getOperand(0).getOperand(0);
14751 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14752 Chain, Dest, CC, Cmp);
14753 CC = Cond.getOperand(1).getOperand(0);
14757 } else { // ISD::AND
14758 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14759 // two branches instead of an explicit AND instruction with a
14760 // separate test. However, we only do this if this block doesn't
14761 // have a fall-through edge, because this requires an explicit
14762 // jmp when the condition is false.
14763 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14764 isX86LogicalCmp(Cmp) &&
14765 Op.getNode()->hasOneUse()) {
14766 X86::CondCode CCode =
14767 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14768 CCode = X86::GetOppositeBranchCondition(CCode);
14769 CC = DAG.getConstant(CCode, dl, MVT::i8);
14770 SDNode *User = *Op.getNode()->use_begin();
14771 // Look for an unconditional branch following this conditional branch.
14772 // We need this because we need to reverse the successors in order
14773 // to implement FCMP_OEQ.
14774 if (User->getOpcode() == ISD::BR) {
14775 SDValue FalseBB = User->getOperand(1);
14777 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14778 assert(NewBR == User);
14782 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14783 Chain, Dest, CC, Cmp);
14784 X86::CondCode CCode =
14785 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14786 CCode = X86::GetOppositeBranchCondition(CCode);
14787 CC = DAG.getConstant(CCode, dl, MVT::i8);
14793 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14794 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14795 // It should be transformed during dag combiner except when the condition
14796 // is set by a arithmetics with overflow node.
14797 X86::CondCode CCode =
14798 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14799 CCode = X86::GetOppositeBranchCondition(CCode);
14800 CC = DAG.getConstant(CCode, dl, MVT::i8);
14801 Cond = Cond.getOperand(0).getOperand(1);
14803 } else if (Cond.getOpcode() == ISD::SETCC &&
14804 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14805 // For FCMP_OEQ, we can emit
14806 // two branches instead of an explicit AND instruction with a
14807 // separate test. However, we only do this if this block doesn't
14808 // have a fall-through edge, because this requires an explicit
14809 // jmp when the condition is false.
14810 if (Op.getNode()->hasOneUse()) {
14811 SDNode *User = *Op.getNode()->use_begin();
14812 // Look for an unconditional branch following this conditional branch.
14813 // We need this because we need to reverse the successors in order
14814 // to implement FCMP_OEQ.
14815 if (User->getOpcode() == ISD::BR) {
14816 SDValue FalseBB = User->getOperand(1);
14818 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14819 assert(NewBR == User);
14823 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14824 Cond.getOperand(0), Cond.getOperand(1));
14825 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14826 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14827 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14828 Chain, Dest, CC, Cmp);
14829 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14834 } else if (Cond.getOpcode() == ISD::SETCC &&
14835 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14836 // For FCMP_UNE, we can emit
14837 // two branches instead of an explicit AND instruction with a
14838 // separate test. However, we only do this if this block doesn't
14839 // have a fall-through edge, because this requires an explicit
14840 // jmp when the condition is false.
14841 if (Op.getNode()->hasOneUse()) {
14842 SDNode *User = *Op.getNode()->use_begin();
14843 // Look for an unconditional branch following this conditional branch.
14844 // We need this because we need to reverse the successors in order
14845 // to implement FCMP_UNE.
14846 if (User->getOpcode() == ISD::BR) {
14847 SDValue FalseBB = User->getOperand(1);
14849 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14850 assert(NewBR == User);
14853 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14854 Cond.getOperand(0), Cond.getOperand(1));
14855 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14856 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14857 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14858 Chain, Dest, CC, Cmp);
14859 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14869 // Look pass the truncate if the high bits are known zero.
14870 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14871 Cond = Cond.getOperand(0);
14873 // We know the result of AND is compared against zero. Try to match
14875 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14876 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14877 if (NewSetCC.getNode()) {
14878 CC = NewSetCC.getOperand(0);
14879 Cond = NewSetCC.getOperand(1);
14886 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14887 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14888 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14890 Cond = ConvertCmpIfNecessary(Cond, DAG);
14891 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14892 Chain, Dest, CC, Cond);
14895 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14896 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14897 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14898 // that the guard pages used by the OS virtual memory manager are allocated in
14899 // correct sequence.
14901 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14902 SelectionDAG &DAG) const {
14903 MachineFunction &MF = DAG.getMachineFunction();
14904 bool SplitStack = MF.shouldSplitStack();
14905 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14910 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14911 SDNode* Node = Op.getNode();
14913 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14914 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14915 " not tell us which reg is the stack pointer!");
14916 EVT VT = Node->getValueType(0);
14917 SDValue Tmp1 = SDValue(Node, 0);
14918 SDValue Tmp2 = SDValue(Node, 1);
14919 SDValue Tmp3 = Node->getOperand(2);
14920 SDValue Chain = Tmp1.getOperand(0);
14922 // Chain the dynamic stack allocation so that it doesn't modify the stack
14923 // pointer when other instructions are using the stack.
14924 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14927 SDValue Size = Tmp2.getOperand(1);
14928 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14929 Chain = SP.getValue(1);
14930 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14931 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14932 unsigned StackAlign = TFI.getStackAlignment();
14933 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14934 if (Align > StackAlign)
14935 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14936 DAG.getConstant(-(uint64_t)Align, dl, VT));
14937 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14939 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14940 DAG.getIntPtrConstant(0, dl, true), SDValue(),
14943 SDValue Ops[2] = { Tmp1, Tmp2 };
14944 return DAG.getMergeValues(Ops, dl);
14948 SDValue Chain = Op.getOperand(0);
14949 SDValue Size = Op.getOperand(1);
14950 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14951 EVT VT = Op.getNode()->getValueType(0);
14953 bool Is64Bit = Subtarget->is64Bit();
14954 MVT SPTy = getPointerTy(DAG.getDataLayout());
14957 MachineRegisterInfo &MRI = MF.getRegInfo();
14960 // The 64 bit implementation of segmented stacks needs to clobber both r10
14961 // r11. This makes it impossible to use it along with nested parameters.
14962 const Function *F = MF.getFunction();
14964 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14966 if (I->hasNestAttr())
14967 report_fatal_error("Cannot use segmented stacks with functions that "
14968 "have nested arguments.");
14971 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
14972 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14973 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14974 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14975 DAG.getRegister(Vreg, SPTy));
14976 SDValue Ops1[2] = { Value, Chain };
14977 return DAG.getMergeValues(Ops1, dl);
14980 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14982 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14983 Flag = Chain.getValue(1);
14984 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14986 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14988 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14989 unsigned SPReg = RegInfo->getStackRegister();
14990 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14991 Chain = SP.getValue(1);
14994 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14995 DAG.getConstant(-(uint64_t)Align, dl, VT));
14996 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14999 SDValue Ops1[2] = { SP, Chain };
15000 return DAG.getMergeValues(Ops1, dl);
15004 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15005 MachineFunction &MF = DAG.getMachineFunction();
15006 auto PtrVT = getPointerTy(MF.getDataLayout());
15007 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15009 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15012 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
15013 // vastart just stores the address of the VarArgsFrameIndex slot into the
15014 // memory location argument.
15015 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15016 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15017 MachinePointerInfo(SV), false, false, 0);
15021 // gp_offset (0 - 6 * 8)
15022 // fp_offset (48 - 48 + 8 * 16)
15023 // overflow_arg_area (point to parameters coming in memory).
15025 SmallVector<SDValue, 8> MemOps;
15026 SDValue FIN = Op.getOperand(1);
15028 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15029 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15031 FIN, MachinePointerInfo(SV), false, false, 0);
15032 MemOps.push_back(Store);
15035 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15036 Store = DAG.getStore(Op.getOperand(0), DL,
15037 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15039 FIN, MachinePointerInfo(SV, 4), false, false, 0);
15040 MemOps.push_back(Store);
15042 // Store ptr to overflow_arg_area
15043 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15044 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15045 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15046 MachinePointerInfo(SV, 8),
15048 MemOps.push_back(Store);
15050 // Store ptr to reg_save_area.
15051 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15052 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15053 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15054 MachinePointerInfo(SV, 16), false, false, 0);
15055 MemOps.push_back(Store);
15056 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15059 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15060 assert(Subtarget->is64Bit() &&
15061 "LowerVAARG only handles 64-bit va_arg!");
15062 assert((Subtarget->isTargetLinux() ||
15063 Subtarget->isTargetDarwin()) &&
15064 "Unhandled target in LowerVAARG");
15065 assert(Op.getNode()->getNumOperands() == 4);
15066 SDValue Chain = Op.getOperand(0);
15067 SDValue SrcPtr = Op.getOperand(1);
15068 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15069 unsigned Align = Op.getConstantOperandVal(3);
15072 EVT ArgVT = Op.getNode()->getValueType(0);
15073 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15074 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15077 // Decide which area this value should be read from.
15078 // TODO: Implement the AMD64 ABI in its entirety. This simple
15079 // selection mechanism works only for the basic types.
15080 if (ArgVT == MVT::f80) {
15081 llvm_unreachable("va_arg for f80 not yet implemented");
15082 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15083 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
15084 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15085 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
15087 llvm_unreachable("Unhandled argument type in LowerVAARG");
15090 if (ArgMode == 2) {
15091 // Sanity Check: Make sure using fp_offset makes sense.
15092 assert(!Subtarget->useSoftFloat() &&
15093 !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15094 Attribute::NoImplicitFloat)) &&
15095 Subtarget->hasSSE1());
15098 // Insert VAARG_64 node into the DAG
15099 // VAARG_64 returns two values: Variable Argument Address, Chain
15100 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15101 DAG.getConstant(ArgMode, dl, MVT::i8),
15102 DAG.getConstant(Align, dl, MVT::i32)};
15103 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15104 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15105 VTs, InstOps, MVT::i64,
15106 MachinePointerInfo(SV),
15108 /*Volatile=*/false,
15110 /*WriteMem=*/true);
15111 Chain = VAARG.getValue(1);
15113 // Load the next argument and return it
15114 return DAG.getLoad(ArgVT, dl,
15117 MachinePointerInfo(),
15118 false, false, false, 0);
15121 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15122 SelectionDAG &DAG) {
15123 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15124 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15125 SDValue Chain = Op.getOperand(0);
15126 SDValue DstPtr = Op.getOperand(1);
15127 SDValue SrcPtr = Op.getOperand(2);
15128 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15129 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15132 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15133 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15135 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15138 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15139 // amount is a constant. Takes immediate version of shift as input.
15140 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15141 SDValue SrcOp, uint64_t ShiftAmt,
15142 SelectionDAG &DAG) {
15143 MVT ElementType = VT.getVectorElementType();
15145 // Fold this packed shift into its first operand if ShiftAmt is 0.
15149 // Check for ShiftAmt >= element width
15150 if (ShiftAmt >= ElementType.getSizeInBits()) {
15151 if (Opc == X86ISD::VSRAI)
15152 ShiftAmt = ElementType.getSizeInBits() - 1;
15154 return DAG.getConstant(0, dl, VT);
15157 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15158 && "Unknown target vector shift-by-constant node");
15160 // Fold this packed vector shift into a build vector if SrcOp is a
15161 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15162 if (VT == SrcOp.getSimpleValueType() &&
15163 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15164 SmallVector<SDValue, 8> Elts;
15165 unsigned NumElts = SrcOp->getNumOperands();
15166 ConstantSDNode *ND;
15169 default: llvm_unreachable(nullptr);
15170 case X86ISD::VSHLI:
15171 for (unsigned i=0; i!=NumElts; ++i) {
15172 SDValue CurrentOp = SrcOp->getOperand(i);
15173 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15174 Elts.push_back(CurrentOp);
15177 ND = cast<ConstantSDNode>(CurrentOp);
15178 const APInt &C = ND->getAPIntValue();
15179 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15182 case X86ISD::VSRLI:
15183 for (unsigned i=0; i!=NumElts; ++i) {
15184 SDValue CurrentOp = SrcOp->getOperand(i);
15185 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15186 Elts.push_back(CurrentOp);
15189 ND = cast<ConstantSDNode>(CurrentOp);
15190 const APInt &C = ND->getAPIntValue();
15191 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15194 case X86ISD::VSRAI:
15195 for (unsigned i=0; i!=NumElts; ++i) {
15196 SDValue CurrentOp = SrcOp->getOperand(i);
15197 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15198 Elts.push_back(CurrentOp);
15201 ND = cast<ConstantSDNode>(CurrentOp);
15202 const APInt &C = ND->getAPIntValue();
15203 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15208 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15211 return DAG.getNode(Opc, dl, VT, SrcOp,
15212 DAG.getConstant(ShiftAmt, dl, MVT::i8));
15215 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15216 // may or may not be a constant. Takes immediate version of shift as input.
15217 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15218 SDValue SrcOp, SDValue ShAmt,
15219 SelectionDAG &DAG) {
15220 MVT SVT = ShAmt.getSimpleValueType();
15221 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15223 // Catch shift-by-constant.
15224 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15225 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15226 CShAmt->getZExtValue(), DAG);
15228 // Change opcode to non-immediate version
15230 default: llvm_unreachable("Unknown target vector shift node");
15231 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15232 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15233 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15236 const X86Subtarget &Subtarget =
15237 static_cast<const X86Subtarget &>(DAG.getSubtarget());
15238 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15239 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15240 // Let the shuffle legalizer expand this shift amount node.
15241 SDValue Op0 = ShAmt.getOperand(0);
15242 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15243 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15245 // Need to build a vector containing shift amount.
15246 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15247 SmallVector<SDValue, 4> ShOps;
15248 ShOps.push_back(ShAmt);
15249 if (SVT == MVT::i32) {
15250 ShOps.push_back(DAG.getConstant(0, dl, SVT));
15251 ShOps.push_back(DAG.getUNDEF(SVT));
15253 ShOps.push_back(DAG.getUNDEF(SVT));
15255 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15256 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15259 // The return type has to be a 128-bit type with the same element
15260 // type as the input type.
15261 MVT EltVT = VT.getVectorElementType();
15262 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15264 ShAmt = DAG.getBitcast(ShVT, ShAmt);
15265 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15268 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15269 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15270 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15271 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15272 SDValue PreservedSrc,
15273 const X86Subtarget *Subtarget,
15274 SelectionDAG &DAG) {
15275 EVT VT = Op.getValueType();
15276 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15277 MVT::i1, VT.getVectorNumElements());
15278 SDValue VMask = SDValue();
15279 unsigned OpcodeSelect = ISD::VSELECT;
15282 assert(MaskVT.isSimple() && "invalid mask type");
15284 if (isAllOnes(Mask))
15287 if (MaskVT.bitsGT(Mask.getValueType())) {
15288 EVT newMaskVT = EVT::getIntegerVT(*DAG.getContext(),
15289 MaskVT.getSizeInBits());
15290 VMask = DAG.getBitcast(MaskVT,
15291 DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15293 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15294 Mask.getValueType().getSizeInBits());
15295 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15296 // are extracted by EXTRACT_SUBVECTOR.
15297 VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15298 DAG.getBitcast(BitcastVT, Mask),
15299 DAG.getIntPtrConstant(0, dl));
15302 switch (Op.getOpcode()) {
15304 case X86ISD::PCMPEQM:
15305 case X86ISD::PCMPGTM:
15307 case X86ISD::CMPMU:
15308 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15309 case X86ISD::VTRUNC:
15310 case X86ISD::VTRUNCS:
15311 case X86ISD::VTRUNCUS:
15312 // We can't use ISD::VSELECT here because it is not always "Legal"
15313 // for the destination type. For example vpmovqb require only AVX512
15314 // and vselect that can operate on byte element type require BWI
15315 OpcodeSelect = X86ISD::SELECT;
15318 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15319 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15320 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15323 /// \brief Creates an SDNode for a predicated scalar operation.
15324 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15325 /// The mask is coming as MVT::i8 and it should be truncated
15326 /// to MVT::i1 while lowering masking intrinsics.
15327 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15328 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15329 /// for a scalar instruction.
15330 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15331 SDValue PreservedSrc,
15332 const X86Subtarget *Subtarget,
15333 SelectionDAG &DAG) {
15334 if (isAllOnes(Mask))
15337 EVT VT = Op.getValueType();
15339 // The mask should be of type MVT::i1
15340 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15342 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15343 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15344 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15347 static int getSEHRegistrationNodeSize(const Function *Fn) {
15348 if (!Fn->hasPersonalityFn())
15349 report_fatal_error(
15350 "querying registration node size for function without personality");
15351 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15352 // WinEHStatePass for the full struct definition.
15353 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15354 case EHPersonality::MSVC_X86SEH: return 24;
15355 case EHPersonality::MSVC_CXX: return 16;
15358 report_fatal_error("can only recover FP for MSVC EH personality functions");
15361 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15362 /// function or when returning to a parent frame after catching an exception, we
15363 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15364 /// Here's the math:
15365 /// RegNodeBase = EntryEBP - RegNodeSize
15366 /// ParentFP = RegNodeBase - RegNodeFrameOffset
15367 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15368 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15369 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15370 SDValue EntryEBP) {
15371 MachineFunction &MF = DAG.getMachineFunction();
15374 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15375 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15377 // It's possible that the parent function no longer has a personality function
15378 // if the exceptional code was optimized away, in which case we just return
15379 // the incoming EBP.
15380 if (!Fn->hasPersonalityFn())
15383 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15385 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15387 MCSymbol *OffsetSym =
15388 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15389 GlobalValue::getRealLinkageName(Fn->getName()));
15390 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15391 SDValue RegNodeFrameOffset =
15392 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15394 // RegNodeBase = EntryEBP - RegNodeSize
15395 // ParentFP = RegNodeBase - RegNodeFrameOffset
15396 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15397 DAG.getConstant(RegNodeSize, dl, PtrVT));
15398 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15401 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15402 SelectionDAG &DAG) {
15404 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15405 EVT VT = Op.getValueType();
15406 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15408 switch(IntrData->Type) {
15409 case INTR_TYPE_1OP:
15410 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15411 case INTR_TYPE_2OP:
15412 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15414 case INTR_TYPE_3OP:
15415 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15416 Op.getOperand(2), Op.getOperand(3));
15417 case INTR_TYPE_4OP:
15418 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15419 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15420 case INTR_TYPE_1OP_MASK_RM: {
15421 SDValue Src = Op.getOperand(1);
15422 SDValue PassThru = Op.getOperand(2);
15423 SDValue Mask = Op.getOperand(3);
15424 SDValue RoundingMode;
15425 // We allways add rounding mode to the Node.
15426 // If the rounding mode is not specified, we add the
15427 // "current direction" mode.
15428 if (Op.getNumOperands() == 4)
15430 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15432 RoundingMode = Op.getOperand(4);
15433 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15434 if (IntrWithRoundingModeOpcode != 0)
15435 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15436 X86::STATIC_ROUNDING::CUR_DIRECTION)
15437 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15438 dl, Op.getValueType(), Src, RoundingMode),
15439 Mask, PassThru, Subtarget, DAG);
15440 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15442 Mask, PassThru, Subtarget, DAG);
15444 case INTR_TYPE_1OP_MASK: {
15445 SDValue Src = Op.getOperand(1);
15446 SDValue PassThru = Op.getOperand(2);
15447 SDValue Mask = Op.getOperand(3);
15448 // We add rounding mode to the Node when
15449 // - RM Opcode is specified and
15450 // - RM is not "current direction".
15451 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15452 if (IntrWithRoundingModeOpcode != 0) {
15453 SDValue Rnd = Op.getOperand(4);
15454 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15455 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15456 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15457 dl, Op.getValueType(),
15459 Mask, PassThru, Subtarget, DAG);
15462 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15463 Mask, PassThru, Subtarget, DAG);
15465 case INTR_TYPE_SCALAR_MASK_RM: {
15466 SDValue Src1 = Op.getOperand(1);
15467 SDValue Src2 = Op.getOperand(2);
15468 SDValue Src0 = Op.getOperand(3);
15469 SDValue Mask = Op.getOperand(4);
15470 // There are 2 kinds of intrinsics in this group:
15471 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15472 // (2) With rounding mode and sae - 7 operands.
15473 if (Op.getNumOperands() == 6) {
15474 SDValue Sae = Op.getOperand(5);
15475 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15476 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15478 Mask, Src0, Subtarget, DAG);
15480 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15481 SDValue RoundingMode = Op.getOperand(5);
15482 SDValue Sae = Op.getOperand(6);
15483 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15484 RoundingMode, Sae),
15485 Mask, Src0, Subtarget, DAG);
15487 case INTR_TYPE_2OP_MASK: {
15488 SDValue Src1 = Op.getOperand(1);
15489 SDValue Src2 = Op.getOperand(2);
15490 SDValue PassThru = Op.getOperand(3);
15491 SDValue Mask = Op.getOperand(4);
15492 // We specify 2 possible opcodes for intrinsics with rounding modes.
15493 // First, we check if the intrinsic may have non-default rounding mode,
15494 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15495 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15496 if (IntrWithRoundingModeOpcode != 0) {
15497 SDValue Rnd = Op.getOperand(5);
15498 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15499 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15500 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15501 dl, Op.getValueType(),
15503 Mask, PassThru, Subtarget, DAG);
15506 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15508 Mask, PassThru, Subtarget, DAG);
15510 case INTR_TYPE_2OP_MASK_RM: {
15511 SDValue Src1 = Op.getOperand(1);
15512 SDValue Src2 = Op.getOperand(2);
15513 SDValue PassThru = Op.getOperand(3);
15514 SDValue Mask = Op.getOperand(4);
15515 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15516 // First, we check if the intrinsic have rounding mode (6 operands),
15517 // if not, we set rounding mode to "current".
15519 if (Op.getNumOperands() == 6)
15520 Rnd = Op.getOperand(5);
15522 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15523 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15525 Mask, PassThru, Subtarget, DAG);
15527 case INTR_TYPE_3OP_MASK_RM: {
15528 SDValue Src1 = Op.getOperand(1);
15529 SDValue Src2 = Op.getOperand(2);
15530 SDValue Imm = Op.getOperand(3);
15531 SDValue PassThru = Op.getOperand(4);
15532 SDValue Mask = Op.getOperand(5);
15533 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15534 // First, we check if the intrinsic have rounding mode (7 operands),
15535 // if not, we set rounding mode to "current".
15537 if (Op.getNumOperands() == 7)
15538 Rnd = Op.getOperand(6);
15540 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15541 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15542 Src1, Src2, Imm, Rnd),
15543 Mask, PassThru, Subtarget, DAG);
15545 case INTR_TYPE_3OP_MASK: {
15546 SDValue Src1 = Op.getOperand(1);
15547 SDValue Src2 = Op.getOperand(2);
15548 SDValue Src3 = Op.getOperand(3);
15549 SDValue PassThru = Op.getOperand(4);
15550 SDValue Mask = Op.getOperand(5);
15551 // We specify 2 possible opcodes for intrinsics with rounding modes.
15552 // First, we check if the intrinsic may have non-default rounding mode,
15553 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15554 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15555 if (IntrWithRoundingModeOpcode != 0) {
15556 SDValue Rnd = Op.getOperand(6);
15557 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15558 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15559 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15560 dl, Op.getValueType(),
15561 Src1, Src2, Src3, Rnd),
15562 Mask, PassThru, Subtarget, DAG);
15565 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15567 Mask, PassThru, Subtarget, DAG);
15569 case VPERM_3OP_MASKZ:
15570 case VPERM_3OP_MASK:
15573 case FMA_OP_MASK: {
15574 SDValue Src1 = Op.getOperand(1);
15575 SDValue Src2 = Op.getOperand(2);
15576 SDValue Src3 = Op.getOperand(3);
15577 SDValue Mask = Op.getOperand(4);
15578 EVT VT = Op.getValueType();
15579 SDValue PassThru = SDValue();
15581 // set PassThru element
15582 if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15583 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15584 else if (IntrData->Type == FMA_OP_MASK3)
15589 // We specify 2 possible opcodes for intrinsics with rounding modes.
15590 // First, we check if the intrinsic may have non-default rounding mode,
15591 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15592 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15593 if (IntrWithRoundingModeOpcode != 0) {
15594 SDValue Rnd = Op.getOperand(5);
15595 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15596 X86::STATIC_ROUNDING::CUR_DIRECTION)
15597 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15598 dl, Op.getValueType(),
15599 Src1, Src2, Src3, Rnd),
15600 Mask, PassThru, Subtarget, DAG);
15602 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15603 dl, Op.getValueType(),
15605 Mask, PassThru, Subtarget, DAG);
15608 case CMP_MASK_CC: {
15609 // Comparison intrinsics with masks.
15610 // Example of transformation:
15611 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15612 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15614 // (v8i1 (insert_subvector undef,
15615 // (v2i1 (and (PCMPEQM %a, %b),
15616 // (extract_subvector
15617 // (v8i1 (bitcast %mask)), 0))), 0))))
15618 EVT VT = Op.getOperand(1).getValueType();
15619 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15620 VT.getVectorNumElements());
15621 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15622 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15623 Mask.getValueType().getSizeInBits());
15625 if (IntrData->Type == CMP_MASK_CC) {
15626 SDValue CC = Op.getOperand(3);
15627 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15628 // We specify 2 possible opcodes for intrinsics with rounding modes.
15629 // First, we check if the intrinsic may have non-default rounding mode,
15630 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15631 if (IntrData->Opc1 != 0) {
15632 SDValue Rnd = Op.getOperand(5);
15633 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15634 X86::STATIC_ROUNDING::CUR_DIRECTION)
15635 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15636 Op.getOperand(2), CC, Rnd);
15638 //default rounding mode
15640 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15641 Op.getOperand(2), CC);
15644 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15645 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15648 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15649 DAG.getTargetConstant(0, dl,
15652 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15653 DAG.getUNDEF(BitcastVT), CmpMask,
15654 DAG.getIntPtrConstant(0, dl));
15655 return DAG.getBitcast(Op.getValueType(), Res);
15657 case COMI: { // Comparison intrinsics
15658 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15659 SDValue LHS = Op.getOperand(1);
15660 SDValue RHS = Op.getOperand(2);
15661 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15662 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15663 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15664 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15665 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15666 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15669 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15670 Op.getOperand(1), Op.getOperand(2), DAG);
15672 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15673 Op.getSimpleValueType(),
15675 Op.getOperand(2), DAG),
15676 Op.getOperand(4), Op.getOperand(3), Subtarget,
15678 case COMPRESS_EXPAND_IN_REG: {
15679 SDValue Mask = Op.getOperand(3);
15680 SDValue DataToCompress = Op.getOperand(1);
15681 SDValue PassThru = Op.getOperand(2);
15682 if (isAllOnes(Mask)) // return data as is
15683 return Op.getOperand(1);
15685 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15687 Mask, PassThru, Subtarget, DAG);
15690 SDValue Mask = Op.getOperand(3);
15691 EVT VT = Op.getValueType();
15692 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15693 VT.getVectorNumElements());
15694 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15695 Mask.getValueType().getSizeInBits());
15697 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15698 DAG.getBitcast(BitcastVT, Mask),
15699 DAG.getIntPtrConstant(0, dl));
15700 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15709 default: return SDValue(); // Don't custom lower most intrinsics.
15711 case Intrinsic::x86_avx2_permd:
15712 case Intrinsic::x86_avx2_permps:
15713 // Operands intentionally swapped. Mask is last operand to intrinsic,
15714 // but second operand for node/instruction.
15715 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15716 Op.getOperand(2), Op.getOperand(1));
15718 // ptest and testp intrinsics. The intrinsic these come from are designed to
15719 // return an integer value, not just an instruction so lower it to the ptest
15720 // or testp pattern and a setcc for the result.
15721 case Intrinsic::x86_sse41_ptestz:
15722 case Intrinsic::x86_sse41_ptestc:
15723 case Intrinsic::x86_sse41_ptestnzc:
15724 case Intrinsic::x86_avx_ptestz_256:
15725 case Intrinsic::x86_avx_ptestc_256:
15726 case Intrinsic::x86_avx_ptestnzc_256:
15727 case Intrinsic::x86_avx_vtestz_ps:
15728 case Intrinsic::x86_avx_vtestc_ps:
15729 case Intrinsic::x86_avx_vtestnzc_ps:
15730 case Intrinsic::x86_avx_vtestz_pd:
15731 case Intrinsic::x86_avx_vtestc_pd:
15732 case Intrinsic::x86_avx_vtestnzc_pd:
15733 case Intrinsic::x86_avx_vtestz_ps_256:
15734 case Intrinsic::x86_avx_vtestc_ps_256:
15735 case Intrinsic::x86_avx_vtestnzc_ps_256:
15736 case Intrinsic::x86_avx_vtestz_pd_256:
15737 case Intrinsic::x86_avx_vtestc_pd_256:
15738 case Intrinsic::x86_avx_vtestnzc_pd_256: {
15739 bool IsTestPacked = false;
15742 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15743 case Intrinsic::x86_avx_vtestz_ps:
15744 case Intrinsic::x86_avx_vtestz_pd:
15745 case Intrinsic::x86_avx_vtestz_ps_256:
15746 case Intrinsic::x86_avx_vtestz_pd_256:
15747 IsTestPacked = true; // Fallthrough
15748 case Intrinsic::x86_sse41_ptestz:
15749 case Intrinsic::x86_avx_ptestz_256:
15751 X86CC = X86::COND_E;
15753 case Intrinsic::x86_avx_vtestc_ps:
15754 case Intrinsic::x86_avx_vtestc_pd:
15755 case Intrinsic::x86_avx_vtestc_ps_256:
15756 case Intrinsic::x86_avx_vtestc_pd_256:
15757 IsTestPacked = true; // Fallthrough
15758 case Intrinsic::x86_sse41_ptestc:
15759 case Intrinsic::x86_avx_ptestc_256:
15761 X86CC = X86::COND_B;
15763 case Intrinsic::x86_avx_vtestnzc_ps:
15764 case Intrinsic::x86_avx_vtestnzc_pd:
15765 case Intrinsic::x86_avx_vtestnzc_ps_256:
15766 case Intrinsic::x86_avx_vtestnzc_pd_256:
15767 IsTestPacked = true; // Fallthrough
15768 case Intrinsic::x86_sse41_ptestnzc:
15769 case Intrinsic::x86_avx_ptestnzc_256:
15771 X86CC = X86::COND_A;
15775 SDValue LHS = Op.getOperand(1);
15776 SDValue RHS = Op.getOperand(2);
15777 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15778 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15779 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15780 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15781 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15783 case Intrinsic::x86_avx512_kortestz_w:
15784 case Intrinsic::x86_avx512_kortestc_w: {
15785 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15786 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15787 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15788 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15789 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15790 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15791 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15794 case Intrinsic::x86_sse42_pcmpistria128:
15795 case Intrinsic::x86_sse42_pcmpestria128:
15796 case Intrinsic::x86_sse42_pcmpistric128:
15797 case Intrinsic::x86_sse42_pcmpestric128:
15798 case Intrinsic::x86_sse42_pcmpistrio128:
15799 case Intrinsic::x86_sse42_pcmpestrio128:
15800 case Intrinsic::x86_sse42_pcmpistris128:
15801 case Intrinsic::x86_sse42_pcmpestris128:
15802 case Intrinsic::x86_sse42_pcmpistriz128:
15803 case Intrinsic::x86_sse42_pcmpestriz128: {
15807 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15808 case Intrinsic::x86_sse42_pcmpistria128:
15809 Opcode = X86ISD::PCMPISTRI;
15810 X86CC = X86::COND_A;
15812 case Intrinsic::x86_sse42_pcmpestria128:
15813 Opcode = X86ISD::PCMPESTRI;
15814 X86CC = X86::COND_A;
15816 case Intrinsic::x86_sse42_pcmpistric128:
15817 Opcode = X86ISD::PCMPISTRI;
15818 X86CC = X86::COND_B;
15820 case Intrinsic::x86_sse42_pcmpestric128:
15821 Opcode = X86ISD::PCMPESTRI;
15822 X86CC = X86::COND_B;
15824 case Intrinsic::x86_sse42_pcmpistrio128:
15825 Opcode = X86ISD::PCMPISTRI;
15826 X86CC = X86::COND_O;
15828 case Intrinsic::x86_sse42_pcmpestrio128:
15829 Opcode = X86ISD::PCMPESTRI;
15830 X86CC = X86::COND_O;
15832 case Intrinsic::x86_sse42_pcmpistris128:
15833 Opcode = X86ISD::PCMPISTRI;
15834 X86CC = X86::COND_S;
15836 case Intrinsic::x86_sse42_pcmpestris128:
15837 Opcode = X86ISD::PCMPESTRI;
15838 X86CC = X86::COND_S;
15840 case Intrinsic::x86_sse42_pcmpistriz128:
15841 Opcode = X86ISD::PCMPISTRI;
15842 X86CC = X86::COND_E;
15844 case Intrinsic::x86_sse42_pcmpestriz128:
15845 Opcode = X86ISD::PCMPESTRI;
15846 X86CC = X86::COND_E;
15849 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15850 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15851 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15852 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15853 DAG.getConstant(X86CC, dl, MVT::i8),
15854 SDValue(PCMP.getNode(), 1));
15855 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15858 case Intrinsic::x86_sse42_pcmpistri128:
15859 case Intrinsic::x86_sse42_pcmpestri128: {
15861 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15862 Opcode = X86ISD::PCMPISTRI;
15864 Opcode = X86ISD::PCMPESTRI;
15866 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15867 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15868 return DAG.getNode(Opcode, dl, VTs, NewOps);
15871 case Intrinsic::x86_seh_lsda: {
15872 // Compute the symbol for the LSDA. We know it'll get emitted later.
15873 MachineFunction &MF = DAG.getMachineFunction();
15874 SDValue Op1 = Op.getOperand(1);
15875 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15876 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15877 GlobalValue::getRealLinkageName(Fn->getName()));
15879 // Generate a simple absolute symbol reference. This intrinsic is only
15880 // supported on 32-bit Windows, which isn't PIC.
15881 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15882 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15885 case Intrinsic::x86_seh_recoverfp: {
15886 SDValue FnOp = Op.getOperand(1);
15887 SDValue IncomingFPOp = Op.getOperand(2);
15888 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15889 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15891 report_fatal_error(
15892 "llvm.x86.seh.recoverfp must take a function as the first argument");
15893 return recoverFramePointer(DAG, Fn, IncomingFPOp);
15896 case Intrinsic::localaddress: {
15897 // Returns one of the stack, base, or frame pointer registers, depending on
15898 // which is used to reference local variables.
15899 MachineFunction &MF = DAG.getMachineFunction();
15900 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15902 if (RegInfo->hasBasePointer(MF))
15903 Reg = RegInfo->getBaseRegister();
15904 else // This function handles the SP or FP case.
15905 Reg = RegInfo->getPtrSizedFrameRegister(MF);
15906 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15911 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15912 SDValue Src, SDValue Mask, SDValue Base,
15913 SDValue Index, SDValue ScaleOp, SDValue Chain,
15914 const X86Subtarget * Subtarget) {
15916 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15918 llvm_unreachable("Invalid scale type");
15919 unsigned ScaleVal = C->getZExtValue();
15920 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15921 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15923 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15924 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15925 Index.getSimpleValueType().getVectorNumElements());
15927 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15929 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15931 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15932 Mask.getValueType().getSizeInBits());
15934 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15935 // are extracted by EXTRACT_SUBVECTOR.
15936 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15937 DAG.getBitcast(BitcastVT, Mask),
15938 DAG.getIntPtrConstant(0, dl));
15940 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15941 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15942 SDValue Segment = DAG.getRegister(0, MVT::i32);
15943 if (Src.getOpcode() == ISD::UNDEF)
15944 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15945 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15946 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15947 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15948 return DAG.getMergeValues(RetOps, dl);
15951 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15952 SDValue Src, SDValue Mask, SDValue Base,
15953 SDValue Index, SDValue ScaleOp, SDValue Chain) {
15955 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15957 llvm_unreachable("Invalid scale type");
15958 unsigned ScaleVal = C->getZExtValue();
15959 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15960 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15962 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15963 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15964 SDValue Segment = DAG.getRegister(0, MVT::i32);
15965 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15966 Index.getSimpleValueType().getVectorNumElements());
15968 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15970 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15972 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15973 Mask.getValueType().getSizeInBits());
15975 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15976 // are extracted by EXTRACT_SUBVECTOR.
15977 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15978 DAG.getBitcast(BitcastVT, Mask),
15979 DAG.getIntPtrConstant(0, dl));
15981 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15982 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15983 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15984 return SDValue(Res, 1);
15987 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15988 SDValue Mask, SDValue Base, SDValue Index,
15989 SDValue ScaleOp, SDValue Chain) {
15991 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15992 assert(C && "Invalid scale type");
15993 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15994 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15995 SDValue Segment = DAG.getRegister(0, MVT::i32);
15997 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15999 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16001 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16003 MaskInReg = DAG.getBitcast(MaskVT, Mask);
16004 //SDVTList VTs = DAG.getVTList(MVT::Other);
16005 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16006 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16007 return SDValue(Res, 0);
16010 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16011 // read performance monitor counters (x86_rdpmc).
16012 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16013 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16014 SmallVectorImpl<SDValue> &Results) {
16015 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16016 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16019 // The ECX register is used to select the index of the performance counter
16021 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16023 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16025 // Reads the content of a 64-bit performance counter and returns it in the
16026 // registers EDX:EAX.
16027 if (Subtarget->is64Bit()) {
16028 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16029 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16032 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16033 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16036 Chain = HI.getValue(1);
16038 if (Subtarget->is64Bit()) {
16039 // The EAX register is loaded with the low-order 32 bits. The EDX register
16040 // is loaded with the supported high-order bits of the counter.
16041 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16042 DAG.getConstant(32, DL, MVT::i8));
16043 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16044 Results.push_back(Chain);
16048 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16049 SDValue Ops[] = { LO, HI };
16050 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16051 Results.push_back(Pair);
16052 Results.push_back(Chain);
16055 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16056 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16057 // also used to custom lower READCYCLECOUNTER nodes.
16058 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16059 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16060 SmallVectorImpl<SDValue> &Results) {
16061 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16062 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16065 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16066 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16067 // and the EAX register is loaded with the low-order 32 bits.
16068 if (Subtarget->is64Bit()) {
16069 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16070 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16073 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16074 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16077 SDValue Chain = HI.getValue(1);
16079 if (Opcode == X86ISD::RDTSCP_DAG) {
16080 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16082 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16083 // the ECX register. Add 'ecx' explicitly to the chain.
16084 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16086 // Explicitly store the content of ECX at the location passed in input
16087 // to the 'rdtscp' intrinsic.
16088 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16089 MachinePointerInfo(), false, false, 0);
16092 if (Subtarget->is64Bit()) {
16093 // The EDX register is loaded with the high-order 32 bits of the MSR, and
16094 // the EAX register is loaded with the low-order 32 bits.
16095 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16096 DAG.getConstant(32, DL, MVT::i8));
16097 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16098 Results.push_back(Chain);
16102 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16103 SDValue Ops[] = { LO, HI };
16104 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16105 Results.push_back(Pair);
16106 Results.push_back(Chain);
16109 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16110 SelectionDAG &DAG) {
16111 SmallVector<SDValue, 2> Results;
16113 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16115 return DAG.getMergeValues(Results, DL);
16118 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16119 SelectionDAG &DAG) {
16120 MachineFunction &MF = DAG.getMachineFunction();
16121 const Function *Fn = MF.getFunction();
16123 SDValue Chain = Op.getOperand(0);
16125 assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16126 "using llvm.x86.seh.restoreframe requires a frame pointer");
16128 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16129 MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16131 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16132 unsigned FrameReg =
16133 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16134 unsigned SPReg = RegInfo->getStackRegister();
16135 unsigned SlotSize = RegInfo->getSlotSize();
16137 // Get incoming EBP.
16138 SDValue IncomingEBP =
16139 DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16141 // SP is saved in the first field of every registration node, so load
16142 // [EBP-RegNodeSize] into SP.
16143 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16144 SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16145 DAG.getConstant(-RegNodeSize, dl, VT));
16147 DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16148 false, VT.getScalarSizeInBits() / 8);
16149 Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16151 if (!RegInfo->needsStackRealignment(MF)) {
16152 // Adjust EBP to point back to the original frame position.
16153 SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16154 Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16156 assert(RegInfo->hasBasePointer(MF) &&
16157 "functions with Win32 EH must use frame or base pointer register");
16159 // Reload the base pointer (ESI) with the adjusted incoming EBP.
16160 SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16161 Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16163 // Reload the spilled EBP value, now that the stack and base pointers are
16165 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16166 X86FI->setHasSEHFramePtrSave(true);
16167 int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16168 X86FI->setSEHFramePtrSaveIndex(FI);
16169 SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16170 MachinePointerInfo(), false, false, false,
16171 VT.getScalarSizeInBits() / 8);
16172 Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16178 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16179 /// return truncate Store/MaskedStore Node
16180 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16184 SDValue Mask = Op.getOperand(4);
16185 SDValue DataToTruncate = Op.getOperand(3);
16186 SDValue Addr = Op.getOperand(2);
16187 SDValue Chain = Op.getOperand(0);
16189 EVT VT = DataToTruncate.getValueType();
16190 EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16191 ElementType, VT.getVectorNumElements());
16193 if (isAllOnes(Mask)) // return just a truncate store
16194 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16195 MachinePointerInfo(), SVT, false, false,
16196 SVT.getScalarSizeInBits()/8);
16198 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16199 MVT::i1, VT.getVectorNumElements());
16200 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16201 Mask.getValueType().getSizeInBits());
16202 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16203 // are extracted by EXTRACT_SUBVECTOR.
16204 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16205 DAG.getBitcast(BitcastVT, Mask),
16206 DAG.getIntPtrConstant(0, dl));
16208 MachineMemOperand *MMO = DAG.getMachineFunction().
16209 getMachineMemOperand(MachinePointerInfo(),
16210 MachineMemOperand::MOStore, SVT.getStoreSize(),
16211 SVT.getScalarSizeInBits()/8);
16213 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16214 VMask, SVT, MMO, true);
16217 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16218 SelectionDAG &DAG) {
16219 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16221 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16223 if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16224 return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16229 switch(IntrData->Type) {
16231 llvm_unreachable("Unknown Intrinsic Type");
16235 // Emit the node with the right value type.
16236 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16237 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16239 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16240 // Otherwise return the value from Rand, which is always 0, casted to i32.
16241 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16242 DAG.getConstant(1, dl, Op->getValueType(1)),
16243 DAG.getConstant(X86::COND_B, dl, MVT::i32),
16244 SDValue(Result.getNode(), 1) };
16245 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16246 DAG.getVTList(Op->getValueType(1), MVT::Glue),
16249 // Return { result, isValid, chain }.
16250 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16251 SDValue(Result.getNode(), 2));
16254 //gather(v1, mask, index, base, scale);
16255 SDValue Chain = Op.getOperand(0);
16256 SDValue Src = Op.getOperand(2);
16257 SDValue Base = Op.getOperand(3);
16258 SDValue Index = Op.getOperand(4);
16259 SDValue Mask = Op.getOperand(5);
16260 SDValue Scale = Op.getOperand(6);
16261 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16265 //scatter(base, mask, index, v1, scale);
16266 SDValue Chain = Op.getOperand(0);
16267 SDValue Base = Op.getOperand(2);
16268 SDValue Mask = Op.getOperand(3);
16269 SDValue Index = Op.getOperand(4);
16270 SDValue Src = Op.getOperand(5);
16271 SDValue Scale = Op.getOperand(6);
16272 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16276 SDValue Hint = Op.getOperand(6);
16277 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16278 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16279 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16280 SDValue Chain = Op.getOperand(0);
16281 SDValue Mask = Op.getOperand(2);
16282 SDValue Index = Op.getOperand(3);
16283 SDValue Base = Op.getOperand(4);
16284 SDValue Scale = Op.getOperand(5);
16285 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16287 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16289 SmallVector<SDValue, 2> Results;
16290 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16292 return DAG.getMergeValues(Results, dl);
16294 // Read Performance Monitoring Counters.
16296 SmallVector<SDValue, 2> Results;
16297 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16298 return DAG.getMergeValues(Results, dl);
16300 // XTEST intrinsics.
16302 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16303 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16304 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16305 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16307 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16308 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16309 Ret, SDValue(InTrans.getNode(), 1));
16313 SmallVector<SDValue, 2> Results;
16314 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16315 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16316 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16317 DAG.getConstant(-1, dl, MVT::i8));
16318 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16319 Op.getOperand(4), GenCF.getValue(1));
16320 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16321 Op.getOperand(5), MachinePointerInfo(),
16323 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16324 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16326 Results.push_back(SetCC);
16327 Results.push_back(Store);
16328 return DAG.getMergeValues(Results, dl);
16330 case COMPRESS_TO_MEM: {
16332 SDValue Mask = Op.getOperand(4);
16333 SDValue DataToCompress = Op.getOperand(3);
16334 SDValue Addr = Op.getOperand(2);
16335 SDValue Chain = Op.getOperand(0);
16337 EVT VT = DataToCompress.getValueType();
16338 if (isAllOnes(Mask)) // return just a store
16339 return DAG.getStore(Chain, dl, DataToCompress, Addr,
16340 MachinePointerInfo(), false, false,
16341 VT.getScalarSizeInBits()/8);
16343 SDValue Compressed =
16344 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16345 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16346 return DAG.getStore(Chain, dl, Compressed, Addr,
16347 MachinePointerInfo(), false, false,
16348 VT.getScalarSizeInBits()/8);
16350 case TRUNCATE_TO_MEM_VI8:
16351 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16352 case TRUNCATE_TO_MEM_VI16:
16353 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16354 case TRUNCATE_TO_MEM_VI32:
16355 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16356 case EXPAND_FROM_MEM: {
16358 SDValue Mask = Op.getOperand(4);
16359 SDValue PassThru = Op.getOperand(3);
16360 SDValue Addr = Op.getOperand(2);
16361 SDValue Chain = Op.getOperand(0);
16362 EVT VT = Op.getValueType();
16364 if (isAllOnes(Mask)) // return just a load
16365 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16366 false, VT.getScalarSizeInBits()/8);
16368 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16369 false, false, false,
16370 VT.getScalarSizeInBits()/8);
16372 SDValue Results[] = {
16373 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16374 Mask, PassThru, Subtarget, DAG), Chain};
16375 return DAG.getMergeValues(Results, dl);
16380 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16381 SelectionDAG &DAG) const {
16382 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16383 MFI->setReturnAddressIsTaken(true);
16385 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16388 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16390 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16393 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16394 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16395 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16396 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16397 DAG.getNode(ISD::ADD, dl, PtrVT,
16398 FrameAddr, Offset),
16399 MachinePointerInfo(), false, false, false, 0);
16402 // Just load the return address.
16403 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16404 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16405 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16408 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16409 MachineFunction &MF = DAG.getMachineFunction();
16410 MachineFrameInfo *MFI = MF.getFrameInfo();
16411 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16412 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16413 EVT VT = Op.getValueType();
16415 MFI->setFrameAddressIsTaken(true);
16417 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16418 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
16419 // is not possible to crawl up the stack without looking at the unwind codes
16421 int FrameAddrIndex = FuncInfo->getFAIndex();
16422 if (!FrameAddrIndex) {
16423 // Set up a frame object for the return address.
16424 unsigned SlotSize = RegInfo->getSlotSize();
16425 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16426 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16427 FuncInfo->setFAIndex(FrameAddrIndex);
16429 return DAG.getFrameIndex(FrameAddrIndex, VT);
16432 unsigned FrameReg =
16433 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16434 SDLoc dl(Op); // FIXME probably not meaningful
16435 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16436 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16437 (FrameReg == X86::EBP && VT == MVT::i32)) &&
16438 "Invalid Frame Register!");
16439 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16441 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16442 MachinePointerInfo(),
16443 false, false, false, 0);
16447 // FIXME? Maybe this could be a TableGen attribute on some registers and
16448 // this table could be generated automatically from RegInfo.
16449 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16450 SelectionDAG &DAG) const {
16451 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16452 const MachineFunction &MF = DAG.getMachineFunction();
16454 unsigned Reg = StringSwitch<unsigned>(RegName)
16455 .Case("esp", X86::ESP)
16456 .Case("rsp", X86::RSP)
16457 .Case("ebp", X86::EBP)
16458 .Case("rbp", X86::RBP)
16461 if (Reg == X86::EBP || Reg == X86::RBP) {
16462 if (!TFI.hasFP(MF))
16463 report_fatal_error("register " + StringRef(RegName) +
16464 " is allocatable: function has no frame pointer");
16467 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16468 unsigned FrameReg =
16469 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16470 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16471 "Invalid Frame Register!");
16479 report_fatal_error("Invalid register name global variable");
16482 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16483 SelectionDAG &DAG) const {
16484 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16485 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16488 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16489 SDValue Chain = Op.getOperand(0);
16490 SDValue Offset = Op.getOperand(1);
16491 SDValue Handler = Op.getOperand(2);
16494 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16495 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16496 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16497 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16498 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16499 "Invalid Frame Register!");
16500 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16501 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16503 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16504 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16506 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16507 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16509 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16511 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16512 DAG.getRegister(StoreAddrReg, PtrVT));
16515 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16516 SelectionDAG &DAG) const {
16518 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16519 DAG.getVTList(MVT::i32, MVT::Other),
16520 Op.getOperand(0), Op.getOperand(1));
16523 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16524 SelectionDAG &DAG) const {
16526 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16527 Op.getOperand(0), Op.getOperand(1));
16530 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16531 return Op.getOperand(0);
16534 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16535 SelectionDAG &DAG) const {
16536 SDValue Root = Op.getOperand(0);
16537 SDValue Trmp = Op.getOperand(1); // trampoline
16538 SDValue FPtr = Op.getOperand(2); // nested function
16539 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16542 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16543 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16545 if (Subtarget->is64Bit()) {
16546 SDValue OutChains[6];
16548 // Large code-model.
16549 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
16550 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16552 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16553 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16555 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16557 // Load the pointer to the nested function into R11.
16558 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16559 SDValue Addr = Trmp;
16560 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16561 Addr, MachinePointerInfo(TrmpAddr),
16564 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16565 DAG.getConstant(2, dl, MVT::i64));
16566 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16567 MachinePointerInfo(TrmpAddr, 2),
16570 // Load the 'nest' parameter value into R10.
16571 // R10 is specified in X86CallingConv.td
16572 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16573 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16574 DAG.getConstant(10, dl, MVT::i64));
16575 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16576 Addr, MachinePointerInfo(TrmpAddr, 10),
16579 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16580 DAG.getConstant(12, dl, MVT::i64));
16581 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16582 MachinePointerInfo(TrmpAddr, 12),
16585 // Jump to the nested function.
16586 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16587 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16588 DAG.getConstant(20, dl, MVT::i64));
16589 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16590 Addr, MachinePointerInfo(TrmpAddr, 20),
16593 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16594 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16595 DAG.getConstant(22, dl, MVT::i64));
16596 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16597 Addr, MachinePointerInfo(TrmpAddr, 22),
16600 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16602 const Function *Func =
16603 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16604 CallingConv::ID CC = Func->getCallingConv();
16609 llvm_unreachable("Unsupported calling convention");
16610 case CallingConv::C:
16611 case CallingConv::X86_StdCall: {
16612 // Pass 'nest' parameter in ECX.
16613 // Must be kept in sync with X86CallingConv.td
16614 NestReg = X86::ECX;
16616 // Check that ECX wasn't needed by an 'inreg' parameter.
16617 FunctionType *FTy = Func->getFunctionType();
16618 const AttributeSet &Attrs = Func->getAttributes();
16620 if (!Attrs.isEmpty() && !Func->isVarArg()) {
16621 unsigned InRegCount = 0;
16624 for (FunctionType::param_iterator I = FTy->param_begin(),
16625 E = FTy->param_end(); I != E; ++I, ++Idx)
16626 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16627 auto &DL = DAG.getDataLayout();
16628 // FIXME: should only count parameters that are lowered to integers.
16629 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16632 if (InRegCount > 2) {
16633 report_fatal_error("Nest register in use - reduce number of inreg"
16639 case CallingConv::X86_FastCall:
16640 case CallingConv::X86_ThisCall:
16641 case CallingConv::Fast:
16642 // Pass 'nest' parameter in EAX.
16643 // Must be kept in sync with X86CallingConv.td
16644 NestReg = X86::EAX;
16648 SDValue OutChains[4];
16649 SDValue Addr, Disp;
16651 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16652 DAG.getConstant(10, dl, MVT::i32));
16653 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16655 // This is storing the opcode for MOV32ri.
16656 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16657 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16658 OutChains[0] = DAG.getStore(Root, dl,
16659 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16660 Trmp, MachinePointerInfo(TrmpAddr),
16663 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16664 DAG.getConstant(1, dl, MVT::i32));
16665 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16666 MachinePointerInfo(TrmpAddr, 1),
16669 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16670 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16671 DAG.getConstant(5, dl, MVT::i32));
16672 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16673 Addr, MachinePointerInfo(TrmpAddr, 5),
16676 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16677 DAG.getConstant(6, dl, MVT::i32));
16678 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16679 MachinePointerInfo(TrmpAddr, 6),
16682 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16686 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16687 SelectionDAG &DAG) const {
16689 The rounding mode is in bits 11:10 of FPSR, and has the following
16691 00 Round to nearest
16696 FLT_ROUNDS, on the other hand, expects the following:
16703 To perform the conversion, we do:
16704 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16707 MachineFunction &MF = DAG.getMachineFunction();
16708 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16709 unsigned StackAlignment = TFI.getStackAlignment();
16710 MVT VT = Op.getSimpleValueType();
16713 // Save FP Control Word to stack slot
16714 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16715 SDValue StackSlot =
16716 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16718 MachineMemOperand *MMO =
16719 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
16720 MachineMemOperand::MOStore, 2, 2);
16722 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16723 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16724 DAG.getVTList(MVT::Other),
16725 Ops, MVT::i16, MMO);
16727 // Load FP Control Word from stack slot
16728 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16729 MachinePointerInfo(), false, false, false, 0);
16731 // Transform as necessary
16733 DAG.getNode(ISD::SRL, DL, MVT::i16,
16734 DAG.getNode(ISD::AND, DL, MVT::i16,
16735 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16736 DAG.getConstant(11, DL, MVT::i8));
16738 DAG.getNode(ISD::SRL, DL, MVT::i16,
16739 DAG.getNode(ISD::AND, DL, MVT::i16,
16740 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16741 DAG.getConstant(9, DL, MVT::i8));
16744 DAG.getNode(ISD::AND, DL, MVT::i16,
16745 DAG.getNode(ISD::ADD, DL, MVT::i16,
16746 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16747 DAG.getConstant(1, DL, MVT::i16)),
16748 DAG.getConstant(3, DL, MVT::i16));
16750 return DAG.getNode((VT.getSizeInBits() < 16 ?
16751 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16754 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16755 MVT VT = Op.getSimpleValueType();
16757 unsigned NumBits = VT.getSizeInBits();
16760 Op = Op.getOperand(0);
16761 if (VT == MVT::i8) {
16762 // Zero extend to i32 since there is not an i8 bsr.
16764 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16767 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16768 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16769 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16771 // If src is zero (i.e. bsr sets ZF), returns NumBits.
16774 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16775 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16778 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16780 // Finally xor with NumBits-1.
16781 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16782 DAG.getConstant(NumBits - 1, dl, OpVT));
16785 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16789 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16790 MVT VT = Op.getSimpleValueType();
16792 unsigned NumBits = VT.getSizeInBits();
16795 Op = Op.getOperand(0);
16796 if (VT == MVT::i8) {
16797 // Zero extend to i32 since there is not an i8 bsr.
16799 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16802 // Issue a bsr (scan bits in reverse).
16803 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16804 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16806 // And xor with NumBits-1.
16807 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16808 DAG.getConstant(NumBits - 1, dl, OpVT));
16811 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16815 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16816 MVT VT = Op.getSimpleValueType();
16817 unsigned NumBits = VT.getSizeInBits();
16819 Op = Op.getOperand(0);
16821 // Issue a bsf (scan bits forward) which also sets EFLAGS.
16822 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16823 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16825 // If src is zero (i.e. bsf sets ZF), returns NumBits.
16828 DAG.getConstant(NumBits, dl, VT),
16829 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16832 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16835 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16836 // ones, and then concatenate the result back.
16837 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16838 MVT VT = Op.getSimpleValueType();
16840 assert(VT.is256BitVector() && VT.isInteger() &&
16841 "Unsupported value type for operation");
16843 unsigned NumElems = VT.getVectorNumElements();
16846 // Extract the LHS vectors
16847 SDValue LHS = Op.getOperand(0);
16848 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16849 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16851 // Extract the RHS vectors
16852 SDValue RHS = Op.getOperand(1);
16853 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16854 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16856 MVT EltVT = VT.getVectorElementType();
16857 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16859 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16860 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16861 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16864 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16865 if (Op.getValueType() == MVT::i1)
16866 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16867 Op.getOperand(0), Op.getOperand(1));
16868 assert(Op.getSimpleValueType().is256BitVector() &&
16869 Op.getSimpleValueType().isInteger() &&
16870 "Only handle AVX 256-bit vector integer operation");
16871 return Lower256IntArith(Op, DAG);
16874 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16875 if (Op.getValueType() == MVT::i1)
16876 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16877 Op.getOperand(0), Op.getOperand(1));
16878 assert(Op.getSimpleValueType().is256BitVector() &&
16879 Op.getSimpleValueType().isInteger() &&
16880 "Only handle AVX 256-bit vector integer operation");
16881 return Lower256IntArith(Op, DAG);
16884 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16885 SelectionDAG &DAG) {
16887 MVT VT = Op.getSimpleValueType();
16890 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16892 // Decompose 256-bit ops into smaller 128-bit ops.
16893 if (VT.is256BitVector() && !Subtarget->hasInt256())
16894 return Lower256IntArith(Op, DAG);
16896 SDValue A = Op.getOperand(0);
16897 SDValue B = Op.getOperand(1);
16899 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16900 // pairs, multiply and truncate.
16901 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16902 if (Subtarget->hasInt256()) {
16903 if (VT == MVT::v32i8) {
16904 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16905 SDValue Lo = DAG.getIntPtrConstant(0, dl);
16906 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16907 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16908 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16909 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16910 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16911 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16912 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16913 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16916 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16917 return DAG.getNode(
16918 ISD::TRUNCATE, dl, VT,
16919 DAG.getNode(ISD::MUL, dl, ExVT,
16920 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16921 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16924 assert(VT == MVT::v16i8 &&
16925 "Pre-AVX2 support only supports v16i8 multiplication");
16926 MVT ExVT = MVT::v8i16;
16928 // Extract the lo parts and sign extend to i16
16930 if (Subtarget->hasSSE41()) {
16931 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16932 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16934 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16935 -1, 4, -1, 5, -1, 6, -1, 7};
16936 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16937 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16938 ALo = DAG.getBitcast(ExVT, ALo);
16939 BLo = DAG.getBitcast(ExVT, BLo);
16940 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16941 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16944 // Extract the hi parts and sign extend to i16
16946 if (Subtarget->hasSSE41()) {
16947 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
16948 -1, -1, -1, -1, -1, -1, -1, -1};
16949 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16950 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16951 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16952 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16954 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
16955 -1, 12, -1, 13, -1, 14, -1, 15};
16956 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16957 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16958 AHi = DAG.getBitcast(ExVT, AHi);
16959 BHi = DAG.getBitcast(ExVT, BHi);
16960 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16961 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16964 // Multiply, mask the lower 8bits of the lo/hi results and pack
16965 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16966 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16967 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16968 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16969 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16972 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16973 if (VT == MVT::v4i32) {
16974 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16975 "Should not custom lower when pmuldq is available!");
16977 // Extract the odd parts.
16978 static const int UnpackMask[] = { 1, -1, 3, -1 };
16979 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16980 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16982 // Multiply the even parts.
16983 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16984 // Now multiply odd parts.
16985 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16987 Evens = DAG.getBitcast(VT, Evens);
16988 Odds = DAG.getBitcast(VT, Odds);
16990 // Merge the two vectors back together with a shuffle. This expands into 2
16992 static const int ShufMask[] = { 0, 4, 2, 6 };
16993 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16996 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16997 "Only know how to lower V2I64/V4I64/V8I64 multiply");
16999 // Ahi = psrlqi(a, 32);
17000 // Bhi = psrlqi(b, 32);
17002 // AloBlo = pmuludq(a, b);
17003 // AloBhi = pmuludq(a, Bhi);
17004 // AhiBlo = pmuludq(Ahi, b);
17006 // AloBhi = psllqi(AloBhi, 32);
17007 // AhiBlo = psllqi(AhiBlo, 32);
17008 // return AloBlo + AloBhi + AhiBlo;
17010 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17011 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17013 SDValue AhiBlo = Ahi;
17014 SDValue AloBhi = Bhi;
17015 // Bit cast to 32-bit vectors for MULUDQ
17016 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17017 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17018 A = DAG.getBitcast(MulVT, A);
17019 B = DAG.getBitcast(MulVT, B);
17020 Ahi = DAG.getBitcast(MulVT, Ahi);
17021 Bhi = DAG.getBitcast(MulVT, Bhi);
17023 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17024 // After shifting right const values the result may be all-zero.
17025 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17026 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17027 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17029 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17030 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17031 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17034 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17035 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17038 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17039 assert(Subtarget->isTargetWin64() && "Unexpected target");
17040 EVT VT = Op.getValueType();
17041 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17042 "Unexpected return type for lowering");
17046 switch (Op->getOpcode()) {
17047 default: llvm_unreachable("Unexpected request for libcall!");
17048 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
17049 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
17050 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
17051 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
17052 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
17053 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17057 SDValue InChain = DAG.getEntryNode();
17059 TargetLowering::ArgListTy Args;
17060 TargetLowering::ArgListEntry Entry;
17061 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17062 EVT ArgVT = Op->getOperand(i).getValueType();
17063 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17064 "Unexpected argument type for lowering");
17065 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17066 Entry.Node = StackPtr;
17067 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17069 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17070 Entry.Ty = PointerType::get(ArgTy,0);
17071 Entry.isSExt = false;
17072 Entry.isZExt = false;
17073 Args.push_back(Entry);
17076 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17077 getPointerTy(DAG.getDataLayout()));
17079 TargetLowering::CallLoweringInfo CLI(DAG);
17080 CLI.setDebugLoc(dl).setChain(InChain)
17081 .setCallee(getLibcallCallingConv(LC),
17082 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17083 Callee, std::move(Args), 0)
17084 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17086 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17087 return DAG.getBitcast(VT, CallInfo.first);
17090 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17091 SelectionDAG &DAG) {
17092 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17093 EVT VT = Op0.getValueType();
17096 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17097 (VT == MVT::v8i32 && Subtarget->hasInt256()));
17099 // PMULxD operations multiply each even value (starting at 0) of LHS with
17100 // the related value of RHS and produce a widen result.
17101 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17102 // => <2 x i64> <ae|cg>
17104 // In other word, to have all the results, we need to perform two PMULxD:
17105 // 1. one with the even values.
17106 // 2. one with the odd values.
17107 // To achieve #2, with need to place the odd values at an even position.
17109 // Place the odd value at an even position (basically, shift all values 1
17110 // step to the left):
17111 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17112 // <a|b|c|d> => <b|undef|d|undef>
17113 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17114 // <e|f|g|h> => <f|undef|h|undef>
17115 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17117 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17119 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17120 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17122 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17123 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17124 // => <2 x i64> <ae|cg>
17125 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17126 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17127 // => <2 x i64> <bf|dh>
17128 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17130 // Shuffle it back into the right order.
17131 SDValue Highs, Lows;
17132 if (VT == MVT::v8i32) {
17133 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17134 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17135 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17136 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17138 const int HighMask[] = {1, 5, 3, 7};
17139 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17140 const int LowMask[] = {0, 4, 2, 6};
17141 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17144 // If we have a signed multiply but no PMULDQ fix up the high parts of a
17145 // unsigned multiply.
17146 if (IsSigned && !Subtarget->hasSSE41()) {
17147 SDValue ShAmt = DAG.getConstant(
17149 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17150 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17151 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17152 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17153 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17155 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17156 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17159 // The first result of MUL_LOHI is actually the low value, followed by the
17161 SDValue Ops[] = {Lows, Highs};
17162 return DAG.getMergeValues(Ops, dl);
17165 // Return true if the required (according to Opcode) shift-imm form is natively
17166 // supported by the Subtarget
17167 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17169 if (VT.getScalarSizeInBits() < 16)
17172 if (VT.is512BitVector() &&
17173 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17176 bool LShift = VT.is128BitVector() ||
17177 (VT.is256BitVector() && Subtarget->hasInt256());
17179 bool AShift = LShift && (Subtarget->hasVLX() ||
17180 (VT != MVT::v2i64 && VT != MVT::v4i64));
17181 return (Opcode == ISD::SRA) ? AShift : LShift;
17184 // The shift amount is a variable, but it is the same for all vector lanes.
17185 // These instructions are defined together with shift-immediate.
17187 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17189 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17192 // Return true if the required (according to Opcode) variable-shift form is
17193 // natively supported by the Subtarget
17194 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17197 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17200 // vXi16 supported only on AVX-512, BWI
17201 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17204 if (VT.is512BitVector() || Subtarget->hasVLX())
17207 bool LShift = VT.is128BitVector() || VT.is256BitVector();
17208 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
17209 return (Opcode == ISD::SRA) ? AShift : LShift;
17212 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17213 const X86Subtarget *Subtarget) {
17214 MVT VT = Op.getSimpleValueType();
17216 SDValue R = Op.getOperand(0);
17217 SDValue Amt = Op.getOperand(1);
17219 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17220 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17222 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17223 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17224 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17225 SDValue Ex = DAG.getBitcast(ExVT, R);
17227 if (ShiftAmt >= 32) {
17228 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17230 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17231 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17232 ShiftAmt - 32, DAG);
17233 if (VT == MVT::v2i64)
17234 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17235 if (VT == MVT::v4i64)
17236 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17237 {9, 1, 11, 3, 13, 5, 15, 7});
17239 // SRA upper i32, SHL whole i64 and select lower i32.
17240 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17243 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17244 Lower = DAG.getBitcast(ExVT, Lower);
17245 if (VT == MVT::v2i64)
17246 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17247 if (VT == MVT::v4i64)
17248 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17249 {8, 1, 10, 3, 12, 5, 14, 7});
17251 return DAG.getBitcast(VT, Ex);
17254 // Optimize shl/srl/sra with constant shift amount.
17255 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17256 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17257 uint64_t ShiftAmt = ShiftConst->getZExtValue();
17259 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17260 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17262 // i64 SRA needs to be performed as partial shifts.
17263 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17264 Op.getOpcode() == ISD::SRA)
17265 return ArithmeticShiftRight64(ShiftAmt);
17267 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17268 unsigned NumElts = VT.getVectorNumElements();
17269 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17271 if (Op.getOpcode() == ISD::SHL) {
17272 // Simple i8 add case
17274 return DAG.getNode(ISD::ADD, dl, VT, R, R);
17276 // Make a large shift.
17277 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17279 SHL = DAG.getBitcast(VT, SHL);
17280 // Zero out the rightmost bits.
17281 SmallVector<SDValue, 32> V(
17282 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17283 return DAG.getNode(ISD::AND, dl, VT, SHL,
17284 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17286 if (Op.getOpcode() == ISD::SRL) {
17287 // Make a large shift.
17288 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17290 SRL = DAG.getBitcast(VT, SRL);
17291 // Zero out the leftmost bits.
17292 SmallVector<SDValue, 32> V(
17293 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17294 return DAG.getNode(ISD::AND, dl, VT, SRL,
17295 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17297 if (Op.getOpcode() == ISD::SRA) {
17298 if (ShiftAmt == 7) {
17299 // ashr(R, 7) === cmp_slt(R, 0)
17300 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17301 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17304 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17305 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17306 SmallVector<SDValue, 32> V(NumElts,
17307 DAG.getConstant(128 >> ShiftAmt, dl,
17309 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17310 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17311 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17314 llvm_unreachable("Unknown shift opcode.");
17319 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17320 if (!Subtarget->is64Bit() &&
17321 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17323 // Peek through any splat that was introduced for i64 shift vectorization.
17324 int SplatIndex = -1;
17325 if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17326 if (SVN->isSplat()) {
17327 SplatIndex = SVN->getSplatIndex();
17328 Amt = Amt.getOperand(0);
17329 assert(SplatIndex < (int)VT.getVectorNumElements() &&
17330 "Splat shuffle referencing second operand");
17333 if (Amt.getOpcode() != ISD::BITCAST ||
17334 Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17337 Amt = Amt.getOperand(0);
17338 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17339 VT.getVectorNumElements();
17340 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17341 uint64_t ShiftAmt = 0;
17342 unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17343 for (unsigned i = 0; i != Ratio; ++i) {
17344 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17348 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17351 // Check remaining shift amounts (if not a splat).
17352 if (SplatIndex < 0) {
17353 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17354 uint64_t ShAmt = 0;
17355 for (unsigned j = 0; j != Ratio; ++j) {
17356 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17360 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17362 if (ShAmt != ShiftAmt)
17367 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17368 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17370 if (Op.getOpcode() == ISD::SRA)
17371 return ArithmeticShiftRight64(ShiftAmt);
17377 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17378 const X86Subtarget* Subtarget) {
17379 MVT VT = Op.getSimpleValueType();
17381 SDValue R = Op.getOperand(0);
17382 SDValue Amt = Op.getOperand(1);
17384 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17385 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17387 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17388 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17390 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17392 EVT EltVT = VT.getVectorElementType();
17394 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17395 // Check if this build_vector node is doing a splat.
17396 // If so, then set BaseShAmt equal to the splat value.
17397 BaseShAmt = BV->getSplatValue();
17398 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17399 BaseShAmt = SDValue();
17401 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17402 Amt = Amt.getOperand(0);
17404 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17405 if (SVN && SVN->isSplat()) {
17406 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17407 SDValue InVec = Amt.getOperand(0);
17408 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17409 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17410 "Unexpected shuffle index found!");
17411 BaseShAmt = InVec.getOperand(SplatIdx);
17412 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17413 if (ConstantSDNode *C =
17414 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17415 if (C->getZExtValue() == SplatIdx)
17416 BaseShAmt = InVec.getOperand(1);
17421 // Avoid introducing an extract element from a shuffle.
17422 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17423 DAG.getIntPtrConstant(SplatIdx, dl));
17427 if (BaseShAmt.getNode()) {
17428 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17429 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17430 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17431 else if (EltVT.bitsLT(MVT::i32))
17432 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17434 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17438 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17439 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
17440 Amt.getOpcode() == ISD::BITCAST &&
17441 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17442 Amt = Amt.getOperand(0);
17443 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17444 VT.getVectorNumElements();
17445 std::vector<SDValue> Vals(Ratio);
17446 for (unsigned i = 0; i != Ratio; ++i)
17447 Vals[i] = Amt.getOperand(i);
17448 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17449 for (unsigned j = 0; j != Ratio; ++j)
17450 if (Vals[j] != Amt.getOperand(i + j))
17454 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17455 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17460 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17461 SelectionDAG &DAG) {
17462 MVT VT = Op.getSimpleValueType();
17464 SDValue R = Op.getOperand(0);
17465 SDValue Amt = Op.getOperand(1);
17467 assert(VT.isVector() && "Custom lowering only for vector shifts!");
17468 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17470 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17473 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17476 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17479 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17480 // shifts per-lane and then shuffle the partial results back together.
17481 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17482 // Splat the shift amounts so the scalar shifts above will catch it.
17483 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17484 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17485 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17486 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17487 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17490 // i64 vector arithmetic shift can be emulated with the transform:
17491 // M = lshr(SIGN_BIT, Amt)
17492 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17493 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17494 Op.getOpcode() == ISD::SRA) {
17495 SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17496 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17497 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17498 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17499 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17503 // If possible, lower this packed shift into a vector multiply instead of
17504 // expanding it into a sequence of scalar shifts.
17505 // Do this only if the vector shift count is a constant build_vector.
17506 if (Op.getOpcode() == ISD::SHL &&
17507 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17508 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17509 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17510 SmallVector<SDValue, 8> Elts;
17511 EVT SVT = VT.getScalarType();
17512 unsigned SVTBits = SVT.getSizeInBits();
17513 const APInt &One = APInt(SVTBits, 1);
17514 unsigned NumElems = VT.getVectorNumElements();
17516 for (unsigned i=0; i !=NumElems; ++i) {
17517 SDValue Op = Amt->getOperand(i);
17518 if (Op->getOpcode() == ISD::UNDEF) {
17519 Elts.push_back(Op);
17523 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17524 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17525 uint64_t ShAmt = C.getZExtValue();
17526 if (ShAmt >= SVTBits) {
17527 Elts.push_back(DAG.getUNDEF(SVT));
17530 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17532 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17533 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17536 // Lower SHL with variable shift amount.
17537 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17538 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17540 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17541 DAG.getConstant(0x3f800000U, dl, VT));
17542 Op = DAG.getBitcast(MVT::v4f32, Op);
17543 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17544 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17547 // If possible, lower this shift as a sequence of two shifts by
17548 // constant plus a MOVSS/MOVSD instead of scalarizing it.
17550 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17552 // Could be rewritten as:
17553 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17555 // The advantage is that the two shifts from the example would be
17556 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17557 // the vector shift into four scalar shifts plus four pairs of vector
17559 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17560 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17561 unsigned TargetOpcode = X86ISD::MOVSS;
17562 bool CanBeSimplified;
17563 // The splat value for the first packed shift (the 'X' from the example).
17564 SDValue Amt1 = Amt->getOperand(0);
17565 // The splat value for the second packed shift (the 'Y' from the example).
17566 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17567 Amt->getOperand(2);
17569 // See if it is possible to replace this node with a sequence of
17570 // two shifts followed by a MOVSS/MOVSD
17571 if (VT == MVT::v4i32) {
17572 // Check if it is legal to use a MOVSS.
17573 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17574 Amt2 == Amt->getOperand(3);
17575 if (!CanBeSimplified) {
17576 // Otherwise, check if we can still simplify this node using a MOVSD.
17577 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17578 Amt->getOperand(2) == Amt->getOperand(3);
17579 TargetOpcode = X86ISD::MOVSD;
17580 Amt2 = Amt->getOperand(2);
17583 // Do similar checks for the case where the machine value type
17585 CanBeSimplified = Amt1 == Amt->getOperand(1);
17586 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17587 CanBeSimplified = Amt2 == Amt->getOperand(i);
17589 if (!CanBeSimplified) {
17590 TargetOpcode = X86ISD::MOVSD;
17591 CanBeSimplified = true;
17592 Amt2 = Amt->getOperand(4);
17593 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17594 CanBeSimplified = Amt1 == Amt->getOperand(i);
17595 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17596 CanBeSimplified = Amt2 == Amt->getOperand(j);
17600 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17601 isa<ConstantSDNode>(Amt2)) {
17602 // Replace this node with two shifts followed by a MOVSS/MOVSD.
17603 EVT CastVT = MVT::v4i32;
17605 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17606 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17608 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17609 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17610 if (TargetOpcode == X86ISD::MOVSD)
17611 CastVT = MVT::v2i64;
17612 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17613 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17614 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17616 return DAG.getBitcast(VT, Result);
17620 // v4i32 Non Uniform Shifts.
17621 // If the shift amount is constant we can shift each lane using the SSE2
17622 // immediate shifts, else we need to zero-extend each lane to the lower i64
17623 // and shift using the SSE2 variable shifts.
17624 // The separate results can then be blended together.
17625 if (VT == MVT::v4i32) {
17626 unsigned Opc = Op.getOpcode();
17627 SDValue Amt0, Amt1, Amt2, Amt3;
17628 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17629 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17630 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17631 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17632 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17634 // ISD::SHL is handled above but we include it here for completeness.
17637 llvm_unreachable("Unknown target vector shift node");
17639 Opc = X86ISD::VSHL;
17642 Opc = X86ISD::VSRL;
17645 Opc = X86ISD::VSRA;
17648 // The SSE2 shifts use the lower i64 as the same shift amount for
17649 // all lanes and the upper i64 is ignored. These shuffle masks
17650 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17651 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17652 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17653 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17654 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17655 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17658 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17659 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17660 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17661 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17662 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17663 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17664 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17667 if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17668 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17669 unsigned ShiftOpcode = Op->getOpcode();
17671 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17672 // On SSE41 targets we make use of the fact that VSELECT lowers
17673 // to PBLENDVB which selects bytes based just on the sign bit.
17674 if (Subtarget->hasSSE41()) {
17675 V0 = DAG.getBitcast(VT, V0);
17676 V1 = DAG.getBitcast(VT, V1);
17677 Sel = DAG.getBitcast(VT, Sel);
17678 return DAG.getBitcast(SelVT,
17679 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17681 // On pre-SSE41 targets we test for the sign bit by comparing to
17682 // zero - a negative value will set all bits of the lanes to true
17683 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17684 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17685 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17686 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17689 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17690 // We can safely do this using i16 shifts as we're only interested in
17691 // the 3 lower bits of each byte.
17692 Amt = DAG.getBitcast(ExtVT, Amt);
17693 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17694 Amt = DAG.getBitcast(VT, Amt);
17696 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17697 // r = VSELECT(r, shift(r, 4), a);
17699 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17700 R = SignBitSelect(VT, Amt, M, R);
17703 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17705 // r = VSELECT(r, shift(r, 2), a);
17706 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17707 R = SignBitSelect(VT, Amt, M, R);
17710 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17712 // return VSELECT(r, shift(r, 1), a);
17713 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17714 R = SignBitSelect(VT, Amt, M, R);
17718 if (Op->getOpcode() == ISD::SRA) {
17719 // For SRA we need to unpack each byte to the higher byte of a i16 vector
17720 // so we can correctly sign extend. We don't care what happens to the
17722 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17723 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17724 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17725 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17726 ALo = DAG.getBitcast(ExtVT, ALo);
17727 AHi = DAG.getBitcast(ExtVT, AHi);
17728 RLo = DAG.getBitcast(ExtVT, RLo);
17729 RHi = DAG.getBitcast(ExtVT, RHi);
17731 // r = VSELECT(r, shift(r, 4), a);
17732 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17733 DAG.getConstant(4, dl, ExtVT));
17734 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17735 DAG.getConstant(4, dl, ExtVT));
17736 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17737 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17740 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17741 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17743 // r = VSELECT(r, shift(r, 2), a);
17744 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17745 DAG.getConstant(2, dl, ExtVT));
17746 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17747 DAG.getConstant(2, dl, ExtVT));
17748 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17749 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17752 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17753 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17755 // r = VSELECT(r, shift(r, 1), a);
17756 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17757 DAG.getConstant(1, dl, ExtVT));
17758 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17759 DAG.getConstant(1, dl, ExtVT));
17760 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17761 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17763 // Logical shift the result back to the lower byte, leaving a zero upper
17765 // meaning that we can safely pack with PACKUSWB.
17767 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17769 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17770 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17774 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17775 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17776 // solution better.
17777 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17778 MVT ExtVT = MVT::v8i32;
17780 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17781 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17782 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17783 return DAG.getNode(ISD::TRUNCATE, dl, VT,
17784 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17787 if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17788 MVT ExtVT = MVT::v8i32;
17789 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17790 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17791 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17792 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17793 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17794 ALo = DAG.getBitcast(ExtVT, ALo);
17795 AHi = DAG.getBitcast(ExtVT, AHi);
17796 RLo = DAG.getBitcast(ExtVT, RLo);
17797 RHi = DAG.getBitcast(ExtVT, RHi);
17798 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17799 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17800 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17801 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17802 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17805 if (VT == MVT::v8i16) {
17806 unsigned ShiftOpcode = Op->getOpcode();
17808 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17809 // On SSE41 targets we make use of the fact that VSELECT lowers
17810 // to PBLENDVB which selects bytes based just on the sign bit.
17811 if (Subtarget->hasSSE41()) {
17812 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17813 V0 = DAG.getBitcast(ExtVT, V0);
17814 V1 = DAG.getBitcast(ExtVT, V1);
17815 Sel = DAG.getBitcast(ExtVT, Sel);
17816 return DAG.getBitcast(
17817 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17819 // On pre-SSE41 targets we splat the sign bit - a negative value will
17820 // set all bits of the lanes to true and VSELECT uses that in
17821 // its OR(AND(V0,C),AND(V1,~C)) lowering.
17823 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17824 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17827 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17828 if (Subtarget->hasSSE41()) {
17829 // On SSE41 targets we need to replicate the shift mask in both
17830 // bytes for PBLENDVB.
17833 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17834 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17836 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17839 // r = VSELECT(r, shift(r, 8), a);
17840 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17841 R = SignBitSelect(Amt, M, R);
17844 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17846 // r = VSELECT(r, shift(r, 4), a);
17847 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17848 R = SignBitSelect(Amt, M, R);
17851 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17853 // r = VSELECT(r, shift(r, 2), a);
17854 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17855 R = SignBitSelect(Amt, M, R);
17858 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17860 // return VSELECT(r, shift(r, 1), a);
17861 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17862 R = SignBitSelect(Amt, M, R);
17866 // Decompose 256-bit shifts into smaller 128-bit shifts.
17867 if (VT.is256BitVector()) {
17868 unsigned NumElems = VT.getVectorNumElements();
17869 MVT EltVT = VT.getVectorElementType();
17870 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17872 // Extract the two vectors
17873 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17874 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17876 // Recreate the shift amount vectors
17877 SDValue Amt1, Amt2;
17878 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17879 // Constant shift amount
17880 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17881 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17882 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17884 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17885 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17887 // Variable shift amount
17888 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17889 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17892 // Issue new vector shifts for the smaller types
17893 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17894 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17896 // Concatenate the result back
17897 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17903 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17904 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17905 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17906 // looks for this combo and may remove the "setcc" instruction if the "setcc"
17907 // has only one use.
17908 SDNode *N = Op.getNode();
17909 SDValue LHS = N->getOperand(0);
17910 SDValue RHS = N->getOperand(1);
17911 unsigned BaseOp = 0;
17914 switch (Op.getOpcode()) {
17915 default: llvm_unreachable("Unknown ovf instruction!");
17917 // A subtract of one will be selected as a INC. Note that INC doesn't
17918 // set CF, so we can't do this for UADDO.
17919 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17921 BaseOp = X86ISD::INC;
17922 Cond = X86::COND_O;
17925 BaseOp = X86ISD::ADD;
17926 Cond = X86::COND_O;
17929 BaseOp = X86ISD::ADD;
17930 Cond = X86::COND_B;
17933 // A subtract of one will be selected as a DEC. Note that DEC doesn't
17934 // set CF, so we can't do this for USUBO.
17935 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17937 BaseOp = X86ISD::DEC;
17938 Cond = X86::COND_O;
17941 BaseOp = X86ISD::SUB;
17942 Cond = X86::COND_O;
17945 BaseOp = X86ISD::SUB;
17946 Cond = X86::COND_B;
17949 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17950 Cond = X86::COND_O;
17952 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17953 if (N->getValueType(0) == MVT::i8) {
17954 BaseOp = X86ISD::UMUL8;
17955 Cond = X86::COND_O;
17958 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17960 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17963 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17964 DAG.getConstant(X86::COND_O, DL, MVT::i32),
17965 SDValue(Sum.getNode(), 2));
17967 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17971 // Also sets EFLAGS.
17972 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17973 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17976 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17977 DAG.getConstant(Cond, DL, MVT::i32),
17978 SDValue(Sum.getNode(), 1));
17980 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17983 /// Returns true if the operand type is exactly twice the native width, and
17984 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17985 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17986 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17987 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
17988 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17991 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17992 else if (OpWidth == 128)
17993 return Subtarget->hasCmpxchg16b();
17998 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17999 return needsCmpXchgNb(SI->getValueOperand()->getType());
18002 // Note: this turns large loads into lock cmpxchg8b/16b.
18003 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18004 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18005 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18006 return needsCmpXchgNb(PTy->getElementType());
18009 TargetLoweringBase::AtomicRMWExpansionKind
18010 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18011 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18012 Type *MemType = AI->getType();
18014 // If the operand is too big, we must see if cmpxchg8/16b is available
18015 // and default to library calls otherwise.
18016 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18017 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
18018 : AtomicRMWExpansionKind::None;
18021 AtomicRMWInst::BinOp Op = AI->getOperation();
18024 llvm_unreachable("Unknown atomic operation");
18025 case AtomicRMWInst::Xchg:
18026 case AtomicRMWInst::Add:
18027 case AtomicRMWInst::Sub:
18028 // It's better to use xadd, xsub or xchg for these in all cases.
18029 return AtomicRMWExpansionKind::None;
18030 case AtomicRMWInst::Or:
18031 case AtomicRMWInst::And:
18032 case AtomicRMWInst::Xor:
18033 // If the atomicrmw's result isn't actually used, we can just add a "lock"
18034 // prefix to a normal instruction for these operations.
18035 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
18036 : AtomicRMWExpansionKind::None;
18037 case AtomicRMWInst::Nand:
18038 case AtomicRMWInst::Max:
18039 case AtomicRMWInst::Min:
18040 case AtomicRMWInst::UMax:
18041 case AtomicRMWInst::UMin:
18042 // These always require a non-trivial set of data operations on x86. We must
18043 // use a cmpxchg loop.
18044 return AtomicRMWExpansionKind::CmpXChg;
18048 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18049 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18050 // no-sse2). There isn't any reason to disable it if the target processor
18052 return Subtarget.hasSSE2() || Subtarget.is64Bit();
18056 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18057 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18058 Type *MemType = AI->getType();
18059 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18060 // there is no benefit in turning such RMWs into loads, and it is actually
18061 // harmful as it introduces a mfence.
18062 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18065 auto Builder = IRBuilder<>(AI);
18066 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18067 auto SynchScope = AI->getSynchScope();
18068 // We must restrict the ordering to avoid generating loads with Release or
18069 // ReleaseAcquire orderings.
18070 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18071 auto Ptr = AI->getPointerOperand();
18073 // Before the load we need a fence. Here is an example lifted from
18074 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18077 // x.store(1, relaxed);
18078 // r1 = y.fetch_add(0, release);
18080 // y.fetch_add(42, acquire);
18081 // r2 = x.load(relaxed);
18082 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18083 // lowered to just a load without a fence. A mfence flushes the store buffer,
18084 // making the optimization clearly correct.
18085 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18086 // otherwise, we might be able to be more aggressive on relaxed idempotent
18087 // rmw. In practice, they do not look useful, so we don't try to be
18088 // especially clever.
18089 if (SynchScope == SingleThread)
18090 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18091 // the IR level, so we must wrap it in an intrinsic.
18094 if (!hasMFENCE(*Subtarget))
18095 // FIXME: it might make sense to use a locked operation here but on a
18096 // different cache-line to prevent cache-line bouncing. In practice it
18097 // is probably a small win, and x86 processors without mfence are rare
18098 // enough that we do not bother.
18102 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18103 Builder.CreateCall(MFence, {});
18105 // Finally we can emit the atomic load.
18106 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18107 AI->getType()->getPrimitiveSizeInBits());
18108 Loaded->setAtomic(Order, SynchScope);
18109 AI->replaceAllUsesWith(Loaded);
18110 AI->eraseFromParent();
18114 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18115 SelectionDAG &DAG) {
18117 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18118 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18119 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18120 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18122 // The only fence that needs an instruction is a sequentially-consistent
18123 // cross-thread fence.
18124 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18125 if (hasMFENCE(*Subtarget))
18126 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18128 SDValue Chain = Op.getOperand(0);
18129 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18131 DAG.getRegister(X86::ESP, MVT::i32), // Base
18132 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
18133 DAG.getRegister(0, MVT::i32), // Index
18134 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
18135 DAG.getRegister(0, MVT::i32), // Segment.
18139 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18140 return SDValue(Res, 0);
18143 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18144 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18147 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18148 SelectionDAG &DAG) {
18149 MVT T = Op.getSimpleValueType();
18153 switch(T.SimpleTy) {
18154 default: llvm_unreachable("Invalid value type!");
18155 case MVT::i8: Reg = X86::AL; size = 1; break;
18156 case MVT::i16: Reg = X86::AX; size = 2; break;
18157 case MVT::i32: Reg = X86::EAX; size = 4; break;
18159 assert(Subtarget->is64Bit() && "Node not type legal!");
18160 Reg = X86::RAX; size = 8;
18163 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18164 Op.getOperand(2), SDValue());
18165 SDValue Ops[] = { cpIn.getValue(0),
18168 DAG.getTargetConstant(size, DL, MVT::i8),
18169 cpIn.getValue(1) };
18170 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18171 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18172 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18176 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18177 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18178 MVT::i32, cpOut.getValue(2));
18179 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18180 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18183 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18184 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18185 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18189 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18190 SelectionDAG &DAG) {
18191 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18192 MVT DstVT = Op.getSimpleValueType();
18194 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18195 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18196 if (DstVT != MVT::f64)
18197 // This conversion needs to be expanded.
18200 SDValue InVec = Op->getOperand(0);
18202 unsigned NumElts = SrcVT.getVectorNumElements();
18203 EVT SVT = SrcVT.getVectorElementType();
18205 // Widen the vector in input in the case of MVT::v2i32.
18206 // Example: from MVT::v2i32 to MVT::v4i32.
18207 SmallVector<SDValue, 16> Elts;
18208 for (unsigned i = 0, e = NumElts; i != e; ++i)
18209 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18210 DAG.getIntPtrConstant(i, dl)));
18212 // Explicitly mark the extra elements as Undef.
18213 Elts.append(NumElts, DAG.getUNDEF(SVT));
18215 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18216 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18217 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18218 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18219 DAG.getIntPtrConstant(0, dl));
18222 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18223 Subtarget->hasMMX() && "Unexpected custom BITCAST");
18224 assert((DstVT == MVT::i64 ||
18225 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18226 "Unexpected custom BITCAST");
18227 // i64 <=> MMX conversions are Legal.
18228 if (SrcVT==MVT::i64 && DstVT.isVector())
18230 if (DstVT==MVT::i64 && SrcVT.isVector())
18232 // MMX <=> MMX conversions are Legal.
18233 if (SrcVT.isVector() && DstVT.isVector())
18235 // All other conversions need to be expanded.
18239 /// Compute the horizontal sum of bytes in V for the elements of VT.
18241 /// Requires V to be a byte vector and VT to be an integer vector type with
18242 /// wider elements than V's type. The width of the elements of VT determines
18243 /// how many bytes of V are summed horizontally to produce each element of the
18245 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18246 const X86Subtarget *Subtarget,
18247 SelectionDAG &DAG) {
18249 MVT ByteVecVT = V.getSimpleValueType();
18250 MVT EltVT = VT.getVectorElementType();
18251 int NumElts = VT.getVectorNumElements();
18252 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18253 "Expected value to have byte element type.");
18254 assert(EltVT != MVT::i8 &&
18255 "Horizontal byte sum only makes sense for wider elements!");
18256 unsigned VecSize = VT.getSizeInBits();
18257 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18259 // PSADBW instruction horizontally add all bytes and leave the result in i64
18260 // chunks, thus directly computes the pop count for v2i64 and v4i64.
18261 if (EltVT == MVT::i64) {
18262 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18263 V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18264 return DAG.getBitcast(VT, V);
18267 if (EltVT == MVT::i32) {
18268 // We unpack the low half and high half into i32s interleaved with zeros so
18269 // that we can use PSADBW to horizontally sum them. The most useful part of
18270 // this is that it lines up the results of two PSADBW instructions to be
18271 // two v2i64 vectors which concatenated are the 4 population counts. We can
18272 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18273 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18274 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18275 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18277 // Do the horizontal sums into two v2i64s.
18278 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18279 Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18280 DAG.getBitcast(ByteVecVT, Low), Zeros);
18281 High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18282 DAG.getBitcast(ByteVecVT, High), Zeros);
18284 // Merge them together.
18285 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18286 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18287 DAG.getBitcast(ShortVecVT, Low),
18288 DAG.getBitcast(ShortVecVT, High));
18290 return DAG.getBitcast(VT, V);
18293 // The only element type left is i16.
18294 assert(EltVT == MVT::i16 && "Unknown how to handle type");
18296 // To obtain pop count for each i16 element starting from the pop count for
18297 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18298 // right by 8. It is important to shift as i16s as i8 vector shift isn't
18299 // directly supported.
18300 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18301 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18302 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18303 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18304 DAG.getBitcast(ByteVecVT, V));
18305 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18308 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18309 const X86Subtarget *Subtarget,
18310 SelectionDAG &DAG) {
18311 MVT VT = Op.getSimpleValueType();
18312 MVT EltVT = VT.getVectorElementType();
18313 unsigned VecSize = VT.getSizeInBits();
18315 // Implement a lookup table in register by using an algorithm based on:
18316 // http://wm.ite.pl/articles/sse-popcount.html
18318 // The general idea is that every lower byte nibble in the input vector is an
18319 // index into a in-register pre-computed pop count table. We then split up the
18320 // input vector in two new ones: (1) a vector with only the shifted-right
18321 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18322 // masked out higher ones) for each byte. PSHUB is used separately with both
18323 // to index the in-register table. Next, both are added and the result is a
18324 // i8 vector where each element contains the pop count for input byte.
18326 // To obtain the pop count for elements != i8, we follow up with the same
18327 // approach and use additional tricks as described below.
18329 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18330 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18331 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18332 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18334 int NumByteElts = VecSize / 8;
18335 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18336 SDValue In = DAG.getBitcast(ByteVecVT, Op);
18337 SmallVector<SDValue, 16> LUTVec;
18338 for (int i = 0; i < NumByteElts; ++i)
18339 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18340 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18341 SmallVector<SDValue, 16> Mask0F(NumByteElts,
18342 DAG.getConstant(0x0F, DL, MVT::i8));
18343 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18346 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18347 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18348 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18351 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18353 // The input vector is used as the shuffle mask that index elements into the
18354 // LUT. After counting low and high nibbles, add the vector to obtain the
18355 // final pop count per i8 element.
18356 SDValue HighPopCnt =
18357 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18358 SDValue LowPopCnt =
18359 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18360 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18362 if (EltVT == MVT::i8)
18365 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18368 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18369 const X86Subtarget *Subtarget,
18370 SelectionDAG &DAG) {
18371 MVT VT = Op.getSimpleValueType();
18372 assert(VT.is128BitVector() &&
18373 "Only 128-bit vector bitmath lowering supported.");
18375 int VecSize = VT.getSizeInBits();
18376 MVT EltVT = VT.getVectorElementType();
18377 int Len = EltVT.getSizeInBits();
18379 // This is the vectorized version of the "best" algorithm from
18380 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18381 // with a minor tweak to use a series of adds + shifts instead of vector
18382 // multiplications. Implemented for all integer vector types. We only use
18383 // this when we don't have SSSE3 which allows a LUT-based lowering that is
18384 // much faster, even faster than using native popcnt instructions.
18386 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18387 MVT VT = V.getSimpleValueType();
18388 SmallVector<SDValue, 32> Shifters(
18389 VT.getVectorNumElements(),
18390 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18391 return DAG.getNode(OpCode, DL, VT, V,
18392 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18394 auto GetMask = [&](SDValue V, APInt Mask) {
18395 MVT VT = V.getSimpleValueType();
18396 SmallVector<SDValue, 32> Masks(
18397 VT.getVectorNumElements(),
18398 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18399 return DAG.getNode(ISD::AND, DL, VT, V,
18400 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18403 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18404 // x86, so set the SRL type to have elements at least i16 wide. This is
18405 // correct because all of our SRLs are followed immediately by a mask anyways
18406 // that handles any bits that sneak into the high bits of the byte elements.
18407 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18411 // v = v - ((v >> 1) & 0x55555555...)
18413 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18414 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18415 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18417 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18418 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18419 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18420 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18421 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18423 // v = (v + (v >> 4)) & 0x0F0F0F0F...
18424 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18425 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18426 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18428 // At this point, V contains the byte-wise population count, and we are
18429 // merely doing a horizontal sum if necessary to get the wider element
18431 if (EltVT == MVT::i8)
18434 return LowerHorizontalByteSum(
18435 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18439 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18440 SelectionDAG &DAG) {
18441 MVT VT = Op.getSimpleValueType();
18442 // FIXME: Need to add AVX-512 support here!
18443 assert((VT.is256BitVector() || VT.is128BitVector()) &&
18444 "Unknown CTPOP type to handle");
18445 SDLoc DL(Op.getNode());
18446 SDValue Op0 = Op.getOperand(0);
18448 if (!Subtarget->hasSSSE3()) {
18449 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18450 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18451 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18454 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18455 unsigned NumElems = VT.getVectorNumElements();
18457 // Extract each 128-bit vector, compute pop count and concat the result.
18458 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18459 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18461 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18462 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18463 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18466 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18469 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18470 SelectionDAG &DAG) {
18471 assert(Op.getValueType().isVector() &&
18472 "We only do custom lowering for vector population count.");
18473 return LowerVectorCTPOP(Op, Subtarget, DAG);
18476 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18477 SDNode *Node = Op.getNode();
18479 EVT T = Node->getValueType(0);
18480 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18481 DAG.getConstant(0, dl, T), Node->getOperand(2));
18482 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18483 cast<AtomicSDNode>(Node)->getMemoryVT(),
18484 Node->getOperand(0),
18485 Node->getOperand(1), negOp,
18486 cast<AtomicSDNode>(Node)->getMemOperand(),
18487 cast<AtomicSDNode>(Node)->getOrdering(),
18488 cast<AtomicSDNode>(Node)->getSynchScope());
18491 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18492 SDNode *Node = Op.getNode();
18494 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18496 // Convert seq_cst store -> xchg
18497 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18498 // FIXME: On 32-bit, store -> fist or movq would be more efficient
18499 // (The only way to get a 16-byte store is cmpxchg16b)
18500 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18501 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18502 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18503 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18504 cast<AtomicSDNode>(Node)->getMemoryVT(),
18505 Node->getOperand(0),
18506 Node->getOperand(1), Node->getOperand(2),
18507 cast<AtomicSDNode>(Node)->getMemOperand(),
18508 cast<AtomicSDNode>(Node)->getOrdering(),
18509 cast<AtomicSDNode>(Node)->getSynchScope());
18510 return Swap.getValue(1);
18512 // Other atomic stores have a simple pattern.
18516 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18517 EVT VT = Op.getNode()->getSimpleValueType(0);
18519 // Let legalize expand this if it isn't a legal type yet.
18520 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18523 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18526 bool ExtraOp = false;
18527 switch (Op.getOpcode()) {
18528 default: llvm_unreachable("Invalid code");
18529 case ISD::ADDC: Opc = X86ISD::ADD; break;
18530 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18531 case ISD::SUBC: Opc = X86ISD::SUB; break;
18532 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18536 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18538 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18539 Op.getOperand(1), Op.getOperand(2));
18542 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18543 SelectionDAG &DAG) {
18544 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18546 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18547 // which returns the values as { float, float } (in XMM0) or
18548 // { double, double } (which is returned in XMM0, XMM1).
18550 SDValue Arg = Op.getOperand(0);
18551 EVT ArgVT = Arg.getValueType();
18552 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18554 TargetLowering::ArgListTy Args;
18555 TargetLowering::ArgListEntry Entry;
18559 Entry.isSExt = false;
18560 Entry.isZExt = false;
18561 Args.push_back(Entry);
18563 bool isF64 = ArgVT == MVT::f64;
18564 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18565 // the small struct {f32, f32} is returned in (eax, edx). For f64,
18566 // the results are returned via SRet in memory.
18567 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
18568 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18570 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18572 Type *RetTy = isF64
18573 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18574 : (Type*)VectorType::get(ArgTy, 4);
18576 TargetLowering::CallLoweringInfo CLI(DAG);
18577 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18578 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18580 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18583 // Returned in xmm0 and xmm1.
18584 return CallResult.first;
18586 // Returned in bits 0:31 and 32:64 xmm0.
18587 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18588 CallResult.first, DAG.getIntPtrConstant(0, dl));
18589 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18590 CallResult.first, DAG.getIntPtrConstant(1, dl));
18591 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18592 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18595 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18596 SelectionDAG &DAG) {
18597 assert(Subtarget->hasAVX512() &&
18598 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18600 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18601 EVT VT = N->getValue().getValueType();
18602 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18605 // X86 scatter kills mask register, so its type should be added to
18606 // the list of return values
18607 if (N->getNumValues() == 1) {
18608 SDValue Index = N->getIndex();
18609 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18610 !Index.getValueType().is512BitVector())
18611 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18613 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18614 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18615 N->getOperand(3), Index };
18617 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18618 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18619 return SDValue(NewScatter.getNode(), 0);
18624 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18625 SelectionDAG &DAG) {
18626 assert(Subtarget->hasAVX512() &&
18627 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18629 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18630 EVT VT = Op.getValueType();
18631 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18634 SDValue Index = N->getIndex();
18635 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18636 !Index.getValueType().is512BitVector()) {
18637 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18638 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18639 N->getOperand(3), Index };
18640 DAG.UpdateNodeOperands(N, Ops);
18645 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18646 SelectionDAG &DAG) const {
18647 // TODO: Eventually, the lowering of these nodes should be informed by or
18648 // deferred to the GC strategy for the function in which they appear. For
18649 // now, however, they must be lowered to something. Since they are logically
18650 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18651 // require special handling for these nodes), lower them as literal NOOPs for
18653 SmallVector<SDValue, 2> Ops;
18655 Ops.push_back(Op.getOperand(0));
18656 if (Op->getGluedNode())
18657 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18660 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18661 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18666 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18667 SelectionDAG &DAG) const {
18668 // TODO: Eventually, the lowering of these nodes should be informed by or
18669 // deferred to the GC strategy for the function in which they appear. For
18670 // now, however, they must be lowered to something. Since they are logically
18671 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18672 // require special handling for these nodes), lower them as literal NOOPs for
18674 SmallVector<SDValue, 2> Ops;
18676 Ops.push_back(Op.getOperand(0));
18677 if (Op->getGluedNode())
18678 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18681 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18682 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18687 /// LowerOperation - Provide custom lowering hooks for some operations.
18689 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18690 switch (Op.getOpcode()) {
18691 default: llvm_unreachable("Should not custom lower this!");
18692 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18693 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18694 return LowerCMP_SWAP(Op, Subtarget, DAG);
18695 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
18696 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
18697 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
18698 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
18699 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18700 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
18701 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
18702 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18703 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
18704 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18705 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18706 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
18707 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
18708 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
18709 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
18710 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
18711 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
18712 case ISD::SHL_PARTS:
18713 case ISD::SRA_PARTS:
18714 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
18715 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
18716 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
18717 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
18718 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
18719 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18720 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
18721 case ISD::SIGN_EXTEND_VECTOR_INREG:
18722 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18723 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
18724 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
18725 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
18726 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
18728 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
18729 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
18730 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
18731 case ISD::SETCC: return LowerSETCC(Op, DAG);
18732 case ISD::SELECT: return LowerSELECT(Op, DAG);
18733 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
18734 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
18735 case ISD::VASTART: return LowerVASTART(Op, DAG);
18736 case ISD::VAARG: return LowerVAARG(Op, DAG);
18737 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
18738 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18739 case ISD::INTRINSIC_VOID:
18740 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18741 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
18742 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
18743 case ISD::FRAME_TO_ARGS_OFFSET:
18744 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18745 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18746 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
18747 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
18748 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
18749 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
18750 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
18751 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
18752 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
18753 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18754 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
18755 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
18756 case ISD::UMUL_LOHI:
18757 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
18760 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
18766 case ISD::UMULO: return LowerXALUO(Op, DAG);
18767 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18768 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
18772 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18773 case ISD::ADD: return LowerADD(Op, DAG);
18774 case ISD::SUB: return LowerSUB(Op, DAG);
18775 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
18776 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
18777 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
18778 case ISD::GC_TRANSITION_START:
18779 return LowerGC_TRANSITION_START(Op, DAG);
18780 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
18784 /// ReplaceNodeResults - Replace a node with an illegal result type
18785 /// with a new node built out of custom code.
18786 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18787 SmallVectorImpl<SDValue>&Results,
18788 SelectionDAG &DAG) const {
18790 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18791 switch (N->getOpcode()) {
18793 llvm_unreachable("Do not know how to custom type legalize this operation!");
18794 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18795 case X86ISD::FMINC:
18797 case X86ISD::FMAXC:
18798 case X86ISD::FMAX: {
18799 EVT VT = N->getValueType(0);
18800 if (VT != MVT::v2f32)
18801 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18802 SDValue UNDEF = DAG.getUNDEF(VT);
18803 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18804 N->getOperand(0), UNDEF);
18805 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18806 N->getOperand(1), UNDEF);
18807 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18810 case ISD::SIGN_EXTEND_INREG:
18815 // We don't want to expand or promote these.
18822 case ISD::UDIVREM: {
18823 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18824 Results.push_back(V);
18827 case ISD::FP_TO_SINT:
18828 // FP_TO_INT*_IN_MEM is not legal for f16 inputs. Do not convert
18829 // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18830 if (N->getOperand(0).getValueType() == MVT::f16)
18833 case ISD::FP_TO_UINT: {
18834 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18836 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18839 std::pair<SDValue,SDValue> Vals =
18840 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18841 SDValue FIST = Vals.first, StackSlot = Vals.second;
18842 if (FIST.getNode()) {
18843 EVT VT = N->getValueType(0);
18844 // Return a load from the stack slot.
18845 if (StackSlot.getNode())
18846 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18847 MachinePointerInfo(),
18848 false, false, false, 0));
18850 Results.push_back(FIST);
18854 case ISD::UINT_TO_FP: {
18855 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18856 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18857 N->getValueType(0) != MVT::v2f32)
18859 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18861 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18863 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18864 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18865 DAG.getBitcast(MVT::v2i64, VBias));
18866 Or = DAG.getBitcast(MVT::v2f64, Or);
18867 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18868 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18871 case ISD::FP_ROUND: {
18872 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18874 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18875 Results.push_back(V);
18878 case ISD::FP_EXTEND: {
18879 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18880 // No other ValueType for FP_EXTEND should reach this point.
18881 assert(N->getValueType(0) == MVT::v2f32 &&
18882 "Do not know how to legalize this Node");
18885 case ISD::INTRINSIC_W_CHAIN: {
18886 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18888 default : llvm_unreachable("Do not know how to custom type "
18889 "legalize this intrinsic operation!");
18890 case Intrinsic::x86_rdtsc:
18891 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18893 case Intrinsic::x86_rdtscp:
18894 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18896 case Intrinsic::x86_rdpmc:
18897 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18900 case ISD::READCYCLECOUNTER: {
18901 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18904 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18905 EVT T = N->getValueType(0);
18906 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18907 bool Regs64bit = T == MVT::i128;
18908 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18909 SDValue cpInL, cpInH;
18910 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18911 DAG.getConstant(0, dl, HalfT));
18912 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18913 DAG.getConstant(1, dl, HalfT));
18914 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18915 Regs64bit ? X86::RAX : X86::EAX,
18917 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18918 Regs64bit ? X86::RDX : X86::EDX,
18919 cpInH, cpInL.getValue(1));
18920 SDValue swapInL, swapInH;
18921 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18922 DAG.getConstant(0, dl, HalfT));
18923 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18924 DAG.getConstant(1, dl, HalfT));
18925 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18926 Regs64bit ? X86::RBX : X86::EBX,
18927 swapInL, cpInH.getValue(1));
18928 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18929 Regs64bit ? X86::RCX : X86::ECX,
18930 swapInH, swapInL.getValue(1));
18931 SDValue Ops[] = { swapInH.getValue(0),
18933 swapInH.getValue(1) };
18934 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18935 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18936 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18937 X86ISD::LCMPXCHG8_DAG;
18938 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18939 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18940 Regs64bit ? X86::RAX : X86::EAX,
18941 HalfT, Result.getValue(1));
18942 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18943 Regs64bit ? X86::RDX : X86::EDX,
18944 HalfT, cpOutL.getValue(2));
18945 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18947 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18948 MVT::i32, cpOutH.getValue(2));
18950 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18951 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18952 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18954 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18955 Results.push_back(Success);
18956 Results.push_back(EFLAGS.getValue(1));
18959 case ISD::ATOMIC_SWAP:
18960 case ISD::ATOMIC_LOAD_ADD:
18961 case ISD::ATOMIC_LOAD_SUB:
18962 case ISD::ATOMIC_LOAD_AND:
18963 case ISD::ATOMIC_LOAD_OR:
18964 case ISD::ATOMIC_LOAD_XOR:
18965 case ISD::ATOMIC_LOAD_NAND:
18966 case ISD::ATOMIC_LOAD_MIN:
18967 case ISD::ATOMIC_LOAD_MAX:
18968 case ISD::ATOMIC_LOAD_UMIN:
18969 case ISD::ATOMIC_LOAD_UMAX:
18970 case ISD::ATOMIC_LOAD: {
18971 // Delegate to generic TypeLegalization. Situations we can really handle
18972 // should have already been dealt with by AtomicExpandPass.cpp.
18975 case ISD::BITCAST: {
18976 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18977 EVT DstVT = N->getValueType(0);
18978 EVT SrcVT = N->getOperand(0)->getValueType(0);
18980 if (SrcVT != MVT::f64 ||
18981 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18984 unsigned NumElts = DstVT.getVectorNumElements();
18985 EVT SVT = DstVT.getVectorElementType();
18986 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18987 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18988 MVT::v2f64, N->getOperand(0));
18989 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18991 if (ExperimentalVectorWideningLegalization) {
18992 // If we are legalizing vectors by widening, we already have the desired
18993 // legal vector type, just return it.
18994 Results.push_back(ToVecInt);
18998 SmallVector<SDValue, 8> Elts;
18999 for (unsigned i = 0, e = NumElts; i != e; ++i)
19000 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19001 ToVecInt, DAG.getIntPtrConstant(i, dl)));
19003 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19008 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19009 switch ((X86ISD::NodeType)Opcode) {
19010 case X86ISD::FIRST_NUMBER: break;
19011 case X86ISD::BSF: return "X86ISD::BSF";
19012 case X86ISD::BSR: return "X86ISD::BSR";
19013 case X86ISD::SHLD: return "X86ISD::SHLD";
19014 case X86ISD::SHRD: return "X86ISD::SHRD";
19015 case X86ISD::FAND: return "X86ISD::FAND";
19016 case X86ISD::FANDN: return "X86ISD::FANDN";
19017 case X86ISD::FOR: return "X86ISD::FOR";
19018 case X86ISD::FXOR: return "X86ISD::FXOR";
19019 case X86ISD::FILD: return "X86ISD::FILD";
19020 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
19021 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19022 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19023 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19024 case X86ISD::FLD: return "X86ISD::FLD";
19025 case X86ISD::FST: return "X86ISD::FST";
19026 case X86ISD::CALL: return "X86ISD::CALL";
19027 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
19028 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
19029 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
19030 case X86ISD::BT: return "X86ISD::BT";
19031 case X86ISD::CMP: return "X86ISD::CMP";
19032 case X86ISD::COMI: return "X86ISD::COMI";
19033 case X86ISD::UCOMI: return "X86ISD::UCOMI";
19034 case X86ISD::CMPM: return "X86ISD::CMPM";
19035 case X86ISD::CMPMU: return "X86ISD::CMPMU";
19036 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
19037 case X86ISD::SETCC: return "X86ISD::SETCC";
19038 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
19039 case X86ISD::FSETCC: return "X86ISD::FSETCC";
19040 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
19041 case X86ISD::CMOV: return "X86ISD::CMOV";
19042 case X86ISD::BRCOND: return "X86ISD::BRCOND";
19043 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
19044 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
19045 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
19046 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
19047 case X86ISD::Wrapper: return "X86ISD::Wrapper";
19048 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
19049 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
19050 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
19051 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
19052 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
19053 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
19054 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
19055 case X86ISD::PINSRB: return "X86ISD::PINSRB";
19056 case X86ISD::PINSRW: return "X86ISD::PINSRW";
19057 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
19058 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
19059 case X86ISD::ANDNP: return "X86ISD::ANDNP";
19060 case X86ISD::PSIGN: return "X86ISD::PSIGN";
19061 case X86ISD::BLENDI: return "X86ISD::BLENDI";
19062 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
19063 case X86ISD::ADDUS: return "X86ISD::ADDUS";
19064 case X86ISD::SUBUS: return "X86ISD::SUBUS";
19065 case X86ISD::HADD: return "X86ISD::HADD";
19066 case X86ISD::HSUB: return "X86ISD::HSUB";
19067 case X86ISD::FHADD: return "X86ISD::FHADD";
19068 case X86ISD::FHSUB: return "X86ISD::FHSUB";
19069 case X86ISD::ABS: return "X86ISD::ABS";
19070 case X86ISD::FMAX: return "X86ISD::FMAX";
19071 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
19072 case X86ISD::FMIN: return "X86ISD::FMIN";
19073 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
19074 case X86ISD::FMAXC: return "X86ISD::FMAXC";
19075 case X86ISD::FMINC: return "X86ISD::FMINC";
19076 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
19077 case X86ISD::FRCP: return "X86ISD::FRCP";
19078 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
19079 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
19080 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
19081 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
19082 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
19083 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
19084 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
19085 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
19086 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
19087 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
19088 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
19089 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
19090 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
19091 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
19092 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
19093 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
19094 case X86ISD::VZEXT: return "X86ISD::VZEXT";
19095 case X86ISD::VSEXT: return "X86ISD::VSEXT";
19096 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
19097 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
19098 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
19099 case X86ISD::VINSERT: return "X86ISD::VINSERT";
19100 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
19101 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
19102 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
19103 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
19104 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
19105 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
19106 case X86ISD::VSHL: return "X86ISD::VSHL";
19107 case X86ISD::VSRL: return "X86ISD::VSRL";
19108 case X86ISD::VSRA: return "X86ISD::VSRA";
19109 case X86ISD::VSHLI: return "X86ISD::VSHLI";
19110 case X86ISD::VSRLI: return "X86ISD::VSRLI";
19111 case X86ISD::VSRAI: return "X86ISD::VSRAI";
19112 case X86ISD::CMPP: return "X86ISD::CMPP";
19113 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
19114 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
19115 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
19116 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
19117 case X86ISD::ADD: return "X86ISD::ADD";
19118 case X86ISD::SUB: return "X86ISD::SUB";
19119 case X86ISD::ADC: return "X86ISD::ADC";
19120 case X86ISD::SBB: return "X86ISD::SBB";
19121 case X86ISD::SMUL: return "X86ISD::SMUL";
19122 case X86ISD::UMUL: return "X86ISD::UMUL";
19123 case X86ISD::SMUL8: return "X86ISD::SMUL8";
19124 case X86ISD::UMUL8: return "X86ISD::UMUL8";
19125 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19126 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19127 case X86ISD::INC: return "X86ISD::INC";
19128 case X86ISD::DEC: return "X86ISD::DEC";
19129 case X86ISD::OR: return "X86ISD::OR";
19130 case X86ISD::XOR: return "X86ISD::XOR";
19131 case X86ISD::AND: return "X86ISD::AND";
19132 case X86ISD::BEXTR: return "X86ISD::BEXTR";
19133 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
19134 case X86ISD::PTEST: return "X86ISD::PTEST";
19135 case X86ISD::TESTP: return "X86ISD::TESTP";
19136 case X86ISD::TESTM: return "X86ISD::TESTM";
19137 case X86ISD::TESTNM: return "X86ISD::TESTNM";
19138 case X86ISD::KORTEST: return "X86ISD::KORTEST";
19139 case X86ISD::PACKSS: return "X86ISD::PACKSS";
19140 case X86ISD::PACKUS: return "X86ISD::PACKUS";
19141 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
19142 case X86ISD::VALIGN: return "X86ISD::VALIGN";
19143 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
19144 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
19145 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
19146 case X86ISD::SHUFP: return "X86ISD::SHUFP";
19147 case X86ISD::SHUF128: return "X86ISD::SHUF128";
19148 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
19149 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
19150 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
19151 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
19152 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
19153 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
19154 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
19155 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
19156 case X86ISD::MOVSD: return "X86ISD::MOVSD";
19157 case X86ISD::MOVSS: return "X86ISD::MOVSS";
19158 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
19159 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
19160 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
19161 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
19162 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
19163 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
19164 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
19165 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
19166 case X86ISD::VPERMV: return "X86ISD::VPERMV";
19167 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
19168 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
19169 case X86ISD::VPERMI: return "X86ISD::VPERMI";
19170 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
19171 case X86ISD::VRANGE: return "X86ISD::VRANGE";
19172 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
19173 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
19174 case X86ISD::PSADBW: return "X86ISD::PSADBW";
19175 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19176 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
19177 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
19178 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
19179 case X86ISD::MFENCE: return "X86ISD::MFENCE";
19180 case X86ISD::SFENCE: return "X86ISD::SFENCE";
19181 case X86ISD::LFENCE: return "X86ISD::LFENCE";
19182 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
19183 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
19184 case X86ISD::SAHF: return "X86ISD::SAHF";
19185 case X86ISD::RDRAND: return "X86ISD::RDRAND";
19186 case X86ISD::RDSEED: return "X86ISD::RDSEED";
19187 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
19188 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
19189 case X86ISD::FMADD: return "X86ISD::FMADD";
19190 case X86ISD::FMSUB: return "X86ISD::FMSUB";
19191 case X86ISD::FNMADD: return "X86ISD::FNMADD";
19192 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
19193 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
19194 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
19195 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
19196 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
19197 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
19198 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
19199 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
19200 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
19201 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
19202 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
19203 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
19204 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
19205 case X86ISD::XTEST: return "X86ISD::XTEST";
19206 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
19207 case X86ISD::EXPAND: return "X86ISD::EXPAND";
19208 case X86ISD::SELECT: return "X86ISD::SELECT";
19209 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
19210 case X86ISD::RCP28: return "X86ISD::RCP28";
19211 case X86ISD::EXP2: return "X86ISD::EXP2";
19212 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
19213 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
19214 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
19215 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
19216 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
19217 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
19218 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
19219 case X86ISD::SCALEF: return "X86ISD::SCALEF";
19220 case X86ISD::ADDS: return "X86ISD::ADDS";
19221 case X86ISD::SUBS: return "X86ISD::SUBS";
19222 case X86ISD::AVG: return "X86ISD::AVG";
19223 case X86ISD::MULHRS: return "X86ISD::MULHRS";
19224 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
19225 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
19226 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
19227 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
19232 // isLegalAddressingMode - Return true if the addressing mode represented
19233 // by AM is legal for this target, for a load/store of the specified type.
19234 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19235 const AddrMode &AM, Type *Ty,
19236 unsigned AS) const {
19237 // X86 supports extremely general addressing modes.
19238 CodeModel::Model M = getTargetMachine().getCodeModel();
19239 Reloc::Model R = getTargetMachine().getRelocationModel();
19241 // X86 allows a sign-extended 32-bit immediate field as a displacement.
19242 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19247 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19249 // If a reference to this global requires an extra load, we can't fold it.
19250 if (isGlobalStubReference(GVFlags))
19253 // If BaseGV requires a register for the PIC base, we cannot also have a
19254 // BaseReg specified.
19255 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19258 // If lower 4G is not available, then we must use rip-relative addressing.
19259 if ((M != CodeModel::Small || R != Reloc::Static) &&
19260 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19264 switch (AM.Scale) {
19270 // These scales always work.
19275 // These scales are formed with basereg+scalereg. Only accept if there is
19280 default: // Other stuff never works.
19287 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19288 unsigned Bits = Ty->getScalarSizeInBits();
19290 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19291 // particularly cheaper than those without.
19295 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19296 // variable shifts just as cheap as scalar ones.
19297 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19300 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19301 // fully general vector.
19305 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19306 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19308 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19309 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19310 return NumBits1 > NumBits2;
19313 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19314 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19317 if (!isTypeLegal(EVT::getEVT(Ty1)))
19320 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19322 // Assuming the caller doesn't have a zeroext or signext return parameter,
19323 // truncation all the way down to i1 is valid.
19327 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19328 return isInt<32>(Imm);
19331 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19332 // Can also use sub to handle negated immediates.
19333 return isInt<32>(Imm);
19336 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19337 if (!VT1.isInteger() || !VT2.isInteger())
19339 unsigned NumBits1 = VT1.getSizeInBits();
19340 unsigned NumBits2 = VT2.getSizeInBits();
19341 return NumBits1 > NumBits2;
19344 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19345 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19346 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19349 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19350 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19351 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19354 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19355 EVT VT1 = Val.getValueType();
19356 if (isZExtFree(VT1, VT2))
19359 if (Val.getOpcode() != ISD::LOAD)
19362 if (!VT1.isSimple() || !VT1.isInteger() ||
19363 !VT2.isSimple() || !VT2.isInteger())
19366 switch (VT1.getSimpleVT().SimpleTy) {
19371 // X86 has 8, 16, and 32-bit zero-extending loads.
19378 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19381 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19382 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19385 VT = VT.getScalarType();
19387 if (!VT.isSimple())
19390 switch (VT.getSimpleVT().SimpleTy) {
19401 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19402 // i16 instructions are longer (0x66 prefix) and potentially slower.
19403 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19406 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19407 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19408 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19409 /// are assumed to be legal.
19411 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19413 if (!VT.isSimple())
19416 // Not for i1 vectors
19417 if (VT.getScalarType() == MVT::i1)
19420 // Very little shuffling can be done for 64-bit vectors right now.
19421 if (VT.getSizeInBits() == 64)
19424 // We only care that the types being shuffled are legal. The lowering can
19425 // handle any possible shuffle mask that results.
19426 return isTypeLegal(VT.getSimpleVT());
19430 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19432 // Just delegate to the generic legality, clear masks aren't special.
19433 return isShuffleMaskLegal(Mask, VT);
19436 //===----------------------------------------------------------------------===//
19437 // X86 Scheduler Hooks
19438 //===----------------------------------------------------------------------===//
19440 /// Utility function to emit xbegin specifying the start of an RTM region.
19441 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19442 const TargetInstrInfo *TII) {
19443 DebugLoc DL = MI->getDebugLoc();
19445 const BasicBlock *BB = MBB->getBasicBlock();
19446 MachineFunction::iterator I = MBB;
19449 // For the v = xbegin(), we generate
19460 MachineBasicBlock *thisMBB = MBB;
19461 MachineFunction *MF = MBB->getParent();
19462 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19463 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19464 MF->insert(I, mainMBB);
19465 MF->insert(I, sinkMBB);
19467 // Transfer the remainder of BB and its successor edges to sinkMBB.
19468 sinkMBB->splice(sinkMBB->begin(), MBB,
19469 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19470 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19474 // # fallthrough to mainMBB
19475 // # abortion to sinkMBB
19476 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19477 thisMBB->addSuccessor(mainMBB);
19478 thisMBB->addSuccessor(sinkMBB);
19482 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19483 mainMBB->addSuccessor(sinkMBB);
19486 // EAX is live into the sinkMBB
19487 sinkMBB->addLiveIn(X86::EAX);
19488 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19489 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19492 MI->eraseFromParent();
19496 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19497 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19498 // in the .td file.
19499 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19500 const TargetInstrInfo *TII) {
19502 switch (MI->getOpcode()) {
19503 default: llvm_unreachable("illegal opcode!");
19504 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
19505 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19506 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
19507 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19508 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
19509 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19510 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
19511 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19514 DebugLoc dl = MI->getDebugLoc();
19515 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19517 unsigned NumArgs = MI->getNumOperands();
19518 for (unsigned i = 1; i < NumArgs; ++i) {
19519 MachineOperand &Op = MI->getOperand(i);
19520 if (!(Op.isReg() && Op.isImplicit()))
19521 MIB.addOperand(Op);
19523 if (MI->hasOneMemOperand())
19524 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19526 BuildMI(*BB, MI, dl,
19527 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19528 .addReg(X86::XMM0);
19530 MI->eraseFromParent();
19534 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19535 // defs in an instruction pattern
19536 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19537 const TargetInstrInfo *TII) {
19539 switch (MI->getOpcode()) {
19540 default: llvm_unreachable("illegal opcode!");
19541 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
19542 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19543 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
19544 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19545 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
19546 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19547 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
19548 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19551 DebugLoc dl = MI->getDebugLoc();
19552 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19554 unsigned NumArgs = MI->getNumOperands(); // remove the results
19555 for (unsigned i = 1; i < NumArgs; ++i) {
19556 MachineOperand &Op = MI->getOperand(i);
19557 if (!(Op.isReg() && Op.isImplicit()))
19558 MIB.addOperand(Op);
19560 if (MI->hasOneMemOperand())
19561 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19563 BuildMI(*BB, MI, dl,
19564 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19567 MI->eraseFromParent();
19571 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19572 const X86Subtarget *Subtarget) {
19573 DebugLoc dl = MI->getDebugLoc();
19574 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19575 // Address into RAX/EAX, other two args into ECX, EDX.
19576 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19577 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19578 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19579 for (int i = 0; i < X86::AddrNumOperands; ++i)
19580 MIB.addOperand(MI->getOperand(i));
19582 unsigned ValOps = X86::AddrNumOperands;
19583 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19584 .addReg(MI->getOperand(ValOps).getReg());
19585 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19586 .addReg(MI->getOperand(ValOps+1).getReg());
19588 // The instruction doesn't actually take any operands though.
19589 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19591 MI->eraseFromParent(); // The pseudo is gone now.
19595 MachineBasicBlock *
19596 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19597 MachineBasicBlock *MBB) const {
19598 // Emit va_arg instruction on X86-64.
19600 // Operands to this pseudo-instruction:
19601 // 0 ) Output : destination address (reg)
19602 // 1-5) Input : va_list address (addr, i64mem)
19603 // 6 ) ArgSize : Size (in bytes) of vararg type
19604 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19605 // 8 ) Align : Alignment of type
19606 // 9 ) EFLAGS (implicit-def)
19608 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19609 static_assert(X86::AddrNumOperands == 5,
19610 "VAARG_64 assumes 5 address operands");
19612 unsigned DestReg = MI->getOperand(0).getReg();
19613 MachineOperand &Base = MI->getOperand(1);
19614 MachineOperand &Scale = MI->getOperand(2);
19615 MachineOperand &Index = MI->getOperand(3);
19616 MachineOperand &Disp = MI->getOperand(4);
19617 MachineOperand &Segment = MI->getOperand(5);
19618 unsigned ArgSize = MI->getOperand(6).getImm();
19619 unsigned ArgMode = MI->getOperand(7).getImm();
19620 unsigned Align = MI->getOperand(8).getImm();
19622 // Memory Reference
19623 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19624 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19625 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19627 // Machine Information
19628 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19629 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19630 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19631 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19632 DebugLoc DL = MI->getDebugLoc();
19634 // struct va_list {
19637 // i64 overflow_area (address)
19638 // i64 reg_save_area (address)
19640 // sizeof(va_list) = 24
19641 // alignment(va_list) = 8
19643 unsigned TotalNumIntRegs = 6;
19644 unsigned TotalNumXMMRegs = 8;
19645 bool UseGPOffset = (ArgMode == 1);
19646 bool UseFPOffset = (ArgMode == 2);
19647 unsigned MaxOffset = TotalNumIntRegs * 8 +
19648 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19650 /* Align ArgSize to a multiple of 8 */
19651 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19652 bool NeedsAlign = (Align > 8);
19654 MachineBasicBlock *thisMBB = MBB;
19655 MachineBasicBlock *overflowMBB;
19656 MachineBasicBlock *offsetMBB;
19657 MachineBasicBlock *endMBB;
19659 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
19660 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
19661 unsigned OffsetReg = 0;
19663 if (!UseGPOffset && !UseFPOffset) {
19664 // If we only pull from the overflow region, we don't create a branch.
19665 // We don't need to alter control flow.
19666 OffsetDestReg = 0; // unused
19667 OverflowDestReg = DestReg;
19669 offsetMBB = nullptr;
19670 overflowMBB = thisMBB;
19673 // First emit code to check if gp_offset (or fp_offset) is below the bound.
19674 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19675 // If not, pull from overflow_area. (branch to overflowMBB)
19680 // offsetMBB overflowMBB
19685 // Registers for the PHI in endMBB
19686 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19687 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19689 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19690 MachineFunction *MF = MBB->getParent();
19691 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19692 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19693 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19695 MachineFunction::iterator MBBIter = MBB;
19698 // Insert the new basic blocks
19699 MF->insert(MBBIter, offsetMBB);
19700 MF->insert(MBBIter, overflowMBB);
19701 MF->insert(MBBIter, endMBB);
19703 // Transfer the remainder of MBB and its successor edges to endMBB.
19704 endMBB->splice(endMBB->begin(), thisMBB,
19705 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19706 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19708 // Make offsetMBB and overflowMBB successors of thisMBB
19709 thisMBB->addSuccessor(offsetMBB);
19710 thisMBB->addSuccessor(overflowMBB);
19712 // endMBB is a successor of both offsetMBB and overflowMBB
19713 offsetMBB->addSuccessor(endMBB);
19714 overflowMBB->addSuccessor(endMBB);
19716 // Load the offset value into a register
19717 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19718 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19722 .addDisp(Disp, UseFPOffset ? 4 : 0)
19723 .addOperand(Segment)
19724 .setMemRefs(MMOBegin, MMOEnd);
19726 // Check if there is enough room left to pull this argument.
19727 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19729 .addImm(MaxOffset + 8 - ArgSizeA8);
19731 // Branch to "overflowMBB" if offset >= max
19732 // Fall through to "offsetMBB" otherwise
19733 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19734 .addMBB(overflowMBB);
19737 // In offsetMBB, emit code to use the reg_save_area.
19739 assert(OffsetReg != 0);
19741 // Read the reg_save_area address.
19742 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19743 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19748 .addOperand(Segment)
19749 .setMemRefs(MMOBegin, MMOEnd);
19751 // Zero-extend the offset
19752 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19753 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19756 .addImm(X86::sub_32bit);
19758 // Add the offset to the reg_save_area to get the final address.
19759 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19760 .addReg(OffsetReg64)
19761 .addReg(RegSaveReg);
19763 // Compute the offset for the next argument
19764 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19765 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19767 .addImm(UseFPOffset ? 16 : 8);
19769 // Store it back into the va_list.
19770 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19774 .addDisp(Disp, UseFPOffset ? 4 : 0)
19775 .addOperand(Segment)
19776 .addReg(NextOffsetReg)
19777 .setMemRefs(MMOBegin, MMOEnd);
19780 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19785 // Emit code to use overflow area
19788 // Load the overflow_area address into a register.
19789 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19790 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19795 .addOperand(Segment)
19796 .setMemRefs(MMOBegin, MMOEnd);
19798 // If we need to align it, do so. Otherwise, just copy the address
19799 // to OverflowDestReg.
19801 // Align the overflow address
19802 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19803 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19805 // aligned_addr = (addr + (align-1)) & ~(align-1)
19806 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19807 .addReg(OverflowAddrReg)
19810 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19812 .addImm(~(uint64_t)(Align-1));
19814 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19815 .addReg(OverflowAddrReg);
19818 // Compute the next overflow address after this argument.
19819 // (the overflow address should be kept 8-byte aligned)
19820 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19821 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19822 .addReg(OverflowDestReg)
19823 .addImm(ArgSizeA8);
19825 // Store the new overflow address.
19826 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19831 .addOperand(Segment)
19832 .addReg(NextAddrReg)
19833 .setMemRefs(MMOBegin, MMOEnd);
19835 // If we branched, emit the PHI to the front of endMBB.
19837 BuildMI(*endMBB, endMBB->begin(), DL,
19838 TII->get(X86::PHI), DestReg)
19839 .addReg(OffsetDestReg).addMBB(offsetMBB)
19840 .addReg(OverflowDestReg).addMBB(overflowMBB);
19843 // Erase the pseudo instruction
19844 MI->eraseFromParent();
19849 MachineBasicBlock *
19850 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19852 MachineBasicBlock *MBB) const {
19853 // Emit code to save XMM registers to the stack. The ABI says that the
19854 // number of registers to save is given in %al, so it's theoretically
19855 // possible to do an indirect jump trick to avoid saving all of them,
19856 // however this code takes a simpler approach and just executes all
19857 // of the stores if %al is non-zero. It's less code, and it's probably
19858 // easier on the hardware branch predictor, and stores aren't all that
19859 // expensive anyway.
19861 // Create the new basic blocks. One block contains all the XMM stores,
19862 // and one block is the final destination regardless of whether any
19863 // stores were performed.
19864 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19865 MachineFunction *F = MBB->getParent();
19866 MachineFunction::iterator MBBIter = MBB;
19868 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19869 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19870 F->insert(MBBIter, XMMSaveMBB);
19871 F->insert(MBBIter, EndMBB);
19873 // Transfer the remainder of MBB and its successor edges to EndMBB.
19874 EndMBB->splice(EndMBB->begin(), MBB,
19875 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19876 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19878 // The original block will now fall through to the XMM save block.
19879 MBB->addSuccessor(XMMSaveMBB);
19880 // The XMMSaveMBB will fall through to the end block.
19881 XMMSaveMBB->addSuccessor(EndMBB);
19883 // Now add the instructions.
19884 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19885 DebugLoc DL = MI->getDebugLoc();
19887 unsigned CountReg = MI->getOperand(0).getReg();
19888 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19889 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19891 if (!Subtarget->isTargetWin64()) {
19892 // If %al is 0, branch around the XMM save block.
19893 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19894 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19895 MBB->addSuccessor(EndMBB);
19898 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19899 // that was just emitted, but clearly shouldn't be "saved".
19900 assert((MI->getNumOperands() <= 3 ||
19901 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19902 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19903 && "Expected last argument to be EFLAGS");
19904 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19905 // In the XMM save block, save all the XMM argument registers.
19906 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19907 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19908 MachineMemOperand *MMO = F->getMachineMemOperand(
19909 MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
19910 MachineMemOperand::MOStore,
19911 /*Size=*/16, /*Align=*/16);
19912 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19913 .addFrameIndex(RegSaveFrameIndex)
19914 .addImm(/*Scale=*/1)
19915 .addReg(/*IndexReg=*/0)
19916 .addImm(/*Disp=*/Offset)
19917 .addReg(/*Segment=*/0)
19918 .addReg(MI->getOperand(i).getReg())
19919 .addMemOperand(MMO);
19922 MI->eraseFromParent(); // The pseudo instruction is gone now.
19927 // The EFLAGS operand of SelectItr might be missing a kill marker
19928 // because there were multiple uses of EFLAGS, and ISel didn't know
19929 // which to mark. Figure out whether SelectItr should have had a
19930 // kill marker, and set it if it should. Returns the correct kill
19932 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19933 MachineBasicBlock* BB,
19934 const TargetRegisterInfo* TRI) {
19935 // Scan forward through BB for a use/def of EFLAGS.
19936 MachineBasicBlock::iterator miI(std::next(SelectItr));
19937 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19938 const MachineInstr& mi = *miI;
19939 if (mi.readsRegister(X86::EFLAGS))
19941 if (mi.definesRegister(X86::EFLAGS))
19942 break; // Should have kill-flag - update below.
19945 // If we hit the end of the block, check whether EFLAGS is live into a
19947 if (miI == BB->end()) {
19948 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19949 sEnd = BB->succ_end();
19950 sItr != sEnd; ++sItr) {
19951 MachineBasicBlock* succ = *sItr;
19952 if (succ->isLiveIn(X86::EFLAGS))
19957 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19958 // out. SelectMI should have a kill flag on EFLAGS.
19959 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19963 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
19964 // together with other CMOV pseudo-opcodes into a single basic-block with
19965 // conditional jump around it.
19966 static bool isCMOVPseudo(MachineInstr *MI) {
19967 switch (MI->getOpcode()) {
19968 case X86::CMOV_FR32:
19969 case X86::CMOV_FR64:
19970 case X86::CMOV_GR8:
19971 case X86::CMOV_GR16:
19972 case X86::CMOV_GR32:
19973 case X86::CMOV_RFP32:
19974 case X86::CMOV_RFP64:
19975 case X86::CMOV_RFP80:
19976 case X86::CMOV_V2F64:
19977 case X86::CMOV_V2I64:
19978 case X86::CMOV_V4F32:
19979 case X86::CMOV_V4F64:
19980 case X86::CMOV_V4I64:
19981 case X86::CMOV_V16F32:
19982 case X86::CMOV_V8F32:
19983 case X86::CMOV_V8F64:
19984 case X86::CMOV_V8I64:
19985 case X86::CMOV_V8I1:
19986 case X86::CMOV_V16I1:
19987 case X86::CMOV_V32I1:
19988 case X86::CMOV_V64I1:
19996 MachineBasicBlock *
19997 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19998 MachineBasicBlock *BB) const {
19999 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20000 DebugLoc DL = MI->getDebugLoc();
20002 // To "insert" a SELECT_CC instruction, we actually have to insert the
20003 // diamond control-flow pattern. The incoming instruction knows the
20004 // destination vreg to set, the condition code register to branch on, the
20005 // true/false values to select between, and a branch opcode to use.
20006 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20007 MachineFunction::iterator It = BB;
20013 // cmpTY ccX, r1, r2
20015 // fallthrough --> copy0MBB
20016 MachineBasicBlock *thisMBB = BB;
20017 MachineFunction *F = BB->getParent();
20019 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20020 // as described above, by inserting a BB, and then making a PHI at the join
20021 // point to select the true and false operands of the CMOV in the PHI.
20023 // The code also handles two different cases of multiple CMOV opcodes
20027 // In this case, there are multiple CMOVs in a row, all which are based on
20028 // the same condition setting (or the exact opposite condition setting).
20029 // In this case we can lower all the CMOVs using a single inserted BB, and
20030 // then make a number of PHIs at the join point to model the CMOVs. The only
20031 // trickiness here, is that in a case like:
20033 // t2 = CMOV cond1 t1, f1
20034 // t3 = CMOV cond1 t2, f2
20036 // when rewriting this into PHIs, we have to perform some renaming on the
20037 // temps since you cannot have a PHI operand refer to a PHI result earlier
20038 // in the same block. The "simple" but wrong lowering would be:
20040 // t2 = PHI t1(BB1), f1(BB2)
20041 // t3 = PHI t2(BB1), f2(BB2)
20043 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20044 // renaming is to note that on the path through BB1, t2 is really just a
20045 // copy of t1, and do that renaming, properly generating:
20047 // t2 = PHI t1(BB1), f1(BB2)
20048 // t3 = PHI t1(BB1), f2(BB2)
20050 // Case 2, we lower cascaded CMOVs such as
20052 // (CMOV (CMOV F, T, cc1), T, cc2)
20054 // to two successives branches. For that, we look for another CMOV as the
20055 // following instruction.
20057 // Without this, we would add a PHI between the two jumps, which ends up
20058 // creating a few copies all around. For instance, for
20060 // (sitofp (zext (fcmp une)))
20062 // we would generate:
20064 // ucomiss %xmm1, %xmm0
20065 // movss <1.0f>, %xmm0
20066 // movaps %xmm0, %xmm1
20068 // xorps %xmm1, %xmm1
20071 // movaps %xmm1, %xmm0
20075 // because this custom-inserter would have generated:
20087 // A: X = ...; Y = ...
20089 // C: Z = PHI [X, A], [Y, B]
20091 // E: PHI [X, C], [Z, D]
20093 // If we lower both CMOVs in a single step, we can instead generate:
20105 // A: X = ...; Y = ...
20107 // E: PHI [X, A], [X, C], [Y, D]
20109 // Which, in our sitofp/fcmp example, gives us something like:
20111 // ucomiss %xmm1, %xmm0
20112 // movss <1.0f>, %xmm0
20115 // xorps %xmm0, %xmm0
20119 MachineInstr *CascadedCMOV = nullptr;
20120 MachineInstr *LastCMOV = MI;
20121 X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20122 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20123 MachineBasicBlock::iterator NextMIIt =
20124 std::next(MachineBasicBlock::iterator(MI));
20126 // Check for case 1, where there are multiple CMOVs with the same condition
20127 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
20128 // number of jumps the most.
20130 if (isCMOVPseudo(MI)) {
20131 // See if we have a string of CMOVS with the same condition.
20132 while (NextMIIt != BB->end() &&
20133 isCMOVPseudo(NextMIIt) &&
20134 (NextMIIt->getOperand(3).getImm() == CC ||
20135 NextMIIt->getOperand(3).getImm() == OppCC)) {
20136 LastCMOV = &*NextMIIt;
20141 // This checks for case 2, but only do this if we didn't already find
20142 // case 1, as indicated by LastCMOV == MI.
20143 if (LastCMOV == MI &&
20144 NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20145 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20146 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20147 CascadedCMOV = &*NextMIIt;
20150 MachineBasicBlock *jcc1MBB = nullptr;
20152 // If we have a cascaded CMOV, we lower it to two successive branches to
20153 // the same block. EFLAGS is used by both, so mark it as live in the second.
20154 if (CascadedCMOV) {
20155 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20156 F->insert(It, jcc1MBB);
20157 jcc1MBB->addLiveIn(X86::EFLAGS);
20160 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20161 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20162 F->insert(It, copy0MBB);
20163 F->insert(It, sinkMBB);
20165 // If the EFLAGS register isn't dead in the terminator, then claim that it's
20166 // live into the sink and copy blocks.
20167 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20169 MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20170 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20171 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20172 copy0MBB->addLiveIn(X86::EFLAGS);
20173 sinkMBB->addLiveIn(X86::EFLAGS);
20176 // Transfer the remainder of BB and its successor edges to sinkMBB.
20177 sinkMBB->splice(sinkMBB->begin(), BB,
20178 std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20179 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20181 // Add the true and fallthrough blocks as its successors.
20182 if (CascadedCMOV) {
20183 // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20184 BB->addSuccessor(jcc1MBB);
20186 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20187 // jump to the sinkMBB.
20188 jcc1MBB->addSuccessor(copy0MBB);
20189 jcc1MBB->addSuccessor(sinkMBB);
20191 BB->addSuccessor(copy0MBB);
20194 // The true block target of the first (or only) branch is always sinkMBB.
20195 BB->addSuccessor(sinkMBB);
20197 // Create the conditional branch instruction.
20198 unsigned Opc = X86::GetCondBranchFromCond(CC);
20199 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20201 if (CascadedCMOV) {
20202 unsigned Opc2 = X86::GetCondBranchFromCond(
20203 (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20204 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20208 // %FalseValue = ...
20209 // # fallthrough to sinkMBB
20210 copy0MBB->addSuccessor(sinkMBB);
20213 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20215 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20216 MachineBasicBlock::iterator MIItEnd =
20217 std::next(MachineBasicBlock::iterator(LastCMOV));
20218 MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20219 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20220 MachineInstrBuilder MIB;
20222 // As we are creating the PHIs, we have to be careful if there is more than
20223 // one. Later CMOVs may reference the results of earlier CMOVs, but later
20224 // PHIs have to reference the individual true/false inputs from earlier PHIs.
20225 // That also means that PHI construction must work forward from earlier to
20226 // later, and that the code must maintain a mapping from earlier PHI's
20227 // destination registers, and the registers that went into the PHI.
20229 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20230 unsigned DestReg = MIIt->getOperand(0).getReg();
20231 unsigned Op1Reg = MIIt->getOperand(1).getReg();
20232 unsigned Op2Reg = MIIt->getOperand(2).getReg();
20234 // If this CMOV we are generating is the opposite condition from
20235 // the jump we generated, then we have to swap the operands for the
20236 // PHI that is going to be generated.
20237 if (MIIt->getOperand(3).getImm() == OppCC)
20238 std::swap(Op1Reg, Op2Reg);
20240 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20241 Op1Reg = RegRewriteTable[Op1Reg].first;
20243 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20244 Op2Reg = RegRewriteTable[Op2Reg].second;
20246 MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20247 TII->get(X86::PHI), DestReg)
20248 .addReg(Op1Reg).addMBB(copy0MBB)
20249 .addReg(Op2Reg).addMBB(thisMBB);
20251 // Add this PHI to the rewrite table.
20252 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20255 // If we have a cascaded CMOV, the second Jcc provides the same incoming
20256 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20257 if (CascadedCMOV) {
20258 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20259 // Copy the PHI result to the register defined by the second CMOV.
20260 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20261 DL, TII->get(TargetOpcode::COPY),
20262 CascadedCMOV->getOperand(0).getReg())
20263 .addReg(MI->getOperand(0).getReg());
20264 CascadedCMOV->eraseFromParent();
20267 // Now remove the CMOV(s).
20268 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20269 (MIIt++)->eraseFromParent();
20274 MachineBasicBlock *
20275 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20276 MachineBasicBlock *BB) const {
20277 // Combine the following atomic floating-point modification pattern:
20278 // a.store(reg OP a.load(acquire), release)
20279 // Transform them into:
20280 // OPss (%gpr), %xmm
20281 // movss %xmm, (%gpr)
20282 // Or sd equivalent for 64-bit operations.
20284 switch (MI->getOpcode()) {
20285 default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20286 case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20287 case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20289 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20290 DebugLoc DL = MI->getDebugLoc();
20291 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20292 unsigned MSrc = MI->getOperand(0).getReg();
20293 unsigned VSrc = MI->getOperand(5).getReg();
20294 MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20295 .addReg(/*Base=*/MSrc)
20296 .addImm(/*Scale=*/1)
20297 .addReg(/*Index=*/0)
20300 MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20301 MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20303 .addReg(/*Base=*/MSrc)
20304 .addImm(/*Scale=*/1)
20305 .addReg(/*Index=*/0)
20306 .addImm(/*Disp=*/0)
20307 .addReg(/*Segment=*/0);
20308 MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20309 MI->eraseFromParent(); // The pseudo instruction is gone now.
20313 MachineBasicBlock *
20314 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20315 MachineBasicBlock *BB) const {
20316 MachineFunction *MF = BB->getParent();
20317 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20318 DebugLoc DL = MI->getDebugLoc();
20319 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20321 assert(MF->shouldSplitStack());
20323 const bool Is64Bit = Subtarget->is64Bit();
20324 const bool IsLP64 = Subtarget->isTarget64BitLP64();
20326 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20327 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20330 // ... [Till the alloca]
20331 // If stacklet is not large enough, jump to mallocMBB
20334 // Allocate by subtracting from RSP
20335 // Jump to continueMBB
20338 // Allocate by call to runtime
20342 // [rest of original BB]
20345 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20346 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20347 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20349 MachineRegisterInfo &MRI = MF->getRegInfo();
20350 const TargetRegisterClass *AddrRegClass =
20351 getRegClassFor(getPointerTy(MF->getDataLayout()));
20353 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20354 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20355 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20356 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20357 sizeVReg = MI->getOperand(1).getReg(),
20358 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20360 MachineFunction::iterator MBBIter = BB;
20363 MF->insert(MBBIter, bumpMBB);
20364 MF->insert(MBBIter, mallocMBB);
20365 MF->insert(MBBIter, continueMBB);
20367 continueMBB->splice(continueMBB->begin(), BB,
20368 std::next(MachineBasicBlock::iterator(MI)), BB->end());
20369 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20371 // Add code to the main basic block to check if the stack limit has been hit,
20372 // and if so, jump to mallocMBB otherwise to bumpMBB.
20373 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20374 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20375 .addReg(tmpSPVReg).addReg(sizeVReg);
20376 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20377 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20378 .addReg(SPLimitVReg);
20379 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20381 // bumpMBB simply decreases the stack pointer, since we know the current
20382 // stacklet has enough space.
20383 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20384 .addReg(SPLimitVReg);
20385 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20386 .addReg(SPLimitVReg);
20387 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20389 // Calls into a routine in libgcc to allocate more space from the heap.
20390 const uint32_t *RegMask =
20391 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20393 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20395 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20396 .addExternalSymbol("__morestack_allocate_stack_space")
20397 .addRegMask(RegMask)
20398 .addReg(X86::RDI, RegState::Implicit)
20399 .addReg(X86::RAX, RegState::ImplicitDefine);
20400 } else if (Is64Bit) {
20401 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20403 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20404 .addExternalSymbol("__morestack_allocate_stack_space")
20405 .addRegMask(RegMask)
20406 .addReg(X86::EDI, RegState::Implicit)
20407 .addReg(X86::EAX, RegState::ImplicitDefine);
20409 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20411 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20412 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20413 .addExternalSymbol("__morestack_allocate_stack_space")
20414 .addRegMask(RegMask)
20415 .addReg(X86::EAX, RegState::ImplicitDefine);
20419 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20422 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20423 .addReg(IsLP64 ? X86::RAX : X86::EAX);
20424 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20426 // Set up the CFG correctly.
20427 BB->addSuccessor(bumpMBB);
20428 BB->addSuccessor(mallocMBB);
20429 mallocMBB->addSuccessor(continueMBB);
20430 bumpMBB->addSuccessor(continueMBB);
20432 // Take care of the PHI nodes.
20433 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20434 MI->getOperand(0).getReg())
20435 .addReg(mallocPtrVReg).addMBB(mallocMBB)
20436 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20438 // Delete the original pseudo instruction.
20439 MI->eraseFromParent();
20442 return continueMBB;
20445 MachineBasicBlock *
20446 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20447 MachineBasicBlock *BB) const {
20448 DebugLoc DL = MI->getDebugLoc();
20450 assert(!Subtarget->isTargetMachO());
20452 Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20455 MI->eraseFromParent(); // The pseudo instruction is gone now.
20459 MachineBasicBlock *
20460 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20461 MachineBasicBlock *BB) const {
20462 // This is pretty easy. We're taking the value that we received from
20463 // our load from the relocation, sticking it in either RDI (x86-64)
20464 // or EAX and doing an indirect call. The return value will then
20465 // be in the normal return register.
20466 MachineFunction *F = BB->getParent();
20467 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20468 DebugLoc DL = MI->getDebugLoc();
20470 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20471 assert(MI->getOperand(3).isGlobal() && "This should be a global");
20473 // Get a register mask for the lowered call.
20474 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20475 // proper register mask.
20476 const uint32_t *RegMask =
20477 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20478 if (Subtarget->is64Bit()) {
20479 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20480 TII->get(X86::MOV64rm), X86::RDI)
20482 .addImm(0).addReg(0)
20483 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20484 MI->getOperand(3).getTargetFlags())
20486 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20487 addDirectMem(MIB, X86::RDI);
20488 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20489 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20490 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20491 TII->get(X86::MOV32rm), X86::EAX)
20493 .addImm(0).addReg(0)
20494 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20495 MI->getOperand(3).getTargetFlags())
20497 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20498 addDirectMem(MIB, X86::EAX);
20499 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20501 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20502 TII->get(X86::MOV32rm), X86::EAX)
20503 .addReg(TII->getGlobalBaseReg(F))
20504 .addImm(0).addReg(0)
20505 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20506 MI->getOperand(3).getTargetFlags())
20508 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20509 addDirectMem(MIB, X86::EAX);
20510 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20513 MI->eraseFromParent(); // The pseudo instruction is gone now.
20517 MachineBasicBlock *
20518 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20519 MachineBasicBlock *MBB) const {
20520 DebugLoc DL = MI->getDebugLoc();
20521 MachineFunction *MF = MBB->getParent();
20522 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20523 MachineRegisterInfo &MRI = MF->getRegInfo();
20525 const BasicBlock *BB = MBB->getBasicBlock();
20526 MachineFunction::iterator I = MBB;
20529 // Memory Reference
20530 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20531 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20534 unsigned MemOpndSlot = 0;
20536 unsigned CurOp = 0;
20538 DstReg = MI->getOperand(CurOp++).getReg();
20539 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20540 assert(RC->hasType(MVT::i32) && "Invalid destination!");
20541 unsigned mainDstReg = MRI.createVirtualRegister(RC);
20542 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20544 MemOpndSlot = CurOp;
20546 MVT PVT = getPointerTy(MF->getDataLayout());
20547 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20548 "Invalid Pointer Size!");
20550 // For v = setjmp(buf), we generate
20553 // buf[LabelOffset] = restoreMBB
20554 // SjLjSetup restoreMBB
20560 // v = phi(main, restore)
20563 // if base pointer being used, load it from frame
20566 MachineBasicBlock *thisMBB = MBB;
20567 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20568 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20569 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20570 MF->insert(I, mainMBB);
20571 MF->insert(I, sinkMBB);
20572 MF->push_back(restoreMBB);
20574 MachineInstrBuilder MIB;
20576 // Transfer the remainder of BB and its successor edges to sinkMBB.
20577 sinkMBB->splice(sinkMBB->begin(), MBB,
20578 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20579 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20582 unsigned PtrStoreOpc = 0;
20583 unsigned LabelReg = 0;
20584 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20585 Reloc::Model RM = MF->getTarget().getRelocationModel();
20586 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20587 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20589 // Prepare IP either in reg or imm.
20590 if (!UseImmLabel) {
20591 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20592 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20593 LabelReg = MRI.createVirtualRegister(PtrRC);
20594 if (Subtarget->is64Bit()) {
20595 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20599 .addMBB(restoreMBB)
20602 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20603 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20604 .addReg(XII->getGlobalBaseReg(MF))
20607 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20611 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20613 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20614 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20615 if (i == X86::AddrDisp)
20616 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20618 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20621 MIB.addReg(LabelReg);
20623 MIB.addMBB(restoreMBB);
20624 MIB.setMemRefs(MMOBegin, MMOEnd);
20626 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20627 .addMBB(restoreMBB);
20629 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20630 MIB.addRegMask(RegInfo->getNoPreservedMask());
20631 thisMBB->addSuccessor(mainMBB);
20632 thisMBB->addSuccessor(restoreMBB);
20636 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20637 mainMBB->addSuccessor(sinkMBB);
20640 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20641 TII->get(X86::PHI), DstReg)
20642 .addReg(mainDstReg).addMBB(mainMBB)
20643 .addReg(restoreDstReg).addMBB(restoreMBB);
20646 if (RegInfo->hasBasePointer(*MF)) {
20647 const bool Uses64BitFramePtr =
20648 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20649 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20650 X86FI->setRestoreBasePointer(MF);
20651 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20652 unsigned BasePtr = RegInfo->getBaseRegister();
20653 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20654 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20655 FramePtr, true, X86FI->getRestoreBasePointerOffset())
20656 .setMIFlag(MachineInstr::FrameSetup);
20658 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20659 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20660 restoreMBB->addSuccessor(sinkMBB);
20662 MI->eraseFromParent();
20666 MachineBasicBlock *
20667 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20668 MachineBasicBlock *MBB) const {
20669 DebugLoc DL = MI->getDebugLoc();
20670 MachineFunction *MF = MBB->getParent();
20671 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20672 MachineRegisterInfo &MRI = MF->getRegInfo();
20674 // Memory Reference
20675 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20676 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20678 MVT PVT = getPointerTy(MF->getDataLayout());
20679 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20680 "Invalid Pointer Size!");
20682 const TargetRegisterClass *RC =
20683 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20684 unsigned Tmp = MRI.createVirtualRegister(RC);
20685 // Since FP is only updated here but NOT referenced, it's treated as GPR.
20686 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20687 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20688 unsigned SP = RegInfo->getStackRegister();
20690 MachineInstrBuilder MIB;
20692 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20693 const int64_t SPOffset = 2 * PVT.getStoreSize();
20695 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20696 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20699 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20700 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20701 MIB.addOperand(MI->getOperand(i));
20702 MIB.setMemRefs(MMOBegin, MMOEnd);
20704 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20705 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20706 if (i == X86::AddrDisp)
20707 MIB.addDisp(MI->getOperand(i), LabelOffset);
20709 MIB.addOperand(MI->getOperand(i));
20711 MIB.setMemRefs(MMOBegin, MMOEnd);
20713 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20714 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20715 if (i == X86::AddrDisp)
20716 MIB.addDisp(MI->getOperand(i), SPOffset);
20718 MIB.addOperand(MI->getOperand(i));
20720 MIB.setMemRefs(MMOBegin, MMOEnd);
20722 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20724 MI->eraseFromParent();
20728 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20729 // accumulator loops. Writing back to the accumulator allows the coalescer
20730 // to remove extra copies in the loop.
20731 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
20732 MachineBasicBlock *
20733 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20734 MachineBasicBlock *MBB) const {
20735 MachineOperand &AddendOp = MI->getOperand(3);
20737 // Bail out early if the addend isn't a register - we can't switch these.
20738 if (!AddendOp.isReg())
20741 MachineFunction &MF = *MBB->getParent();
20742 MachineRegisterInfo &MRI = MF.getRegInfo();
20744 // Check whether the addend is defined by a PHI:
20745 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20746 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20747 if (!AddendDef.isPHI())
20750 // Look for the following pattern:
20752 // %addend = phi [%entry, 0], [%loop, %result]
20754 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20758 // %addend = phi [%entry, 0], [%loop, %result]
20760 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20762 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20763 assert(AddendDef.getOperand(i).isReg());
20764 MachineOperand PHISrcOp = AddendDef.getOperand(i);
20765 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20766 if (&PHISrcInst == MI) {
20767 // Found a matching instruction.
20768 unsigned NewFMAOpc = 0;
20769 switch (MI->getOpcode()) {
20770 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20771 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20772 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20773 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20774 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20775 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20776 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20777 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20778 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20779 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20780 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20781 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20782 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20783 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20784 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20785 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20786 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20787 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20788 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20789 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20791 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20792 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20793 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20794 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20795 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20796 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20797 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20798 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20799 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20800 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20801 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20802 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20803 default: llvm_unreachable("Unrecognized FMA variant.");
20806 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20807 MachineInstrBuilder MIB =
20808 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20809 .addOperand(MI->getOperand(0))
20810 .addOperand(MI->getOperand(3))
20811 .addOperand(MI->getOperand(2))
20812 .addOperand(MI->getOperand(1));
20813 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20814 MI->eraseFromParent();
20821 MachineBasicBlock *
20822 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20823 MachineBasicBlock *BB) const {
20824 switch (MI->getOpcode()) {
20825 default: llvm_unreachable("Unexpected instr type to insert");
20826 case X86::TAILJMPd64:
20827 case X86::TAILJMPr64:
20828 case X86::TAILJMPm64:
20829 case X86::TAILJMPd64_REX:
20830 case X86::TAILJMPr64_REX:
20831 case X86::TAILJMPm64_REX:
20832 llvm_unreachable("TAILJMP64 would not be touched here.");
20833 case X86::TCRETURNdi64:
20834 case X86::TCRETURNri64:
20835 case X86::TCRETURNmi64:
20837 case X86::WIN_ALLOCA:
20838 return EmitLoweredWinAlloca(MI, BB);
20839 case X86::SEG_ALLOCA_32:
20840 case X86::SEG_ALLOCA_64:
20841 return EmitLoweredSegAlloca(MI, BB);
20842 case X86::TLSCall_32:
20843 case X86::TLSCall_64:
20844 return EmitLoweredTLSCall(MI, BB);
20845 case X86::CMOV_FR32:
20846 case X86::CMOV_FR64:
20847 case X86::CMOV_GR8:
20848 case X86::CMOV_GR16:
20849 case X86::CMOV_GR32:
20850 case X86::CMOV_RFP32:
20851 case X86::CMOV_RFP64:
20852 case X86::CMOV_RFP80:
20853 case X86::CMOV_V2F64:
20854 case X86::CMOV_V2I64:
20855 case X86::CMOV_V4F32:
20856 case X86::CMOV_V4F64:
20857 case X86::CMOV_V4I64:
20858 case X86::CMOV_V16F32:
20859 case X86::CMOV_V8F32:
20860 case X86::CMOV_V8F64:
20861 case X86::CMOV_V8I64:
20862 case X86::CMOV_V8I1:
20863 case X86::CMOV_V16I1:
20864 case X86::CMOV_V32I1:
20865 case X86::CMOV_V64I1:
20866 return EmitLoweredSelect(MI, BB);
20868 case X86::RELEASE_FADD32mr:
20869 case X86::RELEASE_FADD64mr:
20870 return EmitLoweredAtomicFP(MI, BB);
20872 case X86::FP32_TO_INT16_IN_MEM:
20873 case X86::FP32_TO_INT32_IN_MEM:
20874 case X86::FP32_TO_INT64_IN_MEM:
20875 case X86::FP64_TO_INT16_IN_MEM:
20876 case X86::FP64_TO_INT32_IN_MEM:
20877 case X86::FP64_TO_INT64_IN_MEM:
20878 case X86::FP80_TO_INT16_IN_MEM:
20879 case X86::FP80_TO_INT32_IN_MEM:
20880 case X86::FP80_TO_INT64_IN_MEM: {
20881 MachineFunction *F = BB->getParent();
20882 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20883 DebugLoc DL = MI->getDebugLoc();
20885 // Change the floating point control register to use "round towards zero"
20886 // mode when truncating to an integer value.
20887 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20888 addFrameReference(BuildMI(*BB, MI, DL,
20889 TII->get(X86::FNSTCW16m)), CWFrameIdx);
20891 // Load the old value of the high byte of the control word...
20893 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20894 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20897 // Set the high part to be round to zero...
20898 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20901 // Reload the modified control word now...
20902 addFrameReference(BuildMI(*BB, MI, DL,
20903 TII->get(X86::FLDCW16m)), CWFrameIdx);
20905 // Restore the memory image of control word to original value
20906 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20909 // Get the X86 opcode to use.
20911 switch (MI->getOpcode()) {
20912 default: llvm_unreachable("illegal opcode!");
20913 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20914 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20915 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20916 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20917 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20918 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20919 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20920 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20921 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20925 MachineOperand &Op = MI->getOperand(0);
20927 AM.BaseType = X86AddressMode::RegBase;
20928 AM.Base.Reg = Op.getReg();
20930 AM.BaseType = X86AddressMode::FrameIndexBase;
20931 AM.Base.FrameIndex = Op.getIndex();
20933 Op = MI->getOperand(1);
20935 AM.Scale = Op.getImm();
20936 Op = MI->getOperand(2);
20938 AM.IndexReg = Op.getImm();
20939 Op = MI->getOperand(3);
20940 if (Op.isGlobal()) {
20941 AM.GV = Op.getGlobal();
20943 AM.Disp = Op.getImm();
20945 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20946 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20948 // Reload the original control word now.
20949 addFrameReference(BuildMI(*BB, MI, DL,
20950 TII->get(X86::FLDCW16m)), CWFrameIdx);
20952 MI->eraseFromParent(); // The pseudo instruction is gone now.
20955 // String/text processing lowering.
20956 case X86::PCMPISTRM128REG:
20957 case X86::VPCMPISTRM128REG:
20958 case X86::PCMPISTRM128MEM:
20959 case X86::VPCMPISTRM128MEM:
20960 case X86::PCMPESTRM128REG:
20961 case X86::VPCMPESTRM128REG:
20962 case X86::PCMPESTRM128MEM:
20963 case X86::VPCMPESTRM128MEM:
20964 assert(Subtarget->hasSSE42() &&
20965 "Target must have SSE4.2 or AVX features enabled");
20966 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20968 // String/text processing lowering.
20969 case X86::PCMPISTRIREG:
20970 case X86::VPCMPISTRIREG:
20971 case X86::PCMPISTRIMEM:
20972 case X86::VPCMPISTRIMEM:
20973 case X86::PCMPESTRIREG:
20974 case X86::VPCMPESTRIREG:
20975 case X86::PCMPESTRIMEM:
20976 case X86::VPCMPESTRIMEM:
20977 assert(Subtarget->hasSSE42() &&
20978 "Target must have SSE4.2 or AVX features enabled");
20979 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20981 // Thread synchronization.
20983 return EmitMonitor(MI, BB, Subtarget);
20987 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20989 case X86::VASTART_SAVE_XMM_REGS:
20990 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20992 case X86::VAARG_64:
20993 return EmitVAARG64WithCustomInserter(MI, BB);
20995 case X86::EH_SjLj_SetJmp32:
20996 case X86::EH_SjLj_SetJmp64:
20997 return emitEHSjLjSetJmp(MI, BB);
20999 case X86::EH_SjLj_LongJmp32:
21000 case X86::EH_SjLj_LongJmp64:
21001 return emitEHSjLjLongJmp(MI, BB);
21003 case TargetOpcode::STATEPOINT:
21004 // As an implementation detail, STATEPOINT shares the STACKMAP format at
21005 // this point in the process. We diverge later.
21006 return emitPatchPoint(MI, BB);
21008 case TargetOpcode::STACKMAP:
21009 case TargetOpcode::PATCHPOINT:
21010 return emitPatchPoint(MI, BB);
21012 case X86::VFMADDPDr213r:
21013 case X86::VFMADDPSr213r:
21014 case X86::VFMADDSDr213r:
21015 case X86::VFMADDSSr213r:
21016 case X86::VFMSUBPDr213r:
21017 case X86::VFMSUBPSr213r:
21018 case X86::VFMSUBSDr213r:
21019 case X86::VFMSUBSSr213r:
21020 case X86::VFNMADDPDr213r:
21021 case X86::VFNMADDPSr213r:
21022 case X86::VFNMADDSDr213r:
21023 case X86::VFNMADDSSr213r:
21024 case X86::VFNMSUBPDr213r:
21025 case X86::VFNMSUBPSr213r:
21026 case X86::VFNMSUBSDr213r:
21027 case X86::VFNMSUBSSr213r:
21028 case X86::VFMADDSUBPDr213r:
21029 case X86::VFMADDSUBPSr213r:
21030 case X86::VFMSUBADDPDr213r:
21031 case X86::VFMSUBADDPSr213r:
21032 case X86::VFMADDPDr213rY:
21033 case X86::VFMADDPSr213rY:
21034 case X86::VFMSUBPDr213rY:
21035 case X86::VFMSUBPSr213rY:
21036 case X86::VFNMADDPDr213rY:
21037 case X86::VFNMADDPSr213rY:
21038 case X86::VFNMSUBPDr213rY:
21039 case X86::VFNMSUBPSr213rY:
21040 case X86::VFMADDSUBPDr213rY:
21041 case X86::VFMADDSUBPSr213rY:
21042 case X86::VFMSUBADDPDr213rY:
21043 case X86::VFMSUBADDPSr213rY:
21044 return emitFMA3Instr(MI, BB);
21048 //===----------------------------------------------------------------------===//
21049 // X86 Optimization Hooks
21050 //===----------------------------------------------------------------------===//
21052 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21055 const SelectionDAG &DAG,
21056 unsigned Depth) const {
21057 unsigned BitWidth = KnownZero.getBitWidth();
21058 unsigned Opc = Op.getOpcode();
21059 assert((Opc >= ISD::BUILTIN_OP_END ||
21060 Opc == ISD::INTRINSIC_WO_CHAIN ||
21061 Opc == ISD::INTRINSIC_W_CHAIN ||
21062 Opc == ISD::INTRINSIC_VOID) &&
21063 "Should use MaskedValueIsZero if you don't know whether Op"
21064 " is a target node!");
21066 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
21080 // These nodes' second result is a boolean.
21081 if (Op.getResNo() == 0)
21084 case X86ISD::SETCC:
21085 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21087 case ISD::INTRINSIC_WO_CHAIN: {
21088 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21089 unsigned NumLoBits = 0;
21092 case Intrinsic::x86_sse_movmsk_ps:
21093 case Intrinsic::x86_avx_movmsk_ps_256:
21094 case Intrinsic::x86_sse2_movmsk_pd:
21095 case Intrinsic::x86_avx_movmsk_pd_256:
21096 case Intrinsic::x86_mmx_pmovmskb:
21097 case Intrinsic::x86_sse2_pmovmskb_128:
21098 case Intrinsic::x86_avx2_pmovmskb: {
21099 // High bits of movmskp{s|d}, pmovmskb are known zero.
21101 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
21102 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
21103 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
21104 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
21105 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
21106 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
21107 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
21108 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
21110 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21119 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21121 const SelectionDAG &,
21122 unsigned Depth) const {
21123 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21124 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21125 return Op.getValueType().getScalarType().getSizeInBits();
21131 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21132 /// node is a GlobalAddress + offset.
21133 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21134 const GlobalValue* &GA,
21135 int64_t &Offset) const {
21136 if (N->getOpcode() == X86ISD::Wrapper) {
21137 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21138 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21139 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21143 return TargetLowering::isGAPlusOffset(N, GA, Offset);
21146 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21147 /// same as extracting the high 128-bit part of 256-bit vector and then
21148 /// inserting the result into the low part of a new 256-bit vector
21149 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21150 EVT VT = SVOp->getValueType(0);
21151 unsigned NumElems = VT.getVectorNumElements();
21153 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21154 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21155 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21156 SVOp->getMaskElt(j) >= 0)
21162 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21163 /// same as extracting the low 128-bit part of 256-bit vector and then
21164 /// inserting the result into the high part of a new 256-bit vector
21165 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21166 EVT VT = SVOp->getValueType(0);
21167 unsigned NumElems = VT.getVectorNumElements();
21169 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21170 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21171 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21172 SVOp->getMaskElt(j) >= 0)
21178 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21179 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21180 TargetLowering::DAGCombinerInfo &DCI,
21181 const X86Subtarget* Subtarget) {
21183 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21184 SDValue V1 = SVOp->getOperand(0);
21185 SDValue V2 = SVOp->getOperand(1);
21186 EVT VT = SVOp->getValueType(0);
21187 unsigned NumElems = VT.getVectorNumElements();
21189 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21190 V2.getOpcode() == ISD::CONCAT_VECTORS) {
21194 // V UNDEF BUILD_VECTOR UNDEF
21196 // CONCAT_VECTOR CONCAT_VECTOR
21199 // RESULT: V + zero extended
21201 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21202 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21203 V1.getOperand(1).getOpcode() != ISD::UNDEF)
21206 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21209 // To match the shuffle mask, the first half of the mask should
21210 // be exactly the first vector, and all the rest a splat with the
21211 // first element of the second one.
21212 for (unsigned i = 0; i != NumElems/2; ++i)
21213 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21214 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21217 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21218 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21219 if (Ld->hasNUsesOfValue(1, 0)) {
21220 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21221 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21223 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21225 Ld->getPointerInfo(),
21226 Ld->getAlignment(),
21227 false/*isVolatile*/, true/*ReadMem*/,
21228 false/*WriteMem*/);
21230 // Make sure the newly-created LOAD is in the same position as Ld in
21231 // terms of dependency. We create a TokenFactor for Ld and ResNode,
21232 // and update uses of Ld's output chain to use the TokenFactor.
21233 if (Ld->hasAnyUseOfValue(1)) {
21234 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21235 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21236 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21237 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21238 SDValue(ResNode.getNode(), 1));
21241 return DAG.getBitcast(VT, ResNode);
21245 // Emit a zeroed vector and insert the desired subvector on its
21247 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21248 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21249 return DCI.CombineTo(N, InsV);
21252 //===--------------------------------------------------------------------===//
21253 // Combine some shuffles into subvector extracts and inserts:
21256 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21257 if (isShuffleHigh128VectorInsertLow(SVOp)) {
21258 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21259 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21260 return DCI.CombineTo(N, InsV);
21263 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21264 if (isShuffleLow128VectorInsertHigh(SVOp)) {
21265 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21266 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21267 return DCI.CombineTo(N, InsV);
21273 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21276 /// This is the leaf of the recursive combinine below. When we have found some
21277 /// chain of single-use x86 shuffle instructions and accumulated the combined
21278 /// shuffle mask represented by them, this will try to pattern match that mask
21279 /// into either a single instruction if there is a special purpose instruction
21280 /// for this operation, or into a PSHUFB instruction which is a fully general
21281 /// instruction but should only be used to replace chains over a certain depth.
21282 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21283 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21284 TargetLowering::DAGCombinerInfo &DCI,
21285 const X86Subtarget *Subtarget) {
21286 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21288 // Find the operand that enters the chain. Note that multiple uses are OK
21289 // here, we're not going to remove the operand we find.
21290 SDValue Input = Op.getOperand(0);
21291 while (Input.getOpcode() == ISD::BITCAST)
21292 Input = Input.getOperand(0);
21294 MVT VT = Input.getSimpleValueType();
21295 MVT RootVT = Root.getSimpleValueType();
21298 // Just remove no-op shuffle masks.
21299 if (Mask.size() == 1) {
21300 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21305 // Use the float domain if the operand type is a floating point type.
21306 bool FloatDomain = VT.isFloatingPoint();
21308 // For floating point shuffles, we don't have free copies in the shuffle
21309 // instructions or the ability to load as part of the instruction, so
21310 // canonicalize their shuffles to UNPCK or MOV variants.
21312 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21313 // vectors because it can have a load folded into it that UNPCK cannot. This
21314 // doesn't preclude something switching to the shorter encoding post-RA.
21316 // FIXME: Should teach these routines about AVX vector widths.
21317 if (FloatDomain && VT.getSizeInBits() == 128) {
21318 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21319 bool Lo = Mask.equals({0, 0});
21322 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21323 // is no slower than UNPCKLPD but has the option to fold the input operand
21324 // into even an unaligned memory load.
21325 if (Lo && Subtarget->hasSSE3()) {
21326 Shuffle = X86ISD::MOVDDUP;
21327 ShuffleVT = MVT::v2f64;
21329 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21330 // than the UNPCK variants.
21331 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21332 ShuffleVT = MVT::v4f32;
21334 if (Depth == 1 && Root->getOpcode() == Shuffle)
21335 return false; // Nothing to do!
21336 Op = DAG.getBitcast(ShuffleVT, Input);
21337 DCI.AddToWorklist(Op.getNode());
21338 if (Shuffle == X86ISD::MOVDDUP)
21339 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21341 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21342 DCI.AddToWorklist(Op.getNode());
21343 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21347 if (Subtarget->hasSSE3() &&
21348 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21349 bool Lo = Mask.equals({0, 0, 2, 2});
21350 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21351 MVT ShuffleVT = MVT::v4f32;
21352 if (Depth == 1 && Root->getOpcode() == Shuffle)
21353 return false; // Nothing to do!
21354 Op = DAG.getBitcast(ShuffleVT, Input);
21355 DCI.AddToWorklist(Op.getNode());
21356 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21357 DCI.AddToWorklist(Op.getNode());
21358 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21362 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21363 bool Lo = Mask.equals({0, 0, 1, 1});
21364 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21365 MVT ShuffleVT = MVT::v4f32;
21366 if (Depth == 1 && Root->getOpcode() == Shuffle)
21367 return false; // Nothing to do!
21368 Op = DAG.getBitcast(ShuffleVT, Input);
21369 DCI.AddToWorklist(Op.getNode());
21370 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21371 DCI.AddToWorklist(Op.getNode());
21372 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21378 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21379 // variants as none of these have single-instruction variants that are
21380 // superior to the UNPCK formulation.
21381 if (!FloatDomain && VT.getSizeInBits() == 128 &&
21382 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21383 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21384 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21386 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21387 bool Lo = Mask[0] == 0;
21388 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21389 if (Depth == 1 && Root->getOpcode() == Shuffle)
21390 return false; // Nothing to do!
21392 switch (Mask.size()) {
21394 ShuffleVT = MVT::v8i16;
21397 ShuffleVT = MVT::v16i8;
21400 llvm_unreachable("Impossible mask size!");
21402 Op = DAG.getBitcast(ShuffleVT, Input);
21403 DCI.AddToWorklist(Op.getNode());
21404 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21405 DCI.AddToWorklist(Op.getNode());
21406 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21411 // Don't try to re-form single instruction chains under any circumstances now
21412 // that we've done encoding canonicalization for them.
21416 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21417 // can replace them with a single PSHUFB instruction profitably. Intel's
21418 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21419 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21420 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21421 SmallVector<SDValue, 16> PSHUFBMask;
21422 int NumBytes = VT.getSizeInBits() / 8;
21423 int Ratio = NumBytes / Mask.size();
21424 for (int i = 0; i < NumBytes; ++i) {
21425 if (Mask[i / Ratio] == SM_SentinelUndef) {
21426 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21429 int M = Mask[i / Ratio] != SM_SentinelZero
21430 ? Ratio * Mask[i / Ratio] + i % Ratio
21432 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21434 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21435 Op = DAG.getBitcast(ByteVT, Input);
21436 DCI.AddToWorklist(Op.getNode());
21437 SDValue PSHUFBMaskOp =
21438 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21439 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21440 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21441 DCI.AddToWorklist(Op.getNode());
21442 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21447 // Failed to find any combines.
21451 /// \brief Fully generic combining of x86 shuffle instructions.
21453 /// This should be the last combine run over the x86 shuffle instructions. Once
21454 /// they have been fully optimized, this will recursively consider all chains
21455 /// of single-use shuffle instructions, build a generic model of the cumulative
21456 /// shuffle operation, and check for simpler instructions which implement this
21457 /// operation. We use this primarily for two purposes:
21459 /// 1) Collapse generic shuffles to specialized single instructions when
21460 /// equivalent. In most cases, this is just an encoding size win, but
21461 /// sometimes we will collapse multiple generic shuffles into a single
21462 /// special-purpose shuffle.
21463 /// 2) Look for sequences of shuffle instructions with 3 or more total
21464 /// instructions, and replace them with the slightly more expensive SSSE3
21465 /// PSHUFB instruction if available. We do this as the last combining step
21466 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
21467 /// a suitable short sequence of other instructions. The PHUFB will either
21468 /// use a register or have to read from memory and so is slightly (but only
21469 /// slightly) more expensive than the other shuffle instructions.
21471 /// Because this is inherently a quadratic operation (for each shuffle in
21472 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21473 /// This should never be an issue in practice as the shuffle lowering doesn't
21474 /// produce sequences of more than 8 instructions.
21476 /// FIXME: We will currently miss some cases where the redundant shuffling
21477 /// would simplify under the threshold for PSHUFB formation because of
21478 /// combine-ordering. To fix this, we should do the redundant instruction
21479 /// combining in this recursive walk.
21480 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21481 ArrayRef<int> RootMask,
21482 int Depth, bool HasPSHUFB,
21484 TargetLowering::DAGCombinerInfo &DCI,
21485 const X86Subtarget *Subtarget) {
21486 // Bound the depth of our recursive combine because this is ultimately
21487 // quadratic in nature.
21491 // Directly rip through bitcasts to find the underlying operand.
21492 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21493 Op = Op.getOperand(0);
21495 MVT VT = Op.getSimpleValueType();
21496 if (!VT.isVector())
21497 return false; // Bail if we hit a non-vector.
21499 assert(Root.getSimpleValueType().isVector() &&
21500 "Shuffles operate on vector types!");
21501 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21502 "Can only combine shuffles of the same vector register size.");
21504 if (!isTargetShuffle(Op.getOpcode()))
21506 SmallVector<int, 16> OpMask;
21508 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21509 // We only can combine unary shuffles which we can decode the mask for.
21510 if (!HaveMask || !IsUnary)
21513 assert(VT.getVectorNumElements() == OpMask.size() &&
21514 "Different mask size from vector size!");
21515 assert(((RootMask.size() > OpMask.size() &&
21516 RootMask.size() % OpMask.size() == 0) ||
21517 (OpMask.size() > RootMask.size() &&
21518 OpMask.size() % RootMask.size() == 0) ||
21519 OpMask.size() == RootMask.size()) &&
21520 "The smaller number of elements must divide the larger.");
21521 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21522 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21523 assert(((RootRatio == 1 && OpRatio == 1) ||
21524 (RootRatio == 1) != (OpRatio == 1)) &&
21525 "Must not have a ratio for both incoming and op masks!");
21527 SmallVector<int, 16> Mask;
21528 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21530 // Merge this shuffle operation's mask into our accumulated mask. Note that
21531 // this shuffle's mask will be the first applied to the input, followed by the
21532 // root mask to get us all the way to the root value arrangement. The reason
21533 // for this order is that we are recursing up the operation chain.
21534 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21535 int RootIdx = i / RootRatio;
21536 if (RootMask[RootIdx] < 0) {
21537 // This is a zero or undef lane, we're done.
21538 Mask.push_back(RootMask[RootIdx]);
21542 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21543 int OpIdx = RootMaskedIdx / OpRatio;
21544 if (OpMask[OpIdx] < 0) {
21545 // The incoming lanes are zero or undef, it doesn't matter which ones we
21547 Mask.push_back(OpMask[OpIdx]);
21551 // Ok, we have non-zero lanes, map them through.
21552 Mask.push_back(OpMask[OpIdx] * OpRatio +
21553 RootMaskedIdx % OpRatio);
21556 // See if we can recurse into the operand to combine more things.
21557 switch (Op.getOpcode()) {
21558 case X86ISD::PSHUFB:
21560 case X86ISD::PSHUFD:
21561 case X86ISD::PSHUFHW:
21562 case X86ISD::PSHUFLW:
21563 if (Op.getOperand(0).hasOneUse() &&
21564 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21565 HasPSHUFB, DAG, DCI, Subtarget))
21569 case X86ISD::UNPCKL:
21570 case X86ISD::UNPCKH:
21571 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21572 // We can't check for single use, we have to check that this shuffle is the only user.
21573 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21574 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21575 HasPSHUFB, DAG, DCI, Subtarget))
21580 // Minor canonicalization of the accumulated shuffle mask to make it easier
21581 // to match below. All this does is detect masks with squential pairs of
21582 // elements, and shrink them to the half-width mask. It does this in a loop
21583 // so it will reduce the size of the mask to the minimal width mask which
21584 // performs an equivalent shuffle.
21585 SmallVector<int, 16> WidenedMask;
21586 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21587 Mask = std::move(WidenedMask);
21588 WidenedMask.clear();
21591 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21595 /// \brief Get the PSHUF-style mask from PSHUF node.
21597 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21598 /// PSHUF-style masks that can be reused with such instructions.
21599 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21600 MVT VT = N.getSimpleValueType();
21601 SmallVector<int, 4> Mask;
21603 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21607 // If we have more than 128-bits, only the low 128-bits of shuffle mask
21608 // matter. Check that the upper masks are repeats and remove them.
21609 if (VT.getSizeInBits() > 128) {
21610 int LaneElts = 128 / VT.getScalarSizeInBits();
21612 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21613 for (int j = 0; j < LaneElts; ++j)
21614 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21615 "Mask doesn't repeat in high 128-bit lanes!");
21617 Mask.resize(LaneElts);
21620 switch (N.getOpcode()) {
21621 case X86ISD::PSHUFD:
21623 case X86ISD::PSHUFLW:
21626 case X86ISD::PSHUFHW:
21627 Mask.erase(Mask.begin(), Mask.begin() + 4);
21628 for (int &M : Mask)
21632 llvm_unreachable("No valid shuffle instruction found!");
21636 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21638 /// We walk up the chain and look for a combinable shuffle, skipping over
21639 /// shuffles that we could hoist this shuffle's transformation past without
21640 /// altering anything.
21642 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21644 TargetLowering::DAGCombinerInfo &DCI) {
21645 assert(N.getOpcode() == X86ISD::PSHUFD &&
21646 "Called with something other than an x86 128-bit half shuffle!");
21649 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21650 // of the shuffles in the chain so that we can form a fresh chain to replace
21652 SmallVector<SDValue, 8> Chain;
21653 SDValue V = N.getOperand(0);
21654 for (; V.hasOneUse(); V = V.getOperand(0)) {
21655 switch (V.getOpcode()) {
21657 return SDValue(); // Nothing combined!
21660 // Skip bitcasts as we always know the type for the target specific
21664 case X86ISD::PSHUFD:
21665 // Found another dword shuffle.
21668 case X86ISD::PSHUFLW:
21669 // Check that the low words (being shuffled) are the identity in the
21670 // dword shuffle, and the high words are self-contained.
21671 if (Mask[0] != 0 || Mask[1] != 1 ||
21672 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21675 Chain.push_back(V);
21678 case X86ISD::PSHUFHW:
21679 // Check that the high words (being shuffled) are the identity in the
21680 // dword shuffle, and the low words are self-contained.
21681 if (Mask[2] != 2 || Mask[3] != 3 ||
21682 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21685 Chain.push_back(V);
21688 case X86ISD::UNPCKL:
21689 case X86ISD::UNPCKH:
21690 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21691 // shuffle into a preceding word shuffle.
21692 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21693 V.getSimpleValueType().getScalarType() != MVT::i16)
21696 // Search for a half-shuffle which we can combine with.
21697 unsigned CombineOp =
21698 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21699 if (V.getOperand(0) != V.getOperand(1) ||
21700 !V->isOnlyUserOf(V.getOperand(0).getNode()))
21702 Chain.push_back(V);
21703 V = V.getOperand(0);
21705 switch (V.getOpcode()) {
21707 return SDValue(); // Nothing to combine.
21709 case X86ISD::PSHUFLW:
21710 case X86ISD::PSHUFHW:
21711 if (V.getOpcode() == CombineOp)
21714 Chain.push_back(V);
21718 V = V.getOperand(0);
21722 } while (V.hasOneUse());
21725 // Break out of the loop if we break out of the switch.
21729 if (!V.hasOneUse())
21730 // We fell out of the loop without finding a viable combining instruction.
21733 // Merge this node's mask and our incoming mask.
21734 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21735 for (int &M : Mask)
21737 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21738 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21740 // Rebuild the chain around this new shuffle.
21741 while (!Chain.empty()) {
21742 SDValue W = Chain.pop_back_val();
21744 if (V.getValueType() != W.getOperand(0).getValueType())
21745 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21747 switch (W.getOpcode()) {
21749 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21751 case X86ISD::UNPCKL:
21752 case X86ISD::UNPCKH:
21753 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21756 case X86ISD::PSHUFD:
21757 case X86ISD::PSHUFLW:
21758 case X86ISD::PSHUFHW:
21759 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21763 if (V.getValueType() != N.getValueType())
21764 V = DAG.getBitcast(N.getValueType(), V);
21766 // Return the new chain to replace N.
21770 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21772 /// We walk up the chain, skipping shuffles of the other half and looking
21773 /// through shuffles which switch halves trying to find a shuffle of the same
21774 /// pair of dwords.
21775 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21777 TargetLowering::DAGCombinerInfo &DCI) {
21779 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21780 "Called with something other than an x86 128-bit half shuffle!");
21782 unsigned CombineOpcode = N.getOpcode();
21784 // Walk up a single-use chain looking for a combinable shuffle.
21785 SDValue V = N.getOperand(0);
21786 for (; V.hasOneUse(); V = V.getOperand(0)) {
21787 switch (V.getOpcode()) {
21789 return false; // Nothing combined!
21792 // Skip bitcasts as we always know the type for the target specific
21796 case X86ISD::PSHUFLW:
21797 case X86ISD::PSHUFHW:
21798 if (V.getOpcode() == CombineOpcode)
21801 // Other-half shuffles are no-ops.
21804 // Break out of the loop if we break out of the switch.
21808 if (!V.hasOneUse())
21809 // We fell out of the loop without finding a viable combining instruction.
21812 // Combine away the bottom node as its shuffle will be accumulated into
21813 // a preceding shuffle.
21814 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21816 // Record the old value.
21819 // Merge this node's mask and our incoming mask (adjusted to account for all
21820 // the pshufd instructions encountered).
21821 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21822 for (int &M : Mask)
21824 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21825 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21827 // Check that the shuffles didn't cancel each other out. If not, we need to
21828 // combine to the new one.
21830 // Replace the combinable shuffle with the combined one, updating all users
21831 // so that we re-evaluate the chain here.
21832 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21837 /// \brief Try to combine x86 target specific shuffles.
21838 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21839 TargetLowering::DAGCombinerInfo &DCI,
21840 const X86Subtarget *Subtarget) {
21842 MVT VT = N.getSimpleValueType();
21843 SmallVector<int, 4> Mask;
21845 switch (N.getOpcode()) {
21846 case X86ISD::PSHUFD:
21847 case X86ISD::PSHUFLW:
21848 case X86ISD::PSHUFHW:
21849 Mask = getPSHUFShuffleMask(N);
21850 assert(Mask.size() == 4);
21856 // Nuke no-op shuffles that show up after combining.
21857 if (isNoopShuffleMask(Mask))
21858 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21860 // Look for simplifications involving one or two shuffle instructions.
21861 SDValue V = N.getOperand(0);
21862 switch (N.getOpcode()) {
21865 case X86ISD::PSHUFLW:
21866 case X86ISD::PSHUFHW:
21867 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21869 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21870 return SDValue(); // We combined away this shuffle, so we're done.
21872 // See if this reduces to a PSHUFD which is no more expensive and can
21873 // combine with more operations. Note that it has to at least flip the
21874 // dwords as otherwise it would have been removed as a no-op.
21875 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21876 int DMask[] = {0, 1, 2, 3};
21877 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21878 DMask[DOffset + 0] = DOffset + 1;
21879 DMask[DOffset + 1] = DOffset + 0;
21880 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21881 V = DAG.getBitcast(DVT, V);
21882 DCI.AddToWorklist(V.getNode());
21883 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21884 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21885 DCI.AddToWorklist(V.getNode());
21886 return DAG.getBitcast(VT, V);
21889 // Look for shuffle patterns which can be implemented as a single unpack.
21890 // FIXME: This doesn't handle the location of the PSHUFD generically, and
21891 // only works when we have a PSHUFD followed by two half-shuffles.
21892 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21893 (V.getOpcode() == X86ISD::PSHUFLW ||
21894 V.getOpcode() == X86ISD::PSHUFHW) &&
21895 V.getOpcode() != N.getOpcode() &&
21897 SDValue D = V.getOperand(0);
21898 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21899 D = D.getOperand(0);
21900 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21901 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21902 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21903 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21904 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21906 for (int i = 0; i < 4; ++i) {
21907 WordMask[i + NOffset] = Mask[i] + NOffset;
21908 WordMask[i + VOffset] = VMask[i] + VOffset;
21910 // Map the word mask through the DWord mask.
21912 for (int i = 0; i < 8; ++i)
21913 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21914 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21915 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21916 // We can replace all three shuffles with an unpack.
21917 V = DAG.getBitcast(VT, D.getOperand(0));
21918 DCI.AddToWorklist(V.getNode());
21919 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21928 case X86ISD::PSHUFD:
21929 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21938 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21940 /// We combine this directly on the abstract vector shuffle nodes so it is
21941 /// easier to generically match. We also insert dummy vector shuffle nodes for
21942 /// the operands which explicitly discard the lanes which are unused by this
21943 /// operation to try to flow through the rest of the combiner the fact that
21944 /// they're unused.
21945 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21947 EVT VT = N->getValueType(0);
21949 // We only handle target-independent shuffles.
21950 // FIXME: It would be easy and harmless to use the target shuffle mask
21951 // extraction tool to support more.
21952 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21955 auto *SVN = cast<ShuffleVectorSDNode>(N);
21956 ArrayRef<int> Mask = SVN->getMask();
21957 SDValue V1 = N->getOperand(0);
21958 SDValue V2 = N->getOperand(1);
21960 // We require the first shuffle operand to be the SUB node, and the second to
21961 // be the ADD node.
21962 // FIXME: We should support the commuted patterns.
21963 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21966 // If there are other uses of these operations we can't fold them.
21967 if (!V1->hasOneUse() || !V2->hasOneUse())
21970 // Ensure that both operations have the same operands. Note that we can
21971 // commute the FADD operands.
21972 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21973 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21974 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21977 // We're looking for blends between FADD and FSUB nodes. We insist on these
21978 // nodes being lined up in a specific expected pattern.
21979 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21980 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21981 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21984 // Only specific types are legal at this point, assert so we notice if and
21985 // when these change.
21986 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21987 VT == MVT::v4f64) &&
21988 "Unknown vector type encountered!");
21990 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21993 /// PerformShuffleCombine - Performs several different shuffle combines.
21994 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21995 TargetLowering::DAGCombinerInfo &DCI,
21996 const X86Subtarget *Subtarget) {
21998 SDValue N0 = N->getOperand(0);
21999 SDValue N1 = N->getOperand(1);
22000 EVT VT = N->getValueType(0);
22002 // Don't create instructions with illegal types after legalize types has run.
22003 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22004 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22007 // If we have legalized the vector types, look for blends of FADD and FSUB
22008 // nodes that we can fuse into an ADDSUB node.
22009 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22010 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22013 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22014 if (Subtarget->hasFp256() && VT.is256BitVector() &&
22015 N->getOpcode() == ISD::VECTOR_SHUFFLE)
22016 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22018 // During Type Legalization, when promoting illegal vector types,
22019 // the backend might introduce new shuffle dag nodes and bitcasts.
22021 // This code performs the following transformation:
22022 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22023 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22025 // We do this only if both the bitcast and the BINOP dag nodes have
22026 // one use. Also, perform this transformation only if the new binary
22027 // operation is legal. This is to avoid introducing dag nodes that
22028 // potentially need to be further expanded (or custom lowered) into a
22029 // less optimal sequence of dag nodes.
22030 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22031 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22032 N0.getOpcode() == ISD::BITCAST) {
22033 SDValue BC0 = N0.getOperand(0);
22034 EVT SVT = BC0.getValueType();
22035 unsigned Opcode = BC0.getOpcode();
22036 unsigned NumElts = VT.getVectorNumElements();
22038 if (BC0.hasOneUse() && SVT.isVector() &&
22039 SVT.getVectorNumElements() * 2 == NumElts &&
22040 TLI.isOperationLegal(Opcode, VT)) {
22041 bool CanFold = false;
22053 unsigned SVTNumElts = SVT.getVectorNumElements();
22054 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22055 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22056 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22057 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22058 CanFold = SVOp->getMaskElt(i) < 0;
22061 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22062 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22063 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22064 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22069 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22070 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22071 // consecutive, non-overlapping, and in the right order.
22072 SmallVector<SDValue, 16> Elts;
22073 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22074 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22076 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22079 if (isTargetShuffle(N->getOpcode())) {
22081 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22082 if (Shuffle.getNode())
22085 // Try recursively combining arbitrary sequences of x86 shuffle
22086 // instructions into higher-order shuffles. We do this after combining
22087 // specific PSHUF instruction sequences into their minimal form so that we
22088 // can evaluate how many specialized shuffle instructions are involved in
22089 // a particular chain.
22090 SmallVector<int, 1> NonceMask; // Just a placeholder.
22091 NonceMask.push_back(0);
22092 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22093 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22095 return SDValue(); // This routine will use CombineTo to replace N.
22101 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22102 /// specific shuffle of a load can be folded into a single element load.
22103 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22104 /// shuffles have been custom lowered so we need to handle those here.
22105 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22106 TargetLowering::DAGCombinerInfo &DCI) {
22107 if (DCI.isBeforeLegalizeOps())
22110 SDValue InVec = N->getOperand(0);
22111 SDValue EltNo = N->getOperand(1);
22113 if (!isa<ConstantSDNode>(EltNo))
22116 EVT OriginalVT = InVec.getValueType();
22118 if (InVec.getOpcode() == ISD::BITCAST) {
22119 // Don't duplicate a load with other uses.
22120 if (!InVec.hasOneUse())
22122 EVT BCVT = InVec.getOperand(0).getValueType();
22123 if (!BCVT.isVector() ||
22124 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22126 InVec = InVec.getOperand(0);
22129 EVT CurrentVT = InVec.getValueType();
22131 if (!isTargetShuffle(InVec.getOpcode()))
22134 // Don't duplicate a load with other uses.
22135 if (!InVec.hasOneUse())
22138 SmallVector<int, 16> ShuffleMask;
22140 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22141 ShuffleMask, UnaryShuffle))
22144 // Select the input vector, guarding against out of range extract vector.
22145 unsigned NumElems = CurrentVT.getVectorNumElements();
22146 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22147 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22148 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22149 : InVec.getOperand(1);
22151 // If inputs to shuffle are the same for both ops, then allow 2 uses
22152 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22153 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22155 if (LdNode.getOpcode() == ISD::BITCAST) {
22156 // Don't duplicate a load with other uses.
22157 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22160 AllowedUses = 1; // only allow 1 load use if we have a bitcast
22161 LdNode = LdNode.getOperand(0);
22164 if (!ISD::isNormalLoad(LdNode.getNode()))
22167 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22169 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22172 EVT EltVT = N->getValueType(0);
22173 // If there's a bitcast before the shuffle, check if the load type and
22174 // alignment is valid.
22175 unsigned Align = LN0->getAlignment();
22176 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22177 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22178 EltVT.getTypeForEVT(*DAG.getContext()));
22180 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22183 // All checks match so transform back to vector_shuffle so that DAG combiner
22184 // can finish the job
22187 // Create shuffle node taking into account the case that its a unary shuffle
22188 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22189 : InVec.getOperand(1);
22190 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22191 InVec.getOperand(0), Shuffle,
22193 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22194 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22198 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22199 /// special and don't usually play with other vector types, it's better to
22200 /// handle them early to be sure we emit efficient code by avoiding
22201 /// store-load conversions.
22202 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22203 if (N->getValueType(0) != MVT::x86mmx ||
22204 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22205 N->getOperand(0)->getValueType(0) != MVT::v2i32)
22208 SDValue V = N->getOperand(0);
22209 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22210 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22211 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22212 N->getValueType(0), V.getOperand(0));
22217 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22218 /// generation and convert it from being a bunch of shuffles and extracts
22219 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22220 /// storing the value and loading scalars back, while for x64 we should
22221 /// use 64-bit extracts and shifts.
22222 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22223 TargetLowering::DAGCombinerInfo &DCI) {
22224 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22227 SDValue InputVector = N->getOperand(0);
22228 SDLoc dl(InputVector);
22229 // Detect mmx to i32 conversion through a v2i32 elt extract.
22230 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22231 N->getValueType(0) == MVT::i32 &&
22232 InputVector.getValueType() == MVT::v2i32) {
22234 // The bitcast source is a direct mmx result.
22235 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22236 if (MMXSrc.getValueType() == MVT::x86mmx)
22237 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22238 N->getValueType(0),
22239 InputVector.getNode()->getOperand(0));
22241 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22242 SDValue MMXSrcOp = MMXSrc.getOperand(0);
22243 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22244 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22245 MMXSrcOp.getOpcode() == ISD::BITCAST &&
22246 MMXSrcOp.getValueType() == MVT::v1i64 &&
22247 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22248 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22249 N->getValueType(0),
22250 MMXSrcOp.getOperand(0));
22253 EVT VT = N->getValueType(0);
22255 if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22256 InputVector.getOpcode() == ISD::BITCAST &&
22257 dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22258 uint64_t ExtractedElt =
22259 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22260 uint64_t InputValue =
22261 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22262 uint64_t Res = (InputValue >> ExtractedElt) & 1;
22263 return DAG.getConstant(Res, dl, MVT::i1);
22265 // Only operate on vectors of 4 elements, where the alternative shuffling
22266 // gets to be more expensive.
22267 if (InputVector.getValueType() != MVT::v4i32)
22270 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22271 // single use which is a sign-extend or zero-extend, and all elements are
22273 SmallVector<SDNode *, 4> Uses;
22274 unsigned ExtractedElements = 0;
22275 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22276 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22277 if (UI.getUse().getResNo() != InputVector.getResNo())
22280 SDNode *Extract = *UI;
22281 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22284 if (Extract->getValueType(0) != MVT::i32)
22286 if (!Extract->hasOneUse())
22288 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22289 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22291 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22294 // Record which element was extracted.
22295 ExtractedElements |=
22296 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22298 Uses.push_back(Extract);
22301 // If not all the elements were used, this may not be worthwhile.
22302 if (ExtractedElements != 15)
22305 // Ok, we've now decided to do the transformation.
22306 // If 64-bit shifts are legal, use the extract-shift sequence,
22307 // otherwise bounce the vector off the cache.
22308 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22311 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22312 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22313 auto &DL = DAG.getDataLayout();
22314 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22315 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22316 DAG.getConstant(0, dl, VecIdxTy));
22317 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22318 DAG.getConstant(1, dl, VecIdxTy));
22320 SDValue ShAmt = DAG.getConstant(
22321 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22322 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22323 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22324 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22325 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22326 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22327 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22329 // Store the value to a temporary stack slot.
22330 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22331 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22332 MachinePointerInfo(), false, false, 0);
22334 EVT ElementType = InputVector.getValueType().getVectorElementType();
22335 unsigned EltSize = ElementType.getSizeInBits() / 8;
22337 // Replace each use (extract) with a load of the appropriate element.
22338 for (unsigned i = 0; i < 4; ++i) {
22339 uint64_t Offset = EltSize * i;
22340 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22341 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22343 SDValue ScalarAddr =
22344 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22346 // Load the scalar.
22347 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22348 ScalarAddr, MachinePointerInfo(),
22349 false, false, false, 0);
22354 // Replace the extracts
22355 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22356 UE = Uses.end(); UI != UE; ++UI) {
22357 SDNode *Extract = *UI;
22359 SDValue Idx = Extract->getOperand(1);
22360 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22361 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22364 // The replacement was made in place; don't return anything.
22368 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22369 static std::pair<unsigned, bool>
22370 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22371 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22372 if (!VT.isVector())
22373 return std::make_pair(0, false);
22375 bool NeedSplit = false;
22376 switch (VT.getSimpleVT().SimpleTy) {
22377 default: return std::make_pair(0, false);
22380 if (!Subtarget->hasVLX())
22381 return std::make_pair(0, false);
22385 if (!Subtarget->hasBWI())
22386 return std::make_pair(0, false);
22390 if (!Subtarget->hasAVX512())
22391 return std::make_pair(0, false);
22396 if (!Subtarget->hasAVX2())
22398 if (!Subtarget->hasAVX())
22399 return std::make_pair(0, false);
22404 if (!Subtarget->hasSSE2())
22405 return std::make_pair(0, false);
22408 // SSE2 has only a small subset of the operations.
22409 bool hasUnsigned = Subtarget->hasSSE41() ||
22410 (Subtarget->hasSSE2() && VT == MVT::v16i8);
22411 bool hasSigned = Subtarget->hasSSE41() ||
22412 (Subtarget->hasSSE2() && VT == MVT::v8i16);
22414 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22417 // Check for x CC y ? x : y.
22418 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22419 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22424 Opc = hasUnsigned ? ISD::UMIN : 0; break;
22427 Opc = hasUnsigned ? ISD::UMAX : 0; break;
22430 Opc = hasSigned ? ISD::SMIN : 0; break;
22433 Opc = hasSigned ? ISD::SMAX : 0; break;
22435 // Check for x CC y ? y : x -- a min/max with reversed arms.
22436 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22437 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22442 Opc = hasUnsigned ? ISD::UMAX : 0; break;
22445 Opc = hasUnsigned ? ISD::UMIN : 0; break;
22448 Opc = hasSigned ? ISD::SMAX : 0; break;
22451 Opc = hasSigned ? ISD::SMIN : 0; break;
22455 return std::make_pair(Opc, NeedSplit);
22459 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22460 const X86Subtarget *Subtarget) {
22462 SDValue Cond = N->getOperand(0);
22463 SDValue LHS = N->getOperand(1);
22464 SDValue RHS = N->getOperand(2);
22466 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22467 SDValue CondSrc = Cond->getOperand(0);
22468 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22469 Cond = CondSrc->getOperand(0);
22472 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22475 // A vselect where all conditions and data are constants can be optimized into
22476 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22477 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22478 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22481 unsigned MaskValue = 0;
22482 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22485 MVT VT = N->getSimpleValueType(0);
22486 unsigned NumElems = VT.getVectorNumElements();
22487 SmallVector<int, 8> ShuffleMask(NumElems, -1);
22488 for (unsigned i = 0; i < NumElems; ++i) {
22489 // Be sure we emit undef where we can.
22490 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22491 ShuffleMask[i] = -1;
22493 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22496 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22497 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22499 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22502 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22504 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22505 TargetLowering::DAGCombinerInfo &DCI,
22506 const X86Subtarget *Subtarget) {
22508 SDValue Cond = N->getOperand(0);
22509 // Get the LHS/RHS of the select.
22510 SDValue LHS = N->getOperand(1);
22511 SDValue RHS = N->getOperand(2);
22512 EVT VT = LHS.getValueType();
22513 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22515 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22516 // instructions match the semantics of the common C idiom x<y?x:y but not
22517 // x<=y?x:y, because of how they handle negative zero (which can be
22518 // ignored in unsafe-math mode).
22519 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22520 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22521 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22522 (Subtarget->hasSSE2() ||
22523 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22524 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22526 unsigned Opcode = 0;
22527 // Check for x CC y ? x : y.
22528 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22529 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22533 // Converting this to a min would handle NaNs incorrectly, and swapping
22534 // the operands would cause it to handle comparisons between positive
22535 // and negative zero incorrectly.
22536 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22537 if (!DAG.getTarget().Options.UnsafeFPMath &&
22538 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22540 std::swap(LHS, RHS);
22542 Opcode = X86ISD::FMIN;
22545 // Converting this to a min would handle comparisons between positive
22546 // and negative zero incorrectly.
22547 if (!DAG.getTarget().Options.UnsafeFPMath &&
22548 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22550 Opcode = X86ISD::FMIN;
22553 // Converting this to a min would handle both negative zeros and NaNs
22554 // incorrectly, but we can swap the operands to fix both.
22555 std::swap(LHS, RHS);
22559 Opcode = X86ISD::FMIN;
22563 // Converting this to a max would handle comparisons between positive
22564 // and negative zero incorrectly.
22565 if (!DAG.getTarget().Options.UnsafeFPMath &&
22566 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22568 Opcode = X86ISD::FMAX;
22571 // Converting this to a max would handle NaNs incorrectly, and swapping
22572 // the operands would cause it to handle comparisons between positive
22573 // and negative zero incorrectly.
22574 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22575 if (!DAG.getTarget().Options.UnsafeFPMath &&
22576 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22578 std::swap(LHS, RHS);
22580 Opcode = X86ISD::FMAX;
22583 // Converting this to a max would handle both negative zeros and NaNs
22584 // incorrectly, but we can swap the operands to fix both.
22585 std::swap(LHS, RHS);
22589 Opcode = X86ISD::FMAX;
22592 // Check for x CC y ? y : x -- a min/max with reversed arms.
22593 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22594 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22598 // Converting this to a min would handle comparisons between positive
22599 // and negative zero incorrectly, and swapping the operands would
22600 // cause it to handle NaNs incorrectly.
22601 if (!DAG.getTarget().Options.UnsafeFPMath &&
22602 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22603 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22605 std::swap(LHS, RHS);
22607 Opcode = X86ISD::FMIN;
22610 // Converting this to a min would handle NaNs incorrectly.
22611 if (!DAG.getTarget().Options.UnsafeFPMath &&
22612 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22614 Opcode = X86ISD::FMIN;
22617 // Converting this to a min would handle both negative zeros and NaNs
22618 // incorrectly, but we can swap the operands to fix both.
22619 std::swap(LHS, RHS);
22623 Opcode = X86ISD::FMIN;
22627 // Converting this to a max would handle NaNs incorrectly.
22628 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22630 Opcode = X86ISD::FMAX;
22633 // Converting this to a max would handle comparisons between positive
22634 // and negative zero incorrectly, and swapping the operands would
22635 // cause it to handle NaNs incorrectly.
22636 if (!DAG.getTarget().Options.UnsafeFPMath &&
22637 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22638 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22640 std::swap(LHS, RHS);
22642 Opcode = X86ISD::FMAX;
22645 // Converting this to a max would handle both negative zeros and NaNs
22646 // incorrectly, but we can swap the operands to fix both.
22647 std::swap(LHS, RHS);
22651 Opcode = X86ISD::FMAX;
22657 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22660 EVT CondVT = Cond.getValueType();
22661 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22662 CondVT.getVectorElementType() == MVT::i1) {
22663 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22664 // lowering on KNL. In this case we convert it to
22665 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22666 // The same situation for all 128 and 256-bit vectors of i8 and i16.
22667 // Since SKX these selects have a proper lowering.
22668 EVT OpVT = LHS.getValueType();
22669 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22670 (OpVT.getVectorElementType() == MVT::i8 ||
22671 OpVT.getVectorElementType() == MVT::i16) &&
22672 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22673 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22674 DCI.AddToWorklist(Cond.getNode());
22675 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22678 // If this is a select between two integer constants, try to do some
22680 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22681 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22682 // Don't do this for crazy integer types.
22683 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22684 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22685 // so that TrueC (the true value) is larger than FalseC.
22686 bool NeedsCondInvert = false;
22688 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22689 // Efficiently invertible.
22690 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
22691 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
22692 isa<ConstantSDNode>(Cond.getOperand(1))))) {
22693 NeedsCondInvert = true;
22694 std::swap(TrueC, FalseC);
22697 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
22698 if (FalseC->getAPIntValue() == 0 &&
22699 TrueC->getAPIntValue().isPowerOf2()) {
22700 if (NeedsCondInvert) // Invert the condition if needed.
22701 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22702 DAG.getConstant(1, DL, Cond.getValueType()));
22704 // Zero extend the condition if needed.
22705 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22707 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22708 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22709 DAG.getConstant(ShAmt, DL, MVT::i8));
22712 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22713 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22714 if (NeedsCondInvert) // Invert the condition if needed.
22715 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22716 DAG.getConstant(1, DL, Cond.getValueType()));
22718 // Zero extend the condition if needed.
22719 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22720 FalseC->getValueType(0), Cond);
22721 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22722 SDValue(FalseC, 0));
22725 // Optimize cases that will turn into an LEA instruction. This requires
22726 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22727 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22728 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22729 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22731 bool isFastMultiplier = false;
22733 switch ((unsigned char)Diff) {
22735 case 1: // result = add base, cond
22736 case 2: // result = lea base( , cond*2)
22737 case 3: // result = lea base(cond, cond*2)
22738 case 4: // result = lea base( , cond*4)
22739 case 5: // result = lea base(cond, cond*4)
22740 case 8: // result = lea base( , cond*8)
22741 case 9: // result = lea base(cond, cond*8)
22742 isFastMultiplier = true;
22747 if (isFastMultiplier) {
22748 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22749 if (NeedsCondInvert) // Invert the condition if needed.
22750 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22751 DAG.getConstant(1, DL, Cond.getValueType()));
22753 // Zero extend the condition if needed.
22754 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22756 // Scale the condition by the difference.
22758 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22759 DAG.getConstant(Diff, DL,
22760 Cond.getValueType()));
22762 // Add the base if non-zero.
22763 if (FalseC->getAPIntValue() != 0)
22764 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22765 SDValue(FalseC, 0));
22772 // Canonicalize max and min:
22773 // (x > y) ? x : y -> (x >= y) ? x : y
22774 // (x < y) ? x : y -> (x <= y) ? x : y
22775 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22776 // the need for an extra compare
22777 // against zero. e.g.
22778 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22780 // testl %edi, %edi
22782 // cmovgl %edi, %eax
22786 // cmovsl %eax, %edi
22787 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22788 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22789 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22790 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22795 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22796 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22797 Cond.getOperand(0), Cond.getOperand(1), NewCC);
22798 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22803 // Early exit check
22804 if (!TLI.isTypeLegal(VT))
22807 // Match VSELECTs into subs with unsigned saturation.
22808 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22809 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22810 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22811 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22812 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22814 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22815 // left side invert the predicate to simplify logic below.
22817 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22819 CC = ISD::getSetCCInverse(CC, true);
22820 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22824 if (Other.getNode() && Other->getNumOperands() == 2 &&
22825 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22826 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22827 SDValue CondRHS = Cond->getOperand(1);
22829 // Look for a general sub with unsigned saturation first.
22830 // x >= y ? x-y : 0 --> subus x, y
22831 // x > y ? x-y : 0 --> subus x, y
22832 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22833 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22834 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22836 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22837 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22838 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22839 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22840 // If the RHS is a constant we have to reverse the const
22841 // canonicalization.
22842 // x > C-1 ? x+-C : 0 --> subus x, C
22843 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22844 CondRHSConst->getAPIntValue() ==
22845 (-OpRHSConst->getAPIntValue() - 1))
22846 return DAG.getNode(
22847 X86ISD::SUBUS, DL, VT, OpLHS,
22848 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22850 // Another special case: If C was a sign bit, the sub has been
22851 // canonicalized into a xor.
22852 // FIXME: Would it be better to use computeKnownBits to determine
22853 // whether it's safe to decanonicalize the xor?
22854 // x s< 0 ? x^C : 0 --> subus x, C
22855 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22856 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22857 OpRHSConst->getAPIntValue().isSignBit())
22858 // Note that we have to rebuild the RHS constant here to ensure we
22859 // don't rely on particular values of undef lanes.
22860 return DAG.getNode(
22861 X86ISD::SUBUS, DL, VT, OpLHS,
22862 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22867 // Try to match a min/max vector operation.
22868 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22869 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22870 unsigned Opc = ret.first;
22871 bool NeedSplit = ret.second;
22873 if (Opc && NeedSplit) {
22874 unsigned NumElems = VT.getVectorNumElements();
22875 // Extract the LHS vectors
22876 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22877 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22879 // Extract the RHS vectors
22880 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22881 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22883 // Create min/max for each subvector
22884 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22885 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22887 // Merge the result
22888 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22890 return DAG.getNode(Opc, DL, VT, LHS, RHS);
22893 // Simplify vector selection if condition value type matches vselect
22895 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22896 assert(Cond.getValueType().isVector() &&
22897 "vector select expects a vector selector!");
22899 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22900 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22902 // Try invert the condition if true value is not all 1s and false value
22904 if (!TValIsAllOnes && !FValIsAllZeros &&
22905 // Check if the selector will be produced by CMPP*/PCMP*
22906 Cond.getOpcode() == ISD::SETCC &&
22907 // Check if SETCC has already been promoted
22908 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22910 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22911 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22913 if (TValIsAllZeros || FValIsAllOnes) {
22914 SDValue CC = Cond.getOperand(2);
22915 ISD::CondCode NewCC =
22916 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22917 Cond.getOperand(0).getValueType().isInteger());
22918 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22919 std::swap(LHS, RHS);
22920 TValIsAllOnes = FValIsAllOnes;
22921 FValIsAllZeros = TValIsAllZeros;
22925 if (TValIsAllOnes || FValIsAllZeros) {
22928 if (TValIsAllOnes && FValIsAllZeros)
22930 else if (TValIsAllOnes)
22932 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22933 else if (FValIsAllZeros)
22934 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22935 DAG.getBitcast(CondVT, LHS));
22937 return DAG.getBitcast(VT, Ret);
22941 // We should generate an X86ISD::BLENDI from a vselect if its argument
22942 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22943 // constants. This specific pattern gets generated when we split a
22944 // selector for a 512 bit vector in a machine without AVX512 (but with
22945 // 256-bit vectors), during legalization:
22947 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22949 // Iff we find this pattern and the build_vectors are built from
22950 // constants, we translate the vselect into a shuffle_vector that we
22951 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22952 if ((N->getOpcode() == ISD::VSELECT ||
22953 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22954 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22955 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22956 if (Shuffle.getNode())
22960 // If this is a *dynamic* select (non-constant condition) and we can match
22961 // this node with one of the variable blend instructions, restructure the
22962 // condition so that the blends can use the high bit of each element and use
22963 // SimplifyDemandedBits to simplify the condition operand.
22964 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22965 !DCI.isBeforeLegalize() &&
22966 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22967 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22969 // Don't optimize vector selects that map to mask-registers.
22973 // We can only handle the cases where VSELECT is directly legal on the
22974 // subtarget. We custom lower VSELECT nodes with constant conditions and
22975 // this makes it hard to see whether a dynamic VSELECT will correctly
22976 // lower, so we both check the operation's status and explicitly handle the
22977 // cases where a *dynamic* blend will fail even though a constant-condition
22978 // blend could be custom lowered.
22979 // FIXME: We should find a better way to handle this class of problems.
22980 // Potentially, we should combine constant-condition vselect nodes
22981 // pre-legalization into shuffles and not mark as many types as custom
22983 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22985 // FIXME: We don't support i16-element blends currently. We could and
22986 // should support them by making *all* the bits in the condition be set
22987 // rather than just the high bit and using an i8-element blend.
22988 if (VT.getScalarType() == MVT::i16)
22990 // Dynamic blending was only available from SSE4.1 onward.
22991 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22993 // Byte blends are only available in AVX2
22994 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22995 !Subtarget->hasAVX2())
22998 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22999 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23001 APInt KnownZero, KnownOne;
23002 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23003 DCI.isBeforeLegalizeOps());
23004 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23005 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23007 // If we changed the computation somewhere in the DAG, this change
23008 // will affect all users of Cond.
23009 // Make sure it is fine and update all the nodes so that we do not
23010 // use the generic VSELECT anymore. Otherwise, we may perform
23011 // wrong optimizations as we messed up with the actual expectation
23012 // for the vector boolean values.
23013 if (Cond != TLO.Old) {
23014 // Check all uses of that condition operand to check whether it will be
23015 // consumed by non-BLEND instructions, which may depend on all bits are
23017 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23019 if (I->getOpcode() != ISD::VSELECT)
23020 // TODO: Add other opcodes eventually lowered into BLEND.
23023 // Update all the users of the condition, before committing the change,
23024 // so that the VSELECT optimizations that expect the correct vector
23025 // boolean value will not be triggered.
23026 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23028 DAG.ReplaceAllUsesOfValueWith(
23030 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23031 Cond, I->getOperand(1), I->getOperand(2)));
23032 DCI.CommitTargetLoweringOpt(TLO);
23035 // At this point, only Cond is changed. Change the condition
23036 // just for N to keep the opportunity to optimize all other
23037 // users their own way.
23038 DAG.ReplaceAllUsesOfValueWith(
23040 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23041 TLO.New, N->getOperand(1), N->getOperand(2)));
23049 // Check whether a boolean test is testing a boolean value generated by
23050 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23053 // Simplify the following patterns:
23054 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23055 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23056 // to (Op EFLAGS Cond)
23058 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23059 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23060 // to (Op EFLAGS !Cond)
23062 // where Op could be BRCOND or CMOV.
23064 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23065 // Quit if not CMP and SUB with its value result used.
23066 if (Cmp.getOpcode() != X86ISD::CMP &&
23067 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23070 // Quit if not used as a boolean value.
23071 if (CC != X86::COND_E && CC != X86::COND_NE)
23074 // Check CMP operands. One of them should be 0 or 1 and the other should be
23075 // an SetCC or extended from it.
23076 SDValue Op1 = Cmp.getOperand(0);
23077 SDValue Op2 = Cmp.getOperand(1);
23080 const ConstantSDNode* C = nullptr;
23081 bool needOppositeCond = (CC == X86::COND_E);
23082 bool checkAgainstTrue = false; // Is it a comparison against 1?
23084 if ((C = dyn_cast<ConstantSDNode>(Op1)))
23086 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23088 else // Quit if all operands are not constants.
23091 if (C->getZExtValue() == 1) {
23092 needOppositeCond = !needOppositeCond;
23093 checkAgainstTrue = true;
23094 } else if (C->getZExtValue() != 0)
23095 // Quit if the constant is neither 0 or 1.
23098 bool truncatedToBoolWithAnd = false;
23099 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23100 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23101 SetCC.getOpcode() == ISD::TRUNCATE ||
23102 SetCC.getOpcode() == ISD::AND) {
23103 if (SetCC.getOpcode() == ISD::AND) {
23105 ConstantSDNode *CS;
23106 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23107 CS->getZExtValue() == 1)
23109 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23110 CS->getZExtValue() == 1)
23114 SetCC = SetCC.getOperand(OpIdx);
23115 truncatedToBoolWithAnd = true;
23117 SetCC = SetCC.getOperand(0);
23120 switch (SetCC.getOpcode()) {
23121 case X86ISD::SETCC_CARRY:
23122 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23123 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23124 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23125 // truncated to i1 using 'and'.
23126 if (checkAgainstTrue && !truncatedToBoolWithAnd)
23128 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23129 "Invalid use of SETCC_CARRY!");
23131 case X86ISD::SETCC:
23132 // Set the condition code or opposite one if necessary.
23133 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23134 if (needOppositeCond)
23135 CC = X86::GetOppositeBranchCondition(CC);
23136 return SetCC.getOperand(1);
23137 case X86ISD::CMOV: {
23138 // Check whether false/true value has canonical one, i.e. 0 or 1.
23139 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23140 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23141 // Quit if true value is not a constant.
23144 // Quit if false value is not a constant.
23146 SDValue Op = SetCC.getOperand(0);
23147 // Skip 'zext' or 'trunc' node.
23148 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23149 Op.getOpcode() == ISD::TRUNCATE)
23150 Op = Op.getOperand(0);
23151 // A special case for rdrand/rdseed, where 0 is set if false cond is
23153 if ((Op.getOpcode() != X86ISD::RDRAND &&
23154 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23157 // Quit if false value is not the constant 0 or 1.
23158 bool FValIsFalse = true;
23159 if (FVal && FVal->getZExtValue() != 0) {
23160 if (FVal->getZExtValue() != 1)
23162 // If FVal is 1, opposite cond is needed.
23163 needOppositeCond = !needOppositeCond;
23164 FValIsFalse = false;
23166 // Quit if TVal is not the constant opposite of FVal.
23167 if (FValIsFalse && TVal->getZExtValue() != 1)
23169 if (!FValIsFalse && TVal->getZExtValue() != 0)
23171 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23172 if (needOppositeCond)
23173 CC = X86::GetOppositeBranchCondition(CC);
23174 return SetCC.getOperand(3);
23181 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23183 /// (X86or (X86setcc) (X86setcc))
23184 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
23185 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23186 X86::CondCode &CC1, SDValue &Flags,
23188 if (Cond->getOpcode() == X86ISD::CMP) {
23189 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23190 if (!CondOp1C || !CondOp1C->isNullValue())
23193 Cond = Cond->getOperand(0);
23198 SDValue SetCC0, SetCC1;
23199 switch (Cond->getOpcode()) {
23200 default: return false;
23207 SetCC0 = Cond->getOperand(0);
23208 SetCC1 = Cond->getOperand(1);
23212 // Make sure we have SETCC nodes, using the same flags value.
23213 if (SetCC0.getOpcode() != X86ISD::SETCC ||
23214 SetCC1.getOpcode() != X86ISD::SETCC ||
23215 SetCC0->getOperand(1) != SetCC1->getOperand(1))
23218 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23219 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23220 Flags = SetCC0->getOperand(1);
23224 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23225 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23226 TargetLowering::DAGCombinerInfo &DCI,
23227 const X86Subtarget *Subtarget) {
23230 // If the flag operand isn't dead, don't touch this CMOV.
23231 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23234 SDValue FalseOp = N->getOperand(0);
23235 SDValue TrueOp = N->getOperand(1);
23236 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23237 SDValue Cond = N->getOperand(3);
23239 if (CC == X86::COND_E || CC == X86::COND_NE) {
23240 switch (Cond.getOpcode()) {
23244 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23245 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23246 return (CC == X86::COND_E) ? FalseOp : TrueOp;
23252 Flags = checkBoolTestSetCCCombine(Cond, CC);
23253 if (Flags.getNode() &&
23254 // Extra check as FCMOV only supports a subset of X86 cond.
23255 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23256 SDValue Ops[] = { FalseOp, TrueOp,
23257 DAG.getConstant(CC, DL, MVT::i8), Flags };
23258 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23261 // If this is a select between two integer constants, try to do some
23262 // optimizations. Note that the operands are ordered the opposite of SELECT
23264 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23265 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23266 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23267 // larger than FalseC (the false value).
23268 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23269 CC = X86::GetOppositeBranchCondition(CC);
23270 std::swap(TrueC, FalseC);
23271 std::swap(TrueOp, FalseOp);
23274 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
23275 // This is efficient for any integer data type (including i8/i16) and
23277 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23278 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23279 DAG.getConstant(CC, DL, MVT::i8), Cond);
23281 // Zero extend the condition if needed.
23282 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23284 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23285 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23286 DAG.getConstant(ShAmt, DL, MVT::i8));
23287 if (N->getNumValues() == 2) // Dead flag value?
23288 return DCI.CombineTo(N, Cond, SDValue());
23292 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
23293 // for any integer data type, including i8/i16.
23294 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23295 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23296 DAG.getConstant(CC, DL, MVT::i8), Cond);
23298 // Zero extend the condition if needed.
23299 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23300 FalseC->getValueType(0), Cond);
23301 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23302 SDValue(FalseC, 0));
23304 if (N->getNumValues() == 2) // Dead flag value?
23305 return DCI.CombineTo(N, Cond, SDValue());
23309 // Optimize cases that will turn into an LEA instruction. This requires
23310 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23311 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23312 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23313 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23315 bool isFastMultiplier = false;
23317 switch ((unsigned char)Diff) {
23319 case 1: // result = add base, cond
23320 case 2: // result = lea base( , cond*2)
23321 case 3: // result = lea base(cond, cond*2)
23322 case 4: // result = lea base( , cond*4)
23323 case 5: // result = lea base(cond, cond*4)
23324 case 8: // result = lea base( , cond*8)
23325 case 9: // result = lea base(cond, cond*8)
23326 isFastMultiplier = true;
23331 if (isFastMultiplier) {
23332 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23333 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23334 DAG.getConstant(CC, DL, MVT::i8), Cond);
23335 // Zero extend the condition if needed.
23336 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23338 // Scale the condition by the difference.
23340 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23341 DAG.getConstant(Diff, DL, Cond.getValueType()));
23343 // Add the base if non-zero.
23344 if (FalseC->getAPIntValue() != 0)
23345 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23346 SDValue(FalseC, 0));
23347 if (N->getNumValues() == 2) // Dead flag value?
23348 return DCI.CombineTo(N, Cond, SDValue());
23355 // Handle these cases:
23356 // (select (x != c), e, c) -> select (x != c), e, x),
23357 // (select (x == c), c, e) -> select (x == c), x, e)
23358 // where the c is an integer constant, and the "select" is the combination
23359 // of CMOV and CMP.
23361 // The rationale for this change is that the conditional-move from a constant
23362 // needs two instructions, however, conditional-move from a register needs
23363 // only one instruction.
23365 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23366 // some instruction-combining opportunities. This opt needs to be
23367 // postponed as late as possible.
23369 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23370 // the DCI.xxxx conditions are provided to postpone the optimization as
23371 // late as possible.
23373 ConstantSDNode *CmpAgainst = nullptr;
23374 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23375 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23376 !isa<ConstantSDNode>(Cond.getOperand(0))) {
23378 if (CC == X86::COND_NE &&
23379 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23380 CC = X86::GetOppositeBranchCondition(CC);
23381 std::swap(TrueOp, FalseOp);
23384 if (CC == X86::COND_E &&
23385 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23386 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23387 DAG.getConstant(CC, DL, MVT::i8), Cond };
23388 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23393 // Fold and/or of setcc's to double CMOV:
23394 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23395 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23397 // This combine lets us generate:
23398 // cmovcc1 (jcc1 if we don't have CMOV)
23404 // cmovne (jne if we don't have CMOV)
23405 // When we can't use the CMOV instruction, it might increase branch
23407 // When we can use CMOV, or when there is no mispredict, this improves
23408 // throughput and reduces register pressure.
23410 if (CC == X86::COND_NE) {
23412 X86::CondCode CC0, CC1;
23414 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23416 std::swap(FalseOp, TrueOp);
23417 CC0 = X86::GetOppositeBranchCondition(CC0);
23418 CC1 = X86::GetOppositeBranchCondition(CC1);
23421 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23423 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23424 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23425 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23426 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23434 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23435 const X86Subtarget *Subtarget) {
23436 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23438 default: return SDValue();
23439 // SSE/AVX/AVX2 blend intrinsics.
23440 case Intrinsic::x86_avx2_pblendvb:
23441 // Don't try to simplify this intrinsic if we don't have AVX2.
23442 if (!Subtarget->hasAVX2())
23445 case Intrinsic::x86_avx_blendv_pd_256:
23446 case Intrinsic::x86_avx_blendv_ps_256:
23447 // Don't try to simplify this intrinsic if we don't have AVX.
23448 if (!Subtarget->hasAVX())
23451 case Intrinsic::x86_sse41_blendvps:
23452 case Intrinsic::x86_sse41_blendvpd:
23453 case Intrinsic::x86_sse41_pblendvb: {
23454 SDValue Op0 = N->getOperand(1);
23455 SDValue Op1 = N->getOperand(2);
23456 SDValue Mask = N->getOperand(3);
23458 // Don't try to simplify this intrinsic if we don't have SSE4.1.
23459 if (!Subtarget->hasSSE41())
23462 // fold (blend A, A, Mask) -> A
23465 // fold (blend A, B, allZeros) -> A
23466 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23468 // fold (blend A, B, allOnes) -> B
23469 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23472 // Simplify the case where the mask is a constant i32 value.
23473 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23474 if (C->isNullValue())
23476 if (C->isAllOnesValue())
23485 /// PerformMulCombine - Optimize a single multiply with constant into two
23486 /// in order to implement it with two cheaper instructions, e.g.
23487 /// LEA + SHL, LEA + LEA.
23488 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23489 TargetLowering::DAGCombinerInfo &DCI) {
23490 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23493 EVT VT = N->getValueType(0);
23494 if (VT != MVT::i64 && VT != MVT::i32)
23497 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23500 uint64_t MulAmt = C->getZExtValue();
23501 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23504 uint64_t MulAmt1 = 0;
23505 uint64_t MulAmt2 = 0;
23506 if ((MulAmt % 9) == 0) {
23508 MulAmt2 = MulAmt / 9;
23509 } else if ((MulAmt % 5) == 0) {
23511 MulAmt2 = MulAmt / 5;
23512 } else if ((MulAmt % 3) == 0) {
23514 MulAmt2 = MulAmt / 3;
23517 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23520 if (isPowerOf2_64(MulAmt2) &&
23521 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23522 // If second multiplifer is pow2, issue it first. We want the multiply by
23523 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23525 std::swap(MulAmt1, MulAmt2);
23528 if (isPowerOf2_64(MulAmt1))
23529 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23530 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23532 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23533 DAG.getConstant(MulAmt1, DL, VT));
23535 if (isPowerOf2_64(MulAmt2))
23536 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23537 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23539 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23540 DAG.getConstant(MulAmt2, DL, VT));
23542 // Do not add new nodes to DAG combiner worklist.
23543 DCI.CombineTo(N, NewMul, false);
23548 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23549 SDValue N0 = N->getOperand(0);
23550 SDValue N1 = N->getOperand(1);
23551 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23552 EVT VT = N0.getValueType();
23554 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23555 // since the result of setcc_c is all zero's or all ones.
23556 if (VT.isInteger() && !VT.isVector() &&
23557 N1C && N0.getOpcode() == ISD::AND &&
23558 N0.getOperand(1).getOpcode() == ISD::Constant) {
23559 SDValue N00 = N0.getOperand(0);
23560 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23561 ((N00.getOpcode() == ISD::ANY_EXTEND ||
23562 N00.getOpcode() == ISD::ZERO_EXTEND) &&
23563 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23564 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23565 APInt ShAmt = N1C->getAPIntValue();
23566 Mask = Mask.shl(ShAmt);
23569 return DAG.getNode(ISD::AND, DL, VT,
23570 N00, DAG.getConstant(Mask, DL, VT));
23575 // Hardware support for vector shifts is sparse which makes us scalarize the
23576 // vector operations in many cases. Also, on sandybridge ADD is faster than
23578 // (shl V, 1) -> add V,V
23579 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23580 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23581 assert(N0.getValueType().isVector() && "Invalid vector shift type");
23582 // We shift all of the values by one. In many cases we do not have
23583 // hardware support for this operation. This is better expressed as an ADD
23585 if (N1SplatC->getAPIntValue() == 1)
23586 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23592 /// \brief Returns a vector of 0s if the node in input is a vector logical
23593 /// shift by a constant amount which is known to be bigger than or equal
23594 /// to the vector element size in bits.
23595 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23596 const X86Subtarget *Subtarget) {
23597 EVT VT = N->getValueType(0);
23599 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23600 (!Subtarget->hasInt256() ||
23601 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23604 SDValue Amt = N->getOperand(1);
23606 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23607 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23608 APInt ShiftAmt = AmtSplat->getAPIntValue();
23609 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23611 // SSE2/AVX2 logical shifts always return a vector of 0s
23612 // if the shift amount is bigger than or equal to
23613 // the element size. The constant shift amount will be
23614 // encoded as a 8-bit immediate.
23615 if (ShiftAmt.trunc(8).uge(MaxAmount))
23616 return getZeroVector(VT, Subtarget, DAG, DL);
23622 /// PerformShiftCombine - Combine shifts.
23623 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23624 TargetLowering::DAGCombinerInfo &DCI,
23625 const X86Subtarget *Subtarget) {
23626 if (N->getOpcode() == ISD::SHL)
23627 if (SDValue V = PerformSHLCombine(N, DAG))
23630 // Try to fold this logical shift into a zero vector.
23631 if (N->getOpcode() != ISD::SRA)
23632 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23638 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
23639 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23640 // and friends. Likewise for OR -> CMPNEQSS.
23641 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23642 TargetLowering::DAGCombinerInfo &DCI,
23643 const X86Subtarget *Subtarget) {
23646 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23647 // we're requiring SSE2 for both.
23648 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23649 SDValue N0 = N->getOperand(0);
23650 SDValue N1 = N->getOperand(1);
23651 SDValue CMP0 = N0->getOperand(1);
23652 SDValue CMP1 = N1->getOperand(1);
23655 // The SETCCs should both refer to the same CMP.
23656 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23659 SDValue CMP00 = CMP0->getOperand(0);
23660 SDValue CMP01 = CMP0->getOperand(1);
23661 EVT VT = CMP00.getValueType();
23663 if (VT == MVT::f32 || VT == MVT::f64) {
23664 bool ExpectingFlags = false;
23665 // Check for any users that want flags:
23666 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23667 !ExpectingFlags && UI != UE; ++UI)
23668 switch (UI->getOpcode()) {
23673 ExpectingFlags = true;
23675 case ISD::CopyToReg:
23676 case ISD::SIGN_EXTEND:
23677 case ISD::ZERO_EXTEND:
23678 case ISD::ANY_EXTEND:
23682 if (!ExpectingFlags) {
23683 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23684 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23686 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23687 X86::CondCode tmp = cc0;
23692 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
23693 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23694 // FIXME: need symbolic constants for these magic numbers.
23695 // See X86ATTInstPrinter.cpp:printSSECC().
23696 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23697 if (Subtarget->hasAVX512()) {
23698 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23700 DAG.getConstant(x86cc, DL, MVT::i8));
23701 if (N->getValueType(0) != MVT::i1)
23702 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23706 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23707 CMP00.getValueType(), CMP00, CMP01,
23708 DAG.getConstant(x86cc, DL,
23711 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23712 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23714 if (is64BitFP && !Subtarget->is64Bit()) {
23715 // On a 32-bit target, we cannot bitcast the 64-bit float to a
23716 // 64-bit integer, since that's not a legal type. Since
23717 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23718 // bits, but can do this little dance to extract the lowest 32 bits
23719 // and work with those going forward.
23720 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23722 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23723 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23724 Vector32, DAG.getIntPtrConstant(0, DL));
23728 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23729 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23730 DAG.getConstant(1, DL, IntVT));
23731 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23733 return OneBitOfTruth;
23741 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23742 /// so it can be folded inside ANDNP.
23743 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23744 EVT VT = N->getValueType(0);
23746 // Match direct AllOnes for 128 and 256-bit vectors
23747 if (ISD::isBuildVectorAllOnes(N))
23750 // Look through a bit convert.
23751 if (N->getOpcode() == ISD::BITCAST)
23752 N = N->getOperand(0).getNode();
23754 // Sometimes the operand may come from a insert_subvector building a 256-bit
23756 if (VT.is256BitVector() &&
23757 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23758 SDValue V1 = N->getOperand(0);
23759 SDValue V2 = N->getOperand(1);
23761 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23762 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23763 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23764 ISD::isBuildVectorAllOnes(V2.getNode()))
23771 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23772 // register. In most cases we actually compare or select YMM-sized registers
23773 // and mixing the two types creates horrible code. This method optimizes
23774 // some of the transition sequences.
23775 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23776 TargetLowering::DAGCombinerInfo &DCI,
23777 const X86Subtarget *Subtarget) {
23778 EVT VT = N->getValueType(0);
23779 if (!VT.is256BitVector())
23782 assert((N->getOpcode() == ISD::ANY_EXTEND ||
23783 N->getOpcode() == ISD::ZERO_EXTEND ||
23784 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23786 SDValue Narrow = N->getOperand(0);
23787 EVT NarrowVT = Narrow->getValueType(0);
23788 if (!NarrowVT.is128BitVector())
23791 if (Narrow->getOpcode() != ISD::XOR &&
23792 Narrow->getOpcode() != ISD::AND &&
23793 Narrow->getOpcode() != ISD::OR)
23796 SDValue N0 = Narrow->getOperand(0);
23797 SDValue N1 = Narrow->getOperand(1);
23800 // The Left side has to be a trunc.
23801 if (N0.getOpcode() != ISD::TRUNCATE)
23804 // The type of the truncated inputs.
23805 EVT WideVT = N0->getOperand(0)->getValueType(0);
23809 // The right side has to be a 'trunc' or a constant vector.
23810 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23811 ConstantSDNode *RHSConstSplat = nullptr;
23812 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23813 RHSConstSplat = RHSBV->getConstantSplatNode();
23814 if (!RHSTrunc && !RHSConstSplat)
23817 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23819 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23822 // Set N0 and N1 to hold the inputs to the new wide operation.
23823 N0 = N0->getOperand(0);
23824 if (RHSConstSplat) {
23825 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23826 SDValue(RHSConstSplat, 0));
23827 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23828 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23829 } else if (RHSTrunc) {
23830 N1 = N1->getOperand(0);
23833 // Generate the wide operation.
23834 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23835 unsigned Opcode = N->getOpcode();
23837 case ISD::ANY_EXTEND:
23839 case ISD::ZERO_EXTEND: {
23840 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23841 APInt Mask = APInt::getAllOnesValue(InBits);
23842 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23843 return DAG.getNode(ISD::AND, DL, VT,
23844 Op, DAG.getConstant(Mask, DL, VT));
23846 case ISD::SIGN_EXTEND:
23847 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23848 Op, DAG.getValueType(NarrowVT));
23850 llvm_unreachable("Unexpected opcode");
23854 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23855 TargetLowering::DAGCombinerInfo &DCI,
23856 const X86Subtarget *Subtarget) {
23857 SDValue N0 = N->getOperand(0);
23858 SDValue N1 = N->getOperand(1);
23861 // A vector zext_in_reg may be represented as a shuffle,
23862 // feeding into a bitcast (this represents anyext) feeding into
23863 // an and with a mask.
23864 // We'd like to try to combine that into a shuffle with zero
23865 // plus a bitcast, removing the and.
23866 if (N0.getOpcode() != ISD::BITCAST ||
23867 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23870 // The other side of the AND should be a splat of 2^C, where C
23871 // is the number of bits in the source type.
23872 if (N1.getOpcode() == ISD::BITCAST)
23873 N1 = N1.getOperand(0);
23874 if (N1.getOpcode() != ISD::BUILD_VECTOR)
23876 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23878 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23879 EVT SrcType = Shuffle->getValueType(0);
23881 // We expect a single-source shuffle
23882 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23885 unsigned SrcSize = SrcType.getScalarSizeInBits();
23887 APInt SplatValue, SplatUndef;
23888 unsigned SplatBitSize;
23890 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23891 SplatBitSize, HasAnyUndefs))
23894 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23895 // Make sure the splat matches the mask we expect
23896 if (SplatBitSize > ResSize ||
23897 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23900 // Make sure the input and output size make sense
23901 if (SrcSize >= ResSize || ResSize % SrcSize)
23904 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23905 // The number of u's between each two values depends on the ratio between
23906 // the source and dest type.
23907 unsigned ZextRatio = ResSize / SrcSize;
23908 bool IsZext = true;
23909 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23910 if (i % ZextRatio) {
23911 if (Shuffle->getMaskElt(i) > 0) {
23917 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23918 // Expected element number
23928 // Ok, perform the transformation - replace the shuffle with
23929 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23930 // (instead of undef) where the k elements come from the zero vector.
23931 SmallVector<int, 8> Mask;
23932 unsigned NumElems = SrcType.getVectorNumElements();
23933 for (unsigned i = 0; i < NumElems; ++i)
23935 Mask.push_back(NumElems);
23937 Mask.push_back(i / ZextRatio);
23939 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23940 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23941 return DAG.getBitcast(N0.getValueType(), NewShuffle);
23944 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23945 TargetLowering::DAGCombinerInfo &DCI,
23946 const X86Subtarget *Subtarget) {
23947 if (DCI.isBeforeLegalizeOps())
23950 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23953 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23956 EVT VT = N->getValueType(0);
23957 SDValue N0 = N->getOperand(0);
23958 SDValue N1 = N->getOperand(1);
23961 // Create BEXTR instructions
23962 // BEXTR is ((X >> imm) & (2**size-1))
23963 if (VT == MVT::i32 || VT == MVT::i64) {
23964 // Check for BEXTR.
23965 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23966 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23967 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23968 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23969 if (MaskNode && ShiftNode) {
23970 uint64_t Mask = MaskNode->getZExtValue();
23971 uint64_t Shift = ShiftNode->getZExtValue();
23972 if (isMask_64(Mask)) {
23973 uint64_t MaskSize = countPopulation(Mask);
23974 if (Shift + MaskSize <= VT.getSizeInBits())
23975 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23976 DAG.getConstant(Shift | (MaskSize << 8), DL,
23985 // Want to form ANDNP nodes:
23986 // 1) In the hopes of then easily combining them with OR and AND nodes
23987 // to form PBLEND/PSIGN.
23988 // 2) To match ANDN packed intrinsics
23989 if (VT != MVT::v2i64 && VT != MVT::v4i64)
23992 // Check LHS for vnot
23993 if (N0.getOpcode() == ISD::XOR &&
23994 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23995 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23996 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23998 // Check RHS for vnot
23999 if (N1.getOpcode() == ISD::XOR &&
24000 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24001 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24002 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24007 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24008 TargetLowering::DAGCombinerInfo &DCI,
24009 const X86Subtarget *Subtarget) {
24010 if (DCI.isBeforeLegalizeOps())
24013 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24016 SDValue N0 = N->getOperand(0);
24017 SDValue N1 = N->getOperand(1);
24018 EVT VT = N->getValueType(0);
24020 // look for psign/blend
24021 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24022 if (!Subtarget->hasSSSE3() ||
24023 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24026 // Canonicalize pandn to RHS
24027 if (N0.getOpcode() == X86ISD::ANDNP)
24029 // or (and (m, y), (pandn m, x))
24030 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24031 SDValue Mask = N1.getOperand(0);
24032 SDValue X = N1.getOperand(1);
24034 if (N0.getOperand(0) == Mask)
24035 Y = N0.getOperand(1);
24036 if (N0.getOperand(1) == Mask)
24037 Y = N0.getOperand(0);
24039 // Check to see if the mask appeared in both the AND and ANDNP and
24043 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24044 // Look through mask bitcast.
24045 if (Mask.getOpcode() == ISD::BITCAST)
24046 Mask = Mask.getOperand(0);
24047 if (X.getOpcode() == ISD::BITCAST)
24048 X = X.getOperand(0);
24049 if (Y.getOpcode() == ISD::BITCAST)
24050 Y = Y.getOperand(0);
24052 EVT MaskVT = Mask.getValueType();
24054 // Validate that the Mask operand is a vector sra node.
24055 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24056 // there is no psrai.b
24057 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24058 unsigned SraAmt = ~0;
24059 if (Mask.getOpcode() == ISD::SRA) {
24060 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24061 if (auto *AmtConst = AmtBV->getConstantSplatNode())
24062 SraAmt = AmtConst->getZExtValue();
24063 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24064 SDValue SraC = Mask.getOperand(1);
24065 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
24067 if ((SraAmt + 1) != EltBits)
24072 // Now we know we at least have a plendvb with the mask val. See if
24073 // we can form a psignb/w/d.
24074 // psign = x.type == y.type == mask.type && y = sub(0, x);
24075 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24076 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24077 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24078 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24079 "Unsupported VT for PSIGN");
24080 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24081 return DAG.getBitcast(VT, Mask);
24083 // PBLENDVB only available on SSE 4.1
24084 if (!Subtarget->hasSSE41())
24087 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24089 X = DAG.getBitcast(BlendVT, X);
24090 Y = DAG.getBitcast(BlendVT, Y);
24091 Mask = DAG.getBitcast(BlendVT, Mask);
24092 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24093 return DAG.getBitcast(VT, Mask);
24097 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24100 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24101 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24103 // SHLD/SHRD instructions have lower register pressure, but on some
24104 // platforms they have higher latency than the equivalent
24105 // series of shifts/or that would otherwise be generated.
24106 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24107 // have higher latencies and we are not optimizing for size.
24108 if (!OptForSize && Subtarget->isSHLDSlow())
24111 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24113 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24115 if (!N0.hasOneUse() || !N1.hasOneUse())
24118 SDValue ShAmt0 = N0.getOperand(1);
24119 if (ShAmt0.getValueType() != MVT::i8)
24121 SDValue ShAmt1 = N1.getOperand(1);
24122 if (ShAmt1.getValueType() != MVT::i8)
24124 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24125 ShAmt0 = ShAmt0.getOperand(0);
24126 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24127 ShAmt1 = ShAmt1.getOperand(0);
24130 unsigned Opc = X86ISD::SHLD;
24131 SDValue Op0 = N0.getOperand(0);
24132 SDValue Op1 = N1.getOperand(0);
24133 if (ShAmt0.getOpcode() == ISD::SUB) {
24134 Opc = X86ISD::SHRD;
24135 std::swap(Op0, Op1);
24136 std::swap(ShAmt0, ShAmt1);
24139 unsigned Bits = VT.getSizeInBits();
24140 if (ShAmt1.getOpcode() == ISD::SUB) {
24141 SDValue Sum = ShAmt1.getOperand(0);
24142 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24143 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24144 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24145 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24146 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24147 return DAG.getNode(Opc, DL, VT,
24149 DAG.getNode(ISD::TRUNCATE, DL,
24152 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24153 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24155 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24156 return DAG.getNode(Opc, DL, VT,
24157 N0.getOperand(0), N1.getOperand(0),
24158 DAG.getNode(ISD::TRUNCATE, DL,
24165 // Generate NEG and CMOV for integer abs.
24166 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24167 EVT VT = N->getValueType(0);
24169 // Since X86 does not have CMOV for 8-bit integer, we don't convert
24170 // 8-bit integer abs to NEG and CMOV.
24171 if (VT.isInteger() && VT.getSizeInBits() == 8)
24174 SDValue N0 = N->getOperand(0);
24175 SDValue N1 = N->getOperand(1);
24178 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24179 // and change it to SUB and CMOV.
24180 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24181 N0.getOpcode() == ISD::ADD &&
24182 N0.getOperand(1) == N1 &&
24183 N1.getOpcode() == ISD::SRA &&
24184 N1.getOperand(0) == N0.getOperand(0))
24185 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24186 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24187 // Generate SUB & CMOV.
24188 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24189 DAG.getConstant(0, DL, VT), N0.getOperand(0));
24191 SDValue Ops[] = { N0.getOperand(0), Neg,
24192 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24193 SDValue(Neg.getNode(), 1) };
24194 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24199 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
24200 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24201 TargetLowering::DAGCombinerInfo &DCI,
24202 const X86Subtarget *Subtarget) {
24203 if (DCI.isBeforeLegalizeOps())
24206 if (Subtarget->hasCMov())
24207 if (SDValue RV = performIntegerAbsCombine(N, DAG))
24213 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24214 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24215 TargetLowering::DAGCombinerInfo &DCI,
24216 const X86Subtarget *Subtarget) {
24217 LoadSDNode *Ld = cast<LoadSDNode>(N);
24218 EVT RegVT = Ld->getValueType(0);
24219 EVT MemVT = Ld->getMemoryVT();
24221 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24223 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24224 // into two 16-byte operations.
24225 ISD::LoadExtType Ext = Ld->getExtensionType();
24226 unsigned Alignment = Ld->getAlignment();
24227 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24228 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24229 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24230 unsigned NumElems = RegVT.getVectorNumElements();
24234 SDValue Ptr = Ld->getBasePtr();
24235 SDValue Increment =
24236 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24238 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24240 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24241 Ld->getPointerInfo(), Ld->isVolatile(),
24242 Ld->isNonTemporal(), Ld->isInvariant(),
24244 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24245 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24246 Ld->getPointerInfo(), Ld->isVolatile(),
24247 Ld->isNonTemporal(), Ld->isInvariant(),
24248 std::min(16U, Alignment));
24249 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24251 Load2.getValue(1));
24253 SDValue NewVec = DAG.getUNDEF(RegVT);
24254 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24255 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24256 return DCI.CombineTo(N, NewVec, TF, true);
24262 /// PerformMLOADCombine - Resolve extending loads
24263 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24264 TargetLowering::DAGCombinerInfo &DCI,
24265 const X86Subtarget *Subtarget) {
24266 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24267 if (Mld->getExtensionType() != ISD::SEXTLOAD)
24270 EVT VT = Mld->getValueType(0);
24271 unsigned NumElems = VT.getVectorNumElements();
24272 EVT LdVT = Mld->getMemoryVT();
24275 assert(LdVT != VT && "Cannot extend to the same type");
24276 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24277 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24278 // From, To sizes and ElemCount must be pow of two
24279 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24280 "Unexpected size for extending masked load");
24282 unsigned SizeRatio = ToSz / FromSz;
24283 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24285 // Create a type on which we perform the shuffle
24286 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24287 LdVT.getScalarType(), NumElems*SizeRatio);
24288 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24290 // Convert Src0 value
24291 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24292 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24293 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24294 for (unsigned i = 0; i != NumElems; ++i)
24295 ShuffleVec[i] = i * SizeRatio;
24297 // Can't shuffle using an illegal type.
24298 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24299 && "WideVecVT should be legal");
24300 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24301 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24303 // Prepare the new mask
24305 SDValue Mask = Mld->getMask();
24306 if (Mask.getValueType() == VT) {
24307 // Mask and original value have the same type
24308 NewMask = DAG.getBitcast(WideVecVT, Mask);
24309 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24310 for (unsigned i = 0; i != NumElems; ++i)
24311 ShuffleVec[i] = i * SizeRatio;
24312 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24313 ShuffleVec[i] = NumElems*SizeRatio;
24314 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24315 DAG.getConstant(0, dl, WideVecVT),
24319 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24320 unsigned WidenNumElts = NumElems*SizeRatio;
24321 unsigned MaskNumElts = VT.getVectorNumElements();
24322 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24325 unsigned NumConcat = WidenNumElts / MaskNumElts;
24326 SmallVector<SDValue, 16> Ops(NumConcat);
24327 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24329 for (unsigned i = 1; i != NumConcat; ++i)
24332 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24335 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24336 Mld->getBasePtr(), NewMask, WideSrc0,
24337 Mld->getMemoryVT(), Mld->getMemOperand(),
24339 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24340 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24343 /// PerformMSTORECombine - Resolve truncating stores
24344 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24345 const X86Subtarget *Subtarget) {
24346 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24347 if (!Mst->isTruncatingStore())
24350 EVT VT = Mst->getValue().getValueType();
24351 unsigned NumElems = VT.getVectorNumElements();
24352 EVT StVT = Mst->getMemoryVT();
24355 assert(StVT != VT && "Cannot truncate to the same type");
24356 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24357 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24359 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24361 // The truncating store is legal in some cases. For example
24362 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24363 // are designated for truncate store.
24364 // In this case we don't need any further transformations.
24365 if (TLI.isTruncStoreLegal(VT, StVT))
24368 // From, To sizes and ElemCount must be pow of two
24369 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24370 "Unexpected size for truncating masked store");
24371 // We are going to use the original vector elt for storing.
24372 // Accumulated smaller vector elements must be a multiple of the store size.
24373 assert (((NumElems * FromSz) % ToSz) == 0 &&
24374 "Unexpected ratio for truncating masked store");
24376 unsigned SizeRatio = FromSz / ToSz;
24377 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24379 // Create a type on which we perform the shuffle
24380 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24381 StVT.getScalarType(), NumElems*SizeRatio);
24383 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24385 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24386 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24387 for (unsigned i = 0; i != NumElems; ++i)
24388 ShuffleVec[i] = i * SizeRatio;
24390 // Can't shuffle using an illegal type.
24391 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24392 && "WideVecVT should be legal");
24394 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24395 DAG.getUNDEF(WideVecVT),
24399 SDValue Mask = Mst->getMask();
24400 if (Mask.getValueType() == VT) {
24401 // Mask and original value have the same type
24402 NewMask = DAG.getBitcast(WideVecVT, Mask);
24403 for (unsigned i = 0; i != NumElems; ++i)
24404 ShuffleVec[i] = i * SizeRatio;
24405 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24406 ShuffleVec[i] = NumElems*SizeRatio;
24407 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24408 DAG.getConstant(0, dl, WideVecVT),
24412 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24413 unsigned WidenNumElts = NumElems*SizeRatio;
24414 unsigned MaskNumElts = VT.getVectorNumElements();
24415 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24418 unsigned NumConcat = WidenNumElts / MaskNumElts;
24419 SmallVector<SDValue, 16> Ops(NumConcat);
24420 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24422 for (unsigned i = 1; i != NumConcat; ++i)
24425 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24428 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24429 NewMask, StVT, Mst->getMemOperand(), false);
24431 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24432 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24433 const X86Subtarget *Subtarget) {
24434 StoreSDNode *St = cast<StoreSDNode>(N);
24435 EVT VT = St->getValue().getValueType();
24436 EVT StVT = St->getMemoryVT();
24438 SDValue StoredVal = St->getOperand(1);
24439 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24441 // If we are saving a concatenation of two XMM registers and 32-byte stores
24442 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24443 unsigned Alignment = St->getAlignment();
24444 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24445 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24446 StVT == VT && !IsAligned) {
24447 unsigned NumElems = VT.getVectorNumElements();
24451 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24452 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24455 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24456 SDValue Ptr0 = St->getBasePtr();
24457 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24459 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24460 St->getPointerInfo(), St->isVolatile(),
24461 St->isNonTemporal(), Alignment);
24462 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24463 St->getPointerInfo(), St->isVolatile(),
24464 St->isNonTemporal(),
24465 std::min(16U, Alignment));
24466 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24469 // Optimize trunc store (of multiple scalars) to shuffle and store.
24470 // First, pack all of the elements in one place. Next, store to memory
24471 // in fewer chunks.
24472 if (St->isTruncatingStore() && VT.isVector()) {
24473 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24474 unsigned NumElems = VT.getVectorNumElements();
24475 assert(StVT != VT && "Cannot truncate to the same type");
24476 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24477 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24479 // The truncating store is legal in some cases. For example
24480 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24481 // are designated for truncate store.
24482 // In this case we don't need any further transformations.
24483 if (TLI.isTruncStoreLegal(VT, StVT))
24486 // From, To sizes and ElemCount must be pow of two
24487 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24488 // We are going to use the original vector elt for storing.
24489 // Accumulated smaller vector elements must be a multiple of the store size.
24490 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24492 unsigned SizeRatio = FromSz / ToSz;
24494 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24496 // Create a type on which we perform the shuffle
24497 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24498 StVT.getScalarType(), NumElems*SizeRatio);
24500 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24502 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24503 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24504 for (unsigned i = 0; i != NumElems; ++i)
24505 ShuffleVec[i] = i * SizeRatio;
24507 // Can't shuffle using an illegal type.
24508 if (!TLI.isTypeLegal(WideVecVT))
24511 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24512 DAG.getUNDEF(WideVecVT),
24514 // At this point all of the data is stored at the bottom of the
24515 // register. We now need to save it to mem.
24517 // Find the largest store unit
24518 MVT StoreType = MVT::i8;
24519 for (MVT Tp : MVT::integer_valuetypes()) {
24520 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24524 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24525 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24526 (64 <= NumElems * ToSz))
24527 StoreType = MVT::f64;
24529 // Bitcast the original vector into a vector of store-size units
24530 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24531 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24532 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24533 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24534 SmallVector<SDValue, 8> Chains;
24535 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24536 TLI.getPointerTy(DAG.getDataLayout()));
24537 SDValue Ptr = St->getBasePtr();
24539 // Perform one or more big stores into memory.
24540 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24541 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24542 StoreType, ShuffWide,
24543 DAG.getIntPtrConstant(i, dl));
24544 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24545 St->getPointerInfo(), St->isVolatile(),
24546 St->isNonTemporal(), St->getAlignment());
24547 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24548 Chains.push_back(Ch);
24551 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24554 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
24555 // the FP state in cases where an emms may be missing.
24556 // A preferable solution to the general problem is to figure out the right
24557 // places to insert EMMS. This qualifies as a quick hack.
24559 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24560 if (VT.getSizeInBits() != 64)
24563 const Function *F = DAG.getMachineFunction().getFunction();
24564 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24566 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24567 if ((VT.isVector() ||
24568 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24569 isa<LoadSDNode>(St->getValue()) &&
24570 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24571 St->getChain().hasOneUse() && !St->isVolatile()) {
24572 SDNode* LdVal = St->getValue().getNode();
24573 LoadSDNode *Ld = nullptr;
24574 int TokenFactorIndex = -1;
24575 SmallVector<SDValue, 8> Ops;
24576 SDNode* ChainVal = St->getChain().getNode();
24577 // Must be a store of a load. We currently handle two cases: the load
24578 // is a direct child, and it's under an intervening TokenFactor. It is
24579 // possible to dig deeper under nested TokenFactors.
24580 if (ChainVal == LdVal)
24581 Ld = cast<LoadSDNode>(St->getChain());
24582 else if (St->getValue().hasOneUse() &&
24583 ChainVal->getOpcode() == ISD::TokenFactor) {
24584 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24585 if (ChainVal->getOperand(i).getNode() == LdVal) {
24586 TokenFactorIndex = i;
24587 Ld = cast<LoadSDNode>(St->getValue());
24589 Ops.push_back(ChainVal->getOperand(i));
24593 if (!Ld || !ISD::isNormalLoad(Ld))
24596 // If this is not the MMX case, i.e. we are just turning i64 load/store
24597 // into f64 load/store, avoid the transformation if there are multiple
24598 // uses of the loaded value.
24599 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24604 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24605 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24607 if (Subtarget->is64Bit() || F64IsLegal) {
24608 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24609 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24610 Ld->getPointerInfo(), Ld->isVolatile(),
24611 Ld->isNonTemporal(), Ld->isInvariant(),
24612 Ld->getAlignment());
24613 SDValue NewChain = NewLd.getValue(1);
24614 if (TokenFactorIndex != -1) {
24615 Ops.push_back(NewChain);
24616 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24618 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24619 St->getPointerInfo(),
24620 St->isVolatile(), St->isNonTemporal(),
24621 St->getAlignment());
24624 // Otherwise, lower to two pairs of 32-bit loads / stores.
24625 SDValue LoAddr = Ld->getBasePtr();
24626 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24627 DAG.getConstant(4, LdDL, MVT::i32));
24629 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24630 Ld->getPointerInfo(),
24631 Ld->isVolatile(), Ld->isNonTemporal(),
24632 Ld->isInvariant(), Ld->getAlignment());
24633 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24634 Ld->getPointerInfo().getWithOffset(4),
24635 Ld->isVolatile(), Ld->isNonTemporal(),
24637 MinAlign(Ld->getAlignment(), 4));
24639 SDValue NewChain = LoLd.getValue(1);
24640 if (TokenFactorIndex != -1) {
24641 Ops.push_back(LoLd);
24642 Ops.push_back(HiLd);
24643 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24646 LoAddr = St->getBasePtr();
24647 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24648 DAG.getConstant(4, StDL, MVT::i32));
24650 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24651 St->getPointerInfo(),
24652 St->isVolatile(), St->isNonTemporal(),
24653 St->getAlignment());
24654 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24655 St->getPointerInfo().getWithOffset(4),
24657 St->isNonTemporal(),
24658 MinAlign(St->getAlignment(), 4));
24659 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24662 // This is similar to the above case, but here we handle a scalar 64-bit
24663 // integer store that is extracted from a vector on a 32-bit target.
24664 // If we have SSE2, then we can treat it like a floating-point double
24665 // to get past legalization. The execution dependencies fixup pass will
24666 // choose the optimal machine instruction for the store if this really is
24667 // an integer or v2f32 rather than an f64.
24668 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24669 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24670 SDValue OldExtract = St->getOperand(1);
24671 SDValue ExtOp0 = OldExtract.getOperand(0);
24672 unsigned VecSize = ExtOp0.getValueSizeInBits();
24673 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24674 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24675 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24676 BitCast, OldExtract.getOperand(1));
24677 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24678 St->getPointerInfo(), St->isVolatile(),
24679 St->isNonTemporal(), St->getAlignment());
24685 /// Return 'true' if this vector operation is "horizontal"
24686 /// and return the operands for the horizontal operation in LHS and RHS. A
24687 /// horizontal operation performs the binary operation on successive elements
24688 /// of its first operand, then on successive elements of its second operand,
24689 /// returning the resulting values in a vector. For example, if
24690 /// A = < float a0, float a1, float a2, float a3 >
24692 /// B = < float b0, float b1, float b2, float b3 >
24693 /// then the result of doing a horizontal operation on A and B is
24694 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24695 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24696 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24697 /// set to A, RHS to B, and the routine returns 'true'.
24698 /// Note that the binary operation should have the property that if one of the
24699 /// operands is UNDEF then the result is UNDEF.
24700 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24701 // Look for the following pattern: if
24702 // A = < float a0, float a1, float a2, float a3 >
24703 // B = < float b0, float b1, float b2, float b3 >
24705 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24706 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24707 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24708 // which is A horizontal-op B.
24710 // At least one of the operands should be a vector shuffle.
24711 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24712 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24715 MVT VT = LHS.getSimpleValueType();
24717 assert((VT.is128BitVector() || VT.is256BitVector()) &&
24718 "Unsupported vector type for horizontal add/sub");
24720 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24721 // operate independently on 128-bit lanes.
24722 unsigned NumElts = VT.getVectorNumElements();
24723 unsigned NumLanes = VT.getSizeInBits()/128;
24724 unsigned NumLaneElts = NumElts / NumLanes;
24725 assert((NumLaneElts % 2 == 0) &&
24726 "Vector type should have an even number of elements in each lane");
24727 unsigned HalfLaneElts = NumLaneElts/2;
24729 // View LHS in the form
24730 // LHS = VECTOR_SHUFFLE A, B, LMask
24731 // If LHS is not a shuffle then pretend it is the shuffle
24732 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24733 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24736 SmallVector<int, 16> LMask(NumElts);
24737 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24738 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24739 A = LHS.getOperand(0);
24740 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24741 B = LHS.getOperand(1);
24742 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24743 std::copy(Mask.begin(), Mask.end(), LMask.begin());
24745 if (LHS.getOpcode() != ISD::UNDEF)
24747 for (unsigned i = 0; i != NumElts; ++i)
24751 // Likewise, view RHS in the form
24752 // RHS = VECTOR_SHUFFLE C, D, RMask
24754 SmallVector<int, 16> RMask(NumElts);
24755 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24756 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24757 C = RHS.getOperand(0);
24758 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24759 D = RHS.getOperand(1);
24760 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24761 std::copy(Mask.begin(), Mask.end(), RMask.begin());
24763 if (RHS.getOpcode() != ISD::UNDEF)
24765 for (unsigned i = 0; i != NumElts; ++i)
24769 // Check that the shuffles are both shuffling the same vectors.
24770 if (!(A == C && B == D) && !(A == D && B == C))
24773 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24774 if (!A.getNode() && !B.getNode())
24777 // If A and B occur in reverse order in RHS, then "swap" them (which means
24778 // rewriting the mask).
24780 ShuffleVectorSDNode::commuteMask(RMask);
24782 // At this point LHS and RHS are equivalent to
24783 // LHS = VECTOR_SHUFFLE A, B, LMask
24784 // RHS = VECTOR_SHUFFLE A, B, RMask
24785 // Check that the masks correspond to performing a horizontal operation.
24786 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24787 for (unsigned i = 0; i != NumLaneElts; ++i) {
24788 int LIdx = LMask[i+l], RIdx = RMask[i+l];
24790 // Ignore any UNDEF components.
24791 if (LIdx < 0 || RIdx < 0 ||
24792 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24793 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24796 // Check that successive elements are being operated on. If not, this is
24797 // not a horizontal operation.
24798 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24799 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24800 if (!(LIdx == Index && RIdx == Index + 1) &&
24801 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24806 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24807 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24811 /// Do target-specific dag combines on floating point adds.
24812 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24813 const X86Subtarget *Subtarget) {
24814 EVT VT = N->getValueType(0);
24815 SDValue LHS = N->getOperand(0);
24816 SDValue RHS = N->getOperand(1);
24818 // Try to synthesize horizontal adds from adds of shuffles.
24819 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24820 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24821 isHorizontalBinOp(LHS, RHS, true))
24822 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24826 /// Do target-specific dag combines on floating point subs.
24827 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24828 const X86Subtarget *Subtarget) {
24829 EVT VT = N->getValueType(0);
24830 SDValue LHS = N->getOperand(0);
24831 SDValue RHS = N->getOperand(1);
24833 // Try to synthesize horizontal subs from subs of shuffles.
24834 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24835 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24836 isHorizontalBinOp(LHS, RHS, false))
24837 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24841 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24842 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24843 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24845 // F[X]OR(0.0, x) -> x
24846 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24847 if (C->getValueAPF().isPosZero())
24848 return N->getOperand(1);
24850 // F[X]OR(x, 0.0) -> x
24851 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24852 if (C->getValueAPF().isPosZero())
24853 return N->getOperand(0);
24857 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24858 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24859 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24861 // Only perform optimizations if UnsafeMath is used.
24862 if (!DAG.getTarget().Options.UnsafeFPMath)
24865 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24866 // into FMINC and FMAXC, which are Commutative operations.
24867 unsigned NewOp = 0;
24868 switch (N->getOpcode()) {
24869 default: llvm_unreachable("unknown opcode");
24870 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
24871 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
24874 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24875 N->getOperand(0), N->getOperand(1));
24878 /// Do target-specific dag combines on X86ISD::FAND nodes.
24879 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24880 // FAND(0.0, x) -> 0.0
24881 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24882 if (C->getValueAPF().isPosZero())
24883 return N->getOperand(0);
24885 // FAND(x, 0.0) -> 0.0
24886 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24887 if (C->getValueAPF().isPosZero())
24888 return N->getOperand(1);
24893 /// Do target-specific dag combines on X86ISD::FANDN nodes
24894 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24895 // FANDN(0.0, x) -> x
24896 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24897 if (C->getValueAPF().isPosZero())
24898 return N->getOperand(1);
24900 // FANDN(x, 0.0) -> 0.0
24901 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24902 if (C->getValueAPF().isPosZero())
24903 return N->getOperand(1);
24908 static SDValue PerformBTCombine(SDNode *N,
24910 TargetLowering::DAGCombinerInfo &DCI) {
24911 // BT ignores high bits in the bit index operand.
24912 SDValue Op1 = N->getOperand(1);
24913 if (Op1.hasOneUse()) {
24914 unsigned BitWidth = Op1.getValueSizeInBits();
24915 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24916 APInt KnownZero, KnownOne;
24917 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24918 !DCI.isBeforeLegalizeOps());
24919 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24920 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24921 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24922 DCI.CommitTargetLoweringOpt(TLO);
24927 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24928 SDValue Op = N->getOperand(0);
24929 if (Op.getOpcode() == ISD::BITCAST)
24930 Op = Op.getOperand(0);
24931 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24932 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24933 VT.getVectorElementType().getSizeInBits() ==
24934 OpVT.getVectorElementType().getSizeInBits()) {
24935 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24940 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24941 const X86Subtarget *Subtarget) {
24942 EVT VT = N->getValueType(0);
24943 if (!VT.isVector())
24946 SDValue N0 = N->getOperand(0);
24947 SDValue N1 = N->getOperand(1);
24948 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24951 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24952 // both SSE and AVX2 since there is no sign-extended shift right
24953 // operation on a vector with 64-bit elements.
24954 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24955 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24956 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24957 N0.getOpcode() == ISD::SIGN_EXTEND)) {
24958 SDValue N00 = N0.getOperand(0);
24960 // EXTLOAD has a better solution on AVX2,
24961 // it may be replaced with X86ISD::VSEXT node.
24962 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24963 if (!ISD::isNormalLoad(N00.getNode()))
24966 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24967 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24969 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24975 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24976 TargetLowering::DAGCombinerInfo &DCI,
24977 const X86Subtarget *Subtarget) {
24978 SDValue N0 = N->getOperand(0);
24979 EVT VT = N->getValueType(0);
24980 EVT SVT = VT.getScalarType();
24981 EVT InVT = N0.getValueType();
24982 EVT InSVT = InVT.getScalarType();
24985 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24986 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24987 // This exposes the sext to the sdivrem lowering, so that it directly extends
24988 // from AH (which we otherwise need to do contortions to access).
24989 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24990 InVT == MVT::i8 && VT == MVT::i32) {
24991 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24992 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24993 N0.getOperand(0), N0.getOperand(1));
24994 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24995 return R.getValue(1);
24998 if (!DCI.isBeforeLegalizeOps()) {
24999 if (InVT == MVT::i1) {
25000 SDValue Zero = DAG.getConstant(0, DL, VT);
25002 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25003 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25008 if (VT.isVector() && Subtarget->hasSSE2()) {
25009 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25010 EVT InVT = N.getValueType();
25011 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25012 Size / InVT.getScalarSizeInBits());
25013 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25014 DAG.getUNDEF(InVT));
25016 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25019 // If target-size is less than 128-bits, extend to a type that would extend
25020 // to 128 bits, extend that and extract the original target vector.
25021 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25022 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25023 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25024 unsigned Scale = 128 / VT.getSizeInBits();
25026 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25027 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25028 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25029 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25030 DAG.getIntPtrConstant(0, DL));
25033 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25034 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25035 if (VT.getSizeInBits() == 128 &&
25036 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25037 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25038 SDValue ExOp = ExtendVecSize(DL, N0, 128);
25039 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25042 // On pre-AVX2 targets, split into 128-bit nodes of
25043 // ISD::SIGN_EXTEND_VECTOR_INREG.
25044 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25045 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25046 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25047 unsigned NumVecs = VT.getSizeInBits() / 128;
25048 unsigned NumSubElts = 128 / SVT.getSizeInBits();
25049 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25050 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25052 SmallVector<SDValue, 8> Opnds;
25053 for (unsigned i = 0, Offset = 0; i != NumVecs;
25054 ++i, Offset += NumSubElts) {
25055 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25056 DAG.getIntPtrConstant(Offset, DL));
25057 SrcVec = ExtendVecSize(DL, SrcVec, 128);
25058 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25059 Opnds.push_back(SrcVec);
25061 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25065 if (!Subtarget->hasFp256())
25068 if (VT.isVector() && VT.getSizeInBits() == 256)
25069 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25075 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25076 const X86Subtarget* Subtarget) {
25078 EVT VT = N->getValueType(0);
25080 // Let legalize expand this if it isn't a legal type yet.
25081 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25084 EVT ScalarVT = VT.getScalarType();
25085 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25086 (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25087 !Subtarget->hasAVX512()))
25090 SDValue A = N->getOperand(0);
25091 SDValue B = N->getOperand(1);
25092 SDValue C = N->getOperand(2);
25094 bool NegA = (A.getOpcode() == ISD::FNEG);
25095 bool NegB = (B.getOpcode() == ISD::FNEG);
25096 bool NegC = (C.getOpcode() == ISD::FNEG);
25098 // Negative multiplication when NegA xor NegB
25099 bool NegMul = (NegA != NegB);
25101 A = A.getOperand(0);
25103 B = B.getOperand(0);
25105 C = C.getOperand(0);
25109 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25111 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25113 return DAG.getNode(Opcode, dl, VT, A, B, C);
25116 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25117 TargetLowering::DAGCombinerInfo &DCI,
25118 const X86Subtarget *Subtarget) {
25119 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
25120 // (and (i32 x86isd::setcc_carry), 1)
25121 // This eliminates the zext. This transformation is necessary because
25122 // ISD::SETCC is always legalized to i8.
25124 SDValue N0 = N->getOperand(0);
25125 EVT VT = N->getValueType(0);
25127 if (N0.getOpcode() == ISD::AND &&
25129 N0.getOperand(0).hasOneUse()) {
25130 SDValue N00 = N0.getOperand(0);
25131 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25132 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25133 if (!C || C->getZExtValue() != 1)
25135 return DAG.getNode(ISD::AND, dl, VT,
25136 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25137 N00.getOperand(0), N00.getOperand(1)),
25138 DAG.getConstant(1, dl, VT));
25142 if (N0.getOpcode() == ISD::TRUNCATE &&
25144 N0.getOperand(0).hasOneUse()) {
25145 SDValue N00 = N0.getOperand(0);
25146 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25147 return DAG.getNode(ISD::AND, dl, VT,
25148 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25149 N00.getOperand(0), N00.getOperand(1)),
25150 DAG.getConstant(1, dl, VT));
25154 if (VT.is256BitVector())
25155 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25158 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25159 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25160 // This exposes the zext to the udivrem lowering, so that it directly extends
25161 // from AH (which we otherwise need to do contortions to access).
25162 if (N0.getOpcode() == ISD::UDIVREM &&
25163 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25164 (VT == MVT::i32 || VT == MVT::i64)) {
25165 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25166 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25167 N0.getOperand(0), N0.getOperand(1));
25168 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25169 return R.getValue(1);
25175 // Optimize x == -y --> x+y == 0
25176 // x != -y --> x+y != 0
25177 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25178 const X86Subtarget* Subtarget) {
25179 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25180 SDValue LHS = N->getOperand(0);
25181 SDValue RHS = N->getOperand(1);
25182 EVT VT = N->getValueType(0);
25185 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25186 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25187 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25188 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25189 LHS.getOperand(1));
25190 return DAG.getSetCC(DL, N->getValueType(0), addV,
25191 DAG.getConstant(0, DL, addV.getValueType()), CC);
25193 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25194 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25195 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25196 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25197 RHS.getOperand(1));
25198 return DAG.getSetCC(DL, N->getValueType(0), addV,
25199 DAG.getConstant(0, DL, addV.getValueType()), CC);
25202 if (VT.getScalarType() == MVT::i1 &&
25203 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25205 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25206 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25207 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25209 if (!IsSEXT0 || !IsVZero1) {
25210 // Swap the operands and update the condition code.
25211 std::swap(LHS, RHS);
25212 CC = ISD::getSetCCSwappedOperands(CC);
25214 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25215 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25216 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25219 if (IsSEXT0 && IsVZero1) {
25220 assert(VT == LHS.getOperand(0).getValueType() &&
25221 "Uexpected operand type");
25222 if (CC == ISD::SETGT)
25223 return DAG.getConstant(0, DL, VT);
25224 if (CC == ISD::SETLE)
25225 return DAG.getConstant(1, DL, VT);
25226 if (CC == ISD::SETEQ || CC == ISD::SETGE)
25227 return DAG.getNOT(DL, LHS.getOperand(0), VT);
25229 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25230 "Unexpected condition code!");
25231 return LHS.getOperand(0);
25238 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25239 SelectionDAG &DAG) {
25241 MVT VT = Load->getSimpleValueType(0);
25242 MVT EVT = VT.getVectorElementType();
25243 SDValue Addr = Load->getOperand(1);
25244 SDValue NewAddr = DAG.getNode(
25245 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25246 DAG.getConstant(Index * EVT.getStoreSize(), dl,
25247 Addr.getSimpleValueType()));
25250 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25251 DAG.getMachineFunction().getMachineMemOperand(
25252 Load->getMemOperand(), 0, EVT.getStoreSize()));
25256 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25257 const X86Subtarget *Subtarget) {
25259 MVT VT = N->getOperand(1)->getSimpleValueType(0);
25260 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25261 "X86insertps is only defined for v4x32");
25263 SDValue Ld = N->getOperand(1);
25264 if (MayFoldLoad(Ld)) {
25265 // Extract the countS bits from the immediate so we can get the proper
25266 // address when narrowing the vector load to a specific element.
25267 // When the second source op is a memory address, insertps doesn't use
25268 // countS and just gets an f32 from that address.
25269 unsigned DestIndex =
25270 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25272 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25274 // Create this as a scalar to vector to match the instruction pattern.
25275 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25276 // countS bits are ignored when loading from memory on insertps, which
25277 // means we don't need to explicitly set them to 0.
25278 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25279 LoadScalarToVector, N->getOperand(2));
25284 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25285 SDValue V0 = N->getOperand(0);
25286 SDValue V1 = N->getOperand(1);
25288 EVT VT = N->getValueType(0);
25290 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25291 // operands and changing the mask to 1. This saves us a bunch of
25292 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25293 // x86InstrInfo knows how to commute this back after instruction selection
25294 // if it would help register allocation.
25296 // TODO: If optimizing for size or a processor that doesn't suffer from
25297 // partial register update stalls, this should be transformed into a MOVSD
25298 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25300 if (VT == MVT::v2f64)
25301 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25302 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25303 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25304 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25310 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25311 // as "sbb reg,reg", since it can be extended without zext and produces
25312 // an all-ones bit which is more useful than 0/1 in some cases.
25313 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25316 return DAG.getNode(ISD::AND, DL, VT,
25317 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25318 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25320 DAG.getConstant(1, DL, VT));
25321 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25322 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25323 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25324 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25328 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25329 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25330 TargetLowering::DAGCombinerInfo &DCI,
25331 const X86Subtarget *Subtarget) {
25333 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25334 SDValue EFLAGS = N->getOperand(1);
25336 if (CC == X86::COND_A) {
25337 // Try to convert COND_A into COND_B in an attempt to facilitate
25338 // materializing "setb reg".
25340 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25341 // cannot take an immediate as its first operand.
25343 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25344 EFLAGS.getValueType().isInteger() &&
25345 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25346 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25347 EFLAGS.getNode()->getVTList(),
25348 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25349 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25350 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25354 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25355 // a zext and produces an all-ones bit which is more useful than 0/1 in some
25357 if (CC == X86::COND_B)
25358 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25360 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25361 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25362 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25368 // Optimize branch condition evaluation.
25370 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25371 TargetLowering::DAGCombinerInfo &DCI,
25372 const X86Subtarget *Subtarget) {
25374 SDValue Chain = N->getOperand(0);
25375 SDValue Dest = N->getOperand(1);
25376 SDValue EFLAGS = N->getOperand(3);
25377 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25379 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25380 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25381 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25388 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25389 SelectionDAG &DAG) {
25390 // Take advantage of vector comparisons producing 0 or -1 in each lane to
25391 // optimize away operation when it's from a constant.
25393 // The general transformation is:
25394 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25395 // AND(VECTOR_CMP(x,y), constant2)
25396 // constant2 = UNARYOP(constant)
25398 // Early exit if this isn't a vector operation, the operand of the
25399 // unary operation isn't a bitwise AND, or if the sizes of the operations
25400 // aren't the same.
25401 EVT VT = N->getValueType(0);
25402 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25403 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25404 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25407 // Now check that the other operand of the AND is a constant. We could
25408 // make the transformation for non-constant splats as well, but it's unclear
25409 // that would be a benefit as it would not eliminate any operations, just
25410 // perform one more step in scalar code before moving to the vector unit.
25411 if (BuildVectorSDNode *BV =
25412 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25413 // Bail out if the vector isn't a constant.
25414 if (!BV->isConstant())
25417 // Everything checks out. Build up the new and improved node.
25419 EVT IntVT = BV->getValueType(0);
25420 // Create a new constant of the appropriate type for the transformed
25422 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25423 // The AND node needs bitcasts to/from an integer vector type around it.
25424 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25425 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25426 N->getOperand(0)->getOperand(0), MaskConst);
25427 SDValue Res = DAG.getBitcast(VT, NewAnd);
25434 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25435 const X86Subtarget *Subtarget) {
25436 SDValue Op0 = N->getOperand(0);
25437 EVT VT = N->getValueType(0);
25438 EVT InVT = Op0.getValueType();
25439 EVT InSVT = InVT.getScalarType();
25440 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25442 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25443 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25444 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25446 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25447 InVT.getVectorNumElements());
25448 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25450 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25451 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25453 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25459 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25460 const X86Subtarget *Subtarget) {
25461 // First try to optimize away the conversion entirely when it's
25462 // conditionally from a constant. Vectors only.
25463 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25466 // Now move on to more general possibilities.
25467 SDValue Op0 = N->getOperand(0);
25468 EVT VT = N->getValueType(0);
25469 EVT InVT = Op0.getValueType();
25470 EVT InSVT = InVT.getScalarType();
25472 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25473 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25474 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25476 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25477 InVT.getVectorNumElements());
25478 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25479 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25482 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25483 // a 32-bit target where SSE doesn't support i64->FP operations.
25484 if (Op0.getOpcode() == ISD::LOAD) {
25485 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25486 EVT LdVT = Ld->getValueType(0);
25488 // This transformation is not supported if the result type is f16
25489 if (VT == MVT::f16)
25492 if (!Ld->isVolatile() && !VT.isVector() &&
25493 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25494 !Subtarget->is64Bit() && LdVT == MVT::i64) {
25495 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25496 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25497 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25504 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25505 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25506 X86TargetLowering::DAGCombinerInfo &DCI) {
25507 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25508 // the result is either zero or one (depending on the input carry bit).
25509 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25510 if (X86::isZeroNode(N->getOperand(0)) &&
25511 X86::isZeroNode(N->getOperand(1)) &&
25512 // We don't have a good way to replace an EFLAGS use, so only do this when
25514 SDValue(N, 1).use_empty()) {
25516 EVT VT = N->getValueType(0);
25517 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25518 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25519 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25520 DAG.getConstant(X86::COND_B, DL,
25523 DAG.getConstant(1, DL, VT));
25524 return DCI.CombineTo(N, Res1, CarryOut);
25530 // fold (add Y, (sete X, 0)) -> adc 0, Y
25531 // (add Y, (setne X, 0)) -> sbb -1, Y
25532 // (sub (sete X, 0), Y) -> sbb 0, Y
25533 // (sub (setne X, 0), Y) -> adc -1, Y
25534 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25537 // Look through ZExts.
25538 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25539 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25542 SDValue SetCC = Ext.getOperand(0);
25543 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25546 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25547 if (CC != X86::COND_E && CC != X86::COND_NE)
25550 SDValue Cmp = SetCC.getOperand(1);
25551 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25552 !X86::isZeroNode(Cmp.getOperand(1)) ||
25553 !Cmp.getOperand(0).getValueType().isInteger())
25556 SDValue CmpOp0 = Cmp.getOperand(0);
25557 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25558 DAG.getConstant(1, DL, CmpOp0.getValueType()));
25560 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25561 if (CC == X86::COND_NE)
25562 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25563 DL, OtherVal.getValueType(), OtherVal,
25564 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25566 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25567 DL, OtherVal.getValueType(), OtherVal,
25568 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25571 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25572 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25573 const X86Subtarget *Subtarget) {
25574 EVT VT = N->getValueType(0);
25575 SDValue Op0 = N->getOperand(0);
25576 SDValue Op1 = N->getOperand(1);
25578 // Try to synthesize horizontal adds from adds of shuffles.
25579 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25580 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25581 isHorizontalBinOp(Op0, Op1, true))
25582 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25584 return OptimizeConditionalInDecrement(N, DAG);
25587 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25588 const X86Subtarget *Subtarget) {
25589 SDValue Op0 = N->getOperand(0);
25590 SDValue Op1 = N->getOperand(1);
25592 // X86 can't encode an immediate LHS of a sub. See if we can push the
25593 // negation into a preceding instruction.
25594 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25595 // If the RHS of the sub is a XOR with one use and a constant, invert the
25596 // immediate. Then add one to the LHS of the sub so we can turn
25597 // X-Y -> X+~Y+1, saving one register.
25598 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25599 isa<ConstantSDNode>(Op1.getOperand(1))) {
25600 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25601 EVT VT = Op0.getValueType();
25602 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25604 DAG.getConstant(~XorC, SDLoc(Op1), VT));
25605 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25606 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25610 // Try to synthesize horizontal adds from adds of shuffles.
25611 EVT VT = N->getValueType(0);
25612 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25613 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25614 isHorizontalBinOp(Op0, Op1, true))
25615 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25617 return OptimizeConditionalInDecrement(N, DAG);
25620 /// performVZEXTCombine - Performs build vector combines
25621 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25622 TargetLowering::DAGCombinerInfo &DCI,
25623 const X86Subtarget *Subtarget) {
25625 MVT VT = N->getSimpleValueType(0);
25626 SDValue Op = N->getOperand(0);
25627 MVT OpVT = Op.getSimpleValueType();
25628 MVT OpEltVT = OpVT.getVectorElementType();
25629 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25631 // (vzext (bitcast (vzext (x)) -> (vzext x)
25633 while (V.getOpcode() == ISD::BITCAST)
25634 V = V.getOperand(0);
25636 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25637 MVT InnerVT = V.getSimpleValueType();
25638 MVT InnerEltVT = InnerVT.getVectorElementType();
25640 // If the element sizes match exactly, we can just do one larger vzext. This
25641 // is always an exact type match as vzext operates on integer types.
25642 if (OpEltVT == InnerEltVT) {
25643 assert(OpVT == InnerVT && "Types must match for vzext!");
25644 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25647 // The only other way we can combine them is if only a single element of the
25648 // inner vzext is used in the input to the outer vzext.
25649 if (InnerEltVT.getSizeInBits() < InputBits)
25652 // In this case, the inner vzext is completely dead because we're going to
25653 // only look at bits inside of the low element. Just do the outer vzext on
25654 // a bitcast of the input to the inner.
25655 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25658 // Check if we can bypass extracting and re-inserting an element of an input
25659 // vector. Essentially:
25660 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25661 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25662 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25663 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25664 SDValue ExtractedV = V.getOperand(0);
25665 SDValue OrigV = ExtractedV.getOperand(0);
25666 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25667 if (ExtractIdx->getZExtValue() == 0) {
25668 MVT OrigVT = OrigV.getSimpleValueType();
25669 // Extract a subvector if necessary...
25670 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25671 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25672 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25673 OrigVT.getVectorNumElements() / Ratio);
25674 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25675 DAG.getIntPtrConstant(0, DL));
25677 Op = DAG.getBitcast(OpVT, OrigV);
25678 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25685 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25686 DAGCombinerInfo &DCI) const {
25687 SelectionDAG &DAG = DCI.DAG;
25688 switch (N->getOpcode()) {
25690 case ISD::EXTRACT_VECTOR_ELT:
25691 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25694 case X86ISD::SHRUNKBLEND:
25695 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25696 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
25697 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25698 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
25699 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
25700 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
25701 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
25704 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
25705 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
25706 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
25707 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
25708 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
25709 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25710 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
25711 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
25712 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25713 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25714 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
25715 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
25717 case X86ISD::FOR: return PerformFORCombine(N, DAG);
25719 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
25720 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
25721 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
25722 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
25723 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
25724 case ISD::ANY_EXTEND:
25725 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
25726 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
25727 case ISD::SIGN_EXTEND_INREG:
25728 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25729 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
25730 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25731 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25732 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
25733 case X86ISD::SHUFP: // Handle all target specific shuffles
25734 case X86ISD::PALIGNR:
25735 case X86ISD::UNPCKH:
25736 case X86ISD::UNPCKL:
25737 case X86ISD::MOVHLPS:
25738 case X86ISD::MOVLHPS:
25739 case X86ISD::PSHUFB:
25740 case X86ISD::PSHUFD:
25741 case X86ISD::PSHUFHW:
25742 case X86ISD::PSHUFLW:
25743 case X86ISD::MOVSS:
25744 case X86ISD::MOVSD:
25745 case X86ISD::VPERMILPI:
25746 case X86ISD::VPERM2X128:
25747 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25748 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
25749 case ISD::INTRINSIC_WO_CHAIN:
25750 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25751 case X86ISD::INSERTPS: {
25752 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25753 return PerformINSERTPSCombine(N, DAG, Subtarget);
25756 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
25762 /// isTypeDesirableForOp - Return true if the target has native support for
25763 /// the specified value type and it is 'desirable' to use the type for the
25764 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25765 /// instruction encodings are longer and some i16 instructions are slow.
25766 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25767 if (!isTypeLegal(VT))
25769 if (VT != MVT::i16)
25776 case ISD::SIGN_EXTEND:
25777 case ISD::ZERO_EXTEND:
25778 case ISD::ANY_EXTEND:
25791 /// IsDesirableToPromoteOp - This method query the target whether it is
25792 /// beneficial for dag combiner to promote the specified node. If true, it
25793 /// should return the desired promotion type by reference.
25794 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25795 EVT VT = Op.getValueType();
25796 if (VT != MVT::i16)
25799 bool Promote = false;
25800 bool Commute = false;
25801 switch (Op.getOpcode()) {
25804 LoadSDNode *LD = cast<LoadSDNode>(Op);
25805 // If the non-extending load has a single use and it's not live out, then it
25806 // might be folded.
25807 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25808 Op.hasOneUse()*/) {
25809 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25810 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25811 // The only case where we'd want to promote LOAD (rather then it being
25812 // promoted as an operand is when it's only use is liveout.
25813 if (UI->getOpcode() != ISD::CopyToReg)
25820 case ISD::SIGN_EXTEND:
25821 case ISD::ZERO_EXTEND:
25822 case ISD::ANY_EXTEND:
25827 SDValue N0 = Op.getOperand(0);
25828 // Look out for (store (shl (load), x)).
25829 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25842 SDValue N0 = Op.getOperand(0);
25843 SDValue N1 = Op.getOperand(1);
25844 if (!Commute && MayFoldLoad(N1))
25846 // Avoid disabling potential load folding opportunities.
25847 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25849 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25859 //===----------------------------------------------------------------------===//
25860 // X86 Inline Assembly Support
25861 //===----------------------------------------------------------------------===//
25863 // Helper to match a string separated by whitespace.
25864 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25865 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25867 for (StringRef Piece : Pieces) {
25868 if (!S.startswith(Piece)) // Check if the piece matches.
25871 S = S.substr(Piece.size());
25872 StringRef::size_type Pos = S.find_first_not_of(" \t");
25873 if (Pos == 0) // We matched a prefix.
25882 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25884 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25885 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25886 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25887 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25889 if (AsmPieces.size() == 3)
25891 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25898 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25899 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25901 std::string AsmStr = IA->getAsmString();
25903 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25904 if (!Ty || Ty->getBitWidth() % 16 != 0)
25907 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25908 SmallVector<StringRef, 4> AsmPieces;
25909 SplitString(AsmStr, AsmPieces, ";\n");
25911 switch (AsmPieces.size()) {
25912 default: return false;
25914 // FIXME: this should verify that we are targeting a 486 or better. If not,
25915 // we will turn this bswap into something that will be lowered to logical
25916 // ops instead of emitting the bswap asm. For now, we don't support 486 or
25917 // lower so don't worry about this.
25919 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25920 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25921 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25922 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25923 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25924 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25925 // No need to check constraints, nothing other than the equivalent of
25926 // "=r,0" would be valid here.
25927 return IntrinsicLowering::LowerToByteSwap(CI);
25930 // rorw $$8, ${0:w} --> llvm.bswap.i16
25931 if (CI->getType()->isIntegerTy(16) &&
25932 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25933 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25934 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25936 StringRef ConstraintsStr = IA->getConstraintString();
25937 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25938 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25939 if (clobbersFlagRegisters(AsmPieces))
25940 return IntrinsicLowering::LowerToByteSwap(CI);
25944 if (CI->getType()->isIntegerTy(32) &&
25945 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25946 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25947 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25948 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25950 StringRef ConstraintsStr = IA->getConstraintString();
25951 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25952 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25953 if (clobbersFlagRegisters(AsmPieces))
25954 return IntrinsicLowering::LowerToByteSwap(CI);
25957 if (CI->getType()->isIntegerTy(64)) {
25958 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25959 if (Constraints.size() >= 2 &&
25960 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25961 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25962 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
25963 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25964 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25965 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25966 return IntrinsicLowering::LowerToByteSwap(CI);
25974 /// getConstraintType - Given a constraint letter, return the type of
25975 /// constraint it is for this target.
25976 X86TargetLowering::ConstraintType
25977 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25978 if (Constraint.size() == 1) {
25979 switch (Constraint[0]) {
25990 return C_RegisterClass;
26014 return TargetLowering::getConstraintType(Constraint);
26017 /// Examine constraint type and operand type and determine a weight value.
26018 /// This object must already have been set up with the operand type
26019 /// and the current alternative constraint selected.
26020 TargetLowering::ConstraintWeight
26021 X86TargetLowering::getSingleConstraintMatchWeight(
26022 AsmOperandInfo &info, const char *constraint) const {
26023 ConstraintWeight weight = CW_Invalid;
26024 Value *CallOperandVal = info.CallOperandVal;
26025 // If we don't have a value, we can't do a match,
26026 // but allow it at the lowest weight.
26027 if (!CallOperandVal)
26029 Type *type = CallOperandVal->getType();
26030 // Look at the constraint type.
26031 switch (*constraint) {
26033 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26044 if (CallOperandVal->getType()->isIntegerTy())
26045 weight = CW_SpecificReg;
26050 if (type->isFloatingPointTy())
26051 weight = CW_SpecificReg;
26054 if (type->isX86_MMXTy() && Subtarget->hasMMX())
26055 weight = CW_SpecificReg;
26059 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26060 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26061 weight = CW_Register;
26064 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26065 if (C->getZExtValue() <= 31)
26066 weight = CW_Constant;
26070 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26071 if (C->getZExtValue() <= 63)
26072 weight = CW_Constant;
26076 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26077 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26078 weight = CW_Constant;
26082 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26083 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26084 weight = CW_Constant;
26088 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26089 if (C->getZExtValue() <= 3)
26090 weight = CW_Constant;
26094 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26095 if (C->getZExtValue() <= 0xff)
26096 weight = CW_Constant;
26101 if (isa<ConstantFP>(CallOperandVal)) {
26102 weight = CW_Constant;
26106 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26107 if ((C->getSExtValue() >= -0x80000000LL) &&
26108 (C->getSExtValue() <= 0x7fffffffLL))
26109 weight = CW_Constant;
26113 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26114 if (C->getZExtValue() <= 0xffffffff)
26115 weight = CW_Constant;
26122 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26123 /// with another that has more specific requirements based on the type of the
26124 /// corresponding operand.
26125 const char *X86TargetLowering::
26126 LowerXConstraint(EVT ConstraintVT) const {
26127 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26128 // 'f' like normal targets.
26129 if (ConstraintVT.isFloatingPoint()) {
26130 if (Subtarget->hasSSE2())
26132 if (Subtarget->hasSSE1())
26136 return TargetLowering::LowerXConstraint(ConstraintVT);
26139 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26140 /// vector. If it is invalid, don't add anything to Ops.
26141 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26142 std::string &Constraint,
26143 std::vector<SDValue>&Ops,
26144 SelectionDAG &DAG) const {
26147 // Only support length 1 constraints for now.
26148 if (Constraint.length() > 1) return;
26150 char ConstraintLetter = Constraint[0];
26151 switch (ConstraintLetter) {
26154 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26155 if (C->getZExtValue() <= 31) {
26156 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26157 Op.getValueType());
26163 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26164 if (C->getZExtValue() <= 63) {
26165 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26166 Op.getValueType());
26172 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26173 if (isInt<8>(C->getSExtValue())) {
26174 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26175 Op.getValueType());
26181 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26182 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26183 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26184 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26185 Op.getValueType());
26191 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26192 if (C->getZExtValue() <= 3) {
26193 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26194 Op.getValueType());
26200 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26201 if (C->getZExtValue() <= 255) {
26202 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26203 Op.getValueType());
26209 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26210 if (C->getZExtValue() <= 127) {
26211 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26212 Op.getValueType());
26218 // 32-bit signed value
26219 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26220 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26221 C->getSExtValue())) {
26222 // Widen to 64 bits here to get it sign extended.
26223 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26226 // FIXME gcc accepts some relocatable values here too, but only in certain
26227 // memory models; it's complicated.
26232 // 32-bit unsigned value
26233 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26234 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26235 C->getZExtValue())) {
26236 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26237 Op.getValueType());
26241 // FIXME gcc accepts some relocatable values here too, but only in certain
26242 // memory models; it's complicated.
26246 // Literal immediates are always ok.
26247 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26248 // Widen to 64 bits here to get it sign extended.
26249 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26253 // In any sort of PIC mode addresses need to be computed at runtime by
26254 // adding in a register or some sort of table lookup. These can't
26255 // be used as immediates.
26256 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26259 // If we are in non-pic codegen mode, we allow the address of a global (with
26260 // an optional displacement) to be used with 'i'.
26261 GlobalAddressSDNode *GA = nullptr;
26262 int64_t Offset = 0;
26264 // Match either (GA), (GA+C), (GA+C1+C2), etc.
26266 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26267 Offset += GA->getOffset();
26269 } else if (Op.getOpcode() == ISD::ADD) {
26270 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26271 Offset += C->getZExtValue();
26272 Op = Op.getOperand(0);
26275 } else if (Op.getOpcode() == ISD::SUB) {
26276 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26277 Offset += -C->getZExtValue();
26278 Op = Op.getOperand(0);
26283 // Otherwise, this isn't something we can handle, reject it.
26287 const GlobalValue *GV = GA->getGlobal();
26288 // If we require an extra load to get this address, as in PIC mode, we
26289 // can't accept it.
26290 if (isGlobalStubReference(
26291 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26294 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26295 GA->getValueType(0), Offset);
26300 if (Result.getNode()) {
26301 Ops.push_back(Result);
26304 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26307 std::pair<unsigned, const TargetRegisterClass *>
26308 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26309 StringRef Constraint,
26311 // First, see if this is a constraint that directly corresponds to an LLVM
26313 if (Constraint.size() == 1) {
26314 // GCC Constraint Letters
26315 switch (Constraint[0]) {
26317 // TODO: Slight differences here in allocation order and leaving
26318 // RIP in the class. Do they matter any more here than they do
26319 // in the normal allocation?
26320 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26321 if (Subtarget->is64Bit()) {
26322 if (VT == MVT::i32 || VT == MVT::f32)
26323 return std::make_pair(0U, &X86::GR32RegClass);
26324 if (VT == MVT::i16)
26325 return std::make_pair(0U, &X86::GR16RegClass);
26326 if (VT == MVT::i8 || VT == MVT::i1)
26327 return std::make_pair(0U, &X86::GR8RegClass);
26328 if (VT == MVT::i64 || VT == MVT::f64)
26329 return std::make_pair(0U, &X86::GR64RegClass);
26332 // 32-bit fallthrough
26333 case 'Q': // Q_REGS
26334 if (VT == MVT::i32 || VT == MVT::f32)
26335 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26336 if (VT == MVT::i16)
26337 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26338 if (VT == MVT::i8 || VT == MVT::i1)
26339 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26340 if (VT == MVT::i64)
26341 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26343 case 'r': // GENERAL_REGS
26344 case 'l': // INDEX_REGS
26345 if (VT == MVT::i8 || VT == MVT::i1)
26346 return std::make_pair(0U, &X86::GR8RegClass);
26347 if (VT == MVT::i16)
26348 return std::make_pair(0U, &X86::GR16RegClass);
26349 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26350 return std::make_pair(0U, &X86::GR32RegClass);
26351 return std::make_pair(0U, &X86::GR64RegClass);
26352 case 'R': // LEGACY_REGS
26353 if (VT == MVT::i8 || VT == MVT::i1)
26354 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26355 if (VT == MVT::i16)
26356 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26357 if (VT == MVT::i32 || !Subtarget->is64Bit())
26358 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26359 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26360 case 'f': // FP Stack registers.
26361 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26362 // value to the correct fpstack register class.
26363 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26364 return std::make_pair(0U, &X86::RFP32RegClass);
26365 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26366 return std::make_pair(0U, &X86::RFP64RegClass);
26367 return std::make_pair(0U, &X86::RFP80RegClass);
26368 case 'y': // MMX_REGS if MMX allowed.
26369 if (!Subtarget->hasMMX()) break;
26370 return std::make_pair(0U, &X86::VR64RegClass);
26371 case 'Y': // SSE_REGS if SSE2 allowed
26372 if (!Subtarget->hasSSE2()) break;
26374 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26375 if (!Subtarget->hasSSE1()) break;
26377 switch (VT.SimpleTy) {
26379 // Scalar SSE types.
26382 return std::make_pair(0U, &X86::FR32RegClass);
26385 return std::make_pair(0U, &X86::FR64RegClass);
26393 return std::make_pair(0U, &X86::VR128RegClass);
26401 return std::make_pair(0U, &X86::VR256RegClass);
26406 return std::make_pair(0U, &X86::VR512RegClass);
26412 // Use the default implementation in TargetLowering to convert the register
26413 // constraint into a member of a register class.
26414 std::pair<unsigned, const TargetRegisterClass*> Res;
26415 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26417 // Not found as a standard register?
26419 // Map st(0) -> st(7) -> ST0
26420 if (Constraint.size() == 7 && Constraint[0] == '{' &&
26421 tolower(Constraint[1]) == 's' &&
26422 tolower(Constraint[2]) == 't' &&
26423 Constraint[3] == '(' &&
26424 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26425 Constraint[5] == ')' &&
26426 Constraint[6] == '}') {
26428 Res.first = X86::FP0+Constraint[4]-'0';
26429 Res.second = &X86::RFP80RegClass;
26433 // GCC allows "st(0)" to be called just plain "st".
26434 if (StringRef("{st}").equals_lower(Constraint)) {
26435 Res.first = X86::FP0;
26436 Res.second = &X86::RFP80RegClass;
26441 if (StringRef("{flags}").equals_lower(Constraint)) {
26442 Res.first = X86::EFLAGS;
26443 Res.second = &X86::CCRRegClass;
26447 // 'A' means EAX + EDX.
26448 if (Constraint == "A") {
26449 Res.first = X86::EAX;
26450 Res.second = &X86::GR32_ADRegClass;
26456 // Otherwise, check to see if this is a register class of the wrong value
26457 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26458 // turn into {ax},{dx}.
26459 // MVT::Other is used to specify clobber names.
26460 if (Res.second->hasType(VT) || VT == MVT::Other)
26461 return Res; // Correct type already, nothing to do.
26463 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26464 // return "eax". This should even work for things like getting 64bit integer
26465 // registers when given an f64 type.
26466 const TargetRegisterClass *Class = Res.second;
26467 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26468 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26469 unsigned Size = VT.getSizeInBits();
26470 MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26471 : Size == 16 ? MVT::i16
26472 : Size == 32 ? MVT::i32
26473 : Size == 64 ? MVT::i64
26475 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26477 Res.first = DestReg;
26478 Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26479 : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26480 : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26481 : &X86::GR64RegClass;
26482 assert(Res.second->contains(Res.first) && "Register in register class");
26484 // No register found/type mismatch.
26486 Res.second = nullptr;
26488 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26489 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26490 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26491 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26492 Class == &X86::VR512RegClass) {
26493 // Handle references to XMM physical registers that got mapped into the
26494 // wrong class. This can happen with constraints like {xmm0} where the
26495 // target independent register mapper will just pick the first match it can
26496 // find, ignoring the required type.
26498 if (VT == MVT::f32 || VT == MVT::i32)
26499 Res.second = &X86::FR32RegClass;
26500 else if (VT == MVT::f64 || VT == MVT::i64)
26501 Res.second = &X86::FR64RegClass;
26502 else if (X86::VR128RegClass.hasType(VT))
26503 Res.second = &X86::VR128RegClass;
26504 else if (X86::VR256RegClass.hasType(VT))
26505 Res.second = &X86::VR256RegClass;
26506 else if (X86::VR512RegClass.hasType(VT))
26507 Res.second = &X86::VR512RegClass;
26509 // Type mismatch and not a clobber: Return an error;
26511 Res.second = nullptr;
26518 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26519 const AddrMode &AM, Type *Ty,
26520 unsigned AS) const {
26521 // Scaling factors are not free at all.
26522 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26523 // will take 2 allocations in the out of order engine instead of 1
26524 // for plain addressing mode, i.e. inst (reg1).
26526 // vaddps (%rsi,%drx), %ymm0, %ymm1
26527 // Requires two allocations (one for the load, one for the computation)
26529 // vaddps (%rsi), %ymm0, %ymm1
26530 // Requires just 1 allocation, i.e., freeing allocations for other operations
26531 // and having less micro operations to execute.
26533 // For some X86 architectures, this is even worse because for instance for
26534 // stores, the complex addressing mode forces the instruction to use the
26535 // "load" ports instead of the dedicated "store" port.
26536 // E.g., on Haswell:
26537 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26538 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26539 if (isLegalAddressingMode(DL, AM, Ty, AS))
26540 // Scale represents reg2 * scale, thus account for 1
26541 // as soon as we use a second register.
26542 return AM.Scale != 0;
26546 bool X86TargetLowering::isTargetFTOL() const {
26547 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();