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);
119 if (Subtarget->isTargetDarwin()) {
120 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
121 setUseUnderscoreSetJmp(false);
122 setUseUnderscoreLongJmp(false);
123 } else if (Subtarget->isTargetWindowsGNU()) {
124 // MS runtime is weird: it exports _setjmp, but longjmp!
125 setUseUnderscoreSetJmp(true);
126 setUseUnderscoreLongJmp(false);
128 setUseUnderscoreSetJmp(true);
129 setUseUnderscoreLongJmp(true);
132 // Set up the register classes.
133 addRegisterClass(MVT::i8, &X86::GR8RegClass);
134 addRegisterClass(MVT::i16, &X86::GR16RegClass);
135 addRegisterClass(MVT::i32, &X86::GR32RegClass);
136 if (Subtarget->is64Bit())
137 addRegisterClass(MVT::i64, &X86::GR64RegClass);
139 for (MVT VT : MVT::integer_valuetypes())
140 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
142 // We don't accept any truncstore of integer registers.
143 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
144 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
145 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
146 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
147 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
148 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
150 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
152 // SETOEQ and SETUNE require checking two conditions.
153 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
154 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
155 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
156 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
157 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
158 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
160 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
162 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
163 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
164 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
166 if (Subtarget->is64Bit()) {
167 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
168 // f32/f64 are legal, f80 is custom.
169 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
171 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
172 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
173 } else if (!Subtarget->useSoftFloat()) {
174 // We have an algorithm for SSE2->double, and we turn this into a
175 // 64-bit FILD followed by conditional FADD for other targets.
176 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
177 // We have an algorithm for SSE2, and we turn this into a 64-bit
178 // FILD or VCVTUSI2SS/SD for other targets.
179 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
182 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
184 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
185 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
187 if (!Subtarget->useSoftFloat()) {
188 // SSE has no i16 to fp conversion, only i32
189 if (X86ScalarSSEf32) {
190 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
191 // f32 and f64 cases are Legal, f80 case is not
192 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
194 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
195 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
198 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
199 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
202 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
203 // are Legal, f80 is custom lowered.
204 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
205 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
207 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
209 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
210 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
212 if (X86ScalarSSEf32) {
213 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
214 // f32 and f64 cases are Legal, f80 case is not
215 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
217 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
218 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
221 // Handle FP_TO_UINT by promoting the destination to a larger signed
223 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
224 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
225 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
227 if (Subtarget->is64Bit()) {
228 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
229 // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
230 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
231 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
233 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
234 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
236 } else if (!Subtarget->useSoftFloat()) {
237 // Since AVX is a superset of SSE3, only check for SSE here.
238 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
239 // Expand FP_TO_UINT into a select.
240 // FIXME: We would like to use a Custom expander here eventually to do
241 // the optimal thing for SSE vs. the default expansion in the legalizer.
242 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
244 // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
245 // With SSE3 we can use fisttpll to convert to a signed i64; without
246 // SSE, we're stuck with a fistpll.
247 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
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);
312 if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
313 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
314 // is. We should promote the value to 64-bits to solve this.
315 // This is what the CRT headers do - `fmodf` is an inline header
316 // function casting to f64 and calling `fmod`.
317 setOperationAction(ISD::FREM , MVT::f32 , Promote);
319 setOperationAction(ISD::FREM , MVT::f32 , Expand);
322 setOperationAction(ISD::FREM , MVT::f64 , Expand);
323 setOperationAction(ISD::FREM , MVT::f80 , Expand);
324 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
326 // Promote the i8 variants and force them on up to i32 which has a shorter
328 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
329 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
330 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
331 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
332 if (Subtarget->hasBMI()) {
333 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
334 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
335 if (Subtarget->is64Bit())
336 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
338 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
339 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
340 if (Subtarget->is64Bit())
341 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
344 if (Subtarget->hasLZCNT()) {
345 // When promoting the i8 variants, force them to i32 for a shorter
347 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
348 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
349 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
350 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
351 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
352 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
353 if (Subtarget->is64Bit())
354 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
356 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
357 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
358 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
359 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
360 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
361 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
362 if (Subtarget->is64Bit()) {
363 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
364 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
368 // Special handling for half-precision floating point conversions.
369 // If we don't have F16C support, then lower half float conversions
370 // into library calls.
371 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
372 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
373 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
376 // There's never any support for operations beyond MVT::f32.
377 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
378 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
379 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
380 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
382 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
383 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
384 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
385 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
386 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
387 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
389 if (Subtarget->hasPOPCNT()) {
390 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
392 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
393 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
394 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
395 if (Subtarget->is64Bit())
396 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
399 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
401 if (!Subtarget->hasMOVBE())
402 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
404 // These should be promoted to a larger select which is supported.
405 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
406 // X86 wants to expand cmov itself.
407 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
408 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
409 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
410 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
411 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
412 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
413 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
414 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
415 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
416 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
417 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
418 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
419 if (Subtarget->is64Bit()) {
420 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
421 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
423 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
424 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
425 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
426 // support continuation, user-level threading, and etc.. As a result, no
427 // other SjLj exception interfaces are implemented and please don't build
428 // your own exception handling based on them.
429 // LLVM/Clang supports zero-cost DWARF exception handling.
430 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
431 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
434 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
435 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
436 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
437 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
438 if (Subtarget->is64Bit())
439 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
440 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
441 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
442 if (Subtarget->is64Bit()) {
443 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
444 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
445 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
446 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
447 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
449 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
450 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
451 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
452 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
453 if (Subtarget->is64Bit()) {
454 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
455 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
456 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
459 if (Subtarget->hasSSE1())
460 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
462 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
464 // Expand certain atomics
465 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
467 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
468 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
469 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
472 if (Subtarget->hasCmpxchg16b()) {
473 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
476 // FIXME - use subtarget debug flags
477 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
478 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
479 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
482 if (Subtarget->isTarget64BitLP64()) {
483 setExceptionPointerRegister(X86::RAX);
484 setExceptionSelectorRegister(X86::RDX);
486 setExceptionPointerRegister(X86::EAX);
487 setExceptionSelectorRegister(X86::EDX);
489 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
490 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
492 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
493 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
495 setOperationAction(ISD::TRAP, MVT::Other, Legal);
496 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
498 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
499 setOperationAction(ISD::VASTART , MVT::Other, Custom);
500 setOperationAction(ISD::VAEND , MVT::Other, Expand);
501 if (Subtarget->is64Bit()) {
502 setOperationAction(ISD::VAARG , MVT::Other, Custom);
503 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
505 // TargetInfo::CharPtrBuiltinVaList
506 setOperationAction(ISD::VAARG , MVT::Other, Expand);
507 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
510 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
511 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
513 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
515 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
516 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
517 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
519 if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
520 // f32 and f64 use SSE.
521 // Set up the FP register classes.
522 addRegisterClass(MVT::f32, &X86::FR32RegClass);
523 addRegisterClass(MVT::f64, &X86::FR64RegClass);
525 // Use ANDPD to simulate FABS.
526 setOperationAction(ISD::FABS , MVT::f64, Custom);
527 setOperationAction(ISD::FABS , MVT::f32, Custom);
529 // Use XORP to simulate FNEG.
530 setOperationAction(ISD::FNEG , MVT::f64, Custom);
531 setOperationAction(ISD::FNEG , MVT::f32, Custom);
533 // Use ANDPD and ORPD to simulate FCOPYSIGN.
534 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
535 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
537 // Lower this to FGETSIGNx86 plus an AND.
538 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
539 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
541 // We don't support sin/cos/fmod
542 setOperationAction(ISD::FSIN , MVT::f64, Expand);
543 setOperationAction(ISD::FCOS , MVT::f64, Expand);
544 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
545 setOperationAction(ISD::FSIN , MVT::f32, Expand);
546 setOperationAction(ISD::FCOS , MVT::f32, Expand);
547 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
549 // Expand FP immediates into loads from the stack, except for the special
551 addLegalFPImmediate(APFloat(+0.0)); // xorpd
552 addLegalFPImmediate(APFloat(+0.0f)); // xorps
553 } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
554 // Use SSE for f32, x87 for f64.
555 // Set up the FP register classes.
556 addRegisterClass(MVT::f32, &X86::FR32RegClass);
557 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
559 // Use ANDPS to simulate FABS.
560 setOperationAction(ISD::FABS , MVT::f32, Custom);
562 // Use XORP to simulate FNEG.
563 setOperationAction(ISD::FNEG , MVT::f32, Custom);
565 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
567 // Use ANDPS and ORPS to simulate FCOPYSIGN.
568 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
569 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
571 // We don't support sin/cos/fmod
572 setOperationAction(ISD::FSIN , MVT::f32, Expand);
573 setOperationAction(ISD::FCOS , MVT::f32, Expand);
574 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
576 // Special cases we handle for FP constants.
577 addLegalFPImmediate(APFloat(+0.0f)); // xorps
578 addLegalFPImmediate(APFloat(+0.0)); // FLD0
579 addLegalFPImmediate(APFloat(+1.0)); // FLD1
580 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
581 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
583 if (!TM.Options.UnsafeFPMath) {
584 setOperationAction(ISD::FSIN , MVT::f64, Expand);
585 setOperationAction(ISD::FCOS , MVT::f64, Expand);
586 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
588 } else if (!Subtarget->useSoftFloat()) {
589 // f32 and f64 in x87.
590 // Set up the FP register classes.
591 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
592 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
594 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
595 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
596 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
597 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
599 if (!TM.Options.UnsafeFPMath) {
600 setOperationAction(ISD::FSIN , MVT::f64, Expand);
601 setOperationAction(ISD::FSIN , MVT::f32, Expand);
602 setOperationAction(ISD::FCOS , MVT::f64, Expand);
603 setOperationAction(ISD::FCOS , MVT::f32, Expand);
604 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
605 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
607 addLegalFPImmediate(APFloat(+0.0)); // FLD0
608 addLegalFPImmediate(APFloat(+1.0)); // FLD1
609 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
610 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
611 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
612 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
613 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
614 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
617 // We don't support FMA.
618 setOperationAction(ISD::FMA, MVT::f64, Expand);
619 setOperationAction(ISD::FMA, MVT::f32, Expand);
621 // Long double always uses X87.
622 if (!Subtarget->useSoftFloat()) {
623 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
624 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
625 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
627 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
628 addLegalFPImmediate(TmpFlt); // FLD0
630 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
633 APFloat TmpFlt2(+1.0);
634 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
636 addLegalFPImmediate(TmpFlt2); // FLD1
637 TmpFlt2.changeSign();
638 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
641 if (!TM.Options.UnsafeFPMath) {
642 setOperationAction(ISD::FSIN , MVT::f80, Expand);
643 setOperationAction(ISD::FCOS , MVT::f80, Expand);
644 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
647 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
648 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
649 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
650 setOperationAction(ISD::FRINT, MVT::f80, Expand);
651 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
652 setOperationAction(ISD::FMA, MVT::f80, Expand);
655 // Always use a library call for pow.
656 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
657 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
658 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
660 setOperationAction(ISD::FLOG, MVT::f80, Expand);
661 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
662 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
663 setOperationAction(ISD::FEXP, MVT::f80, Expand);
664 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
665 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
666 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
668 // First set operation action for all vector types to either promote
669 // (for widening) or expand (for scalarization). Then we will selectively
670 // turn on ones that can be effectively codegen'd.
671 for (MVT VT : MVT::vector_valuetypes()) {
672 setOperationAction(ISD::ADD , VT, Expand);
673 setOperationAction(ISD::SUB , VT, Expand);
674 setOperationAction(ISD::FADD, VT, Expand);
675 setOperationAction(ISD::FNEG, VT, Expand);
676 setOperationAction(ISD::FSUB, VT, Expand);
677 setOperationAction(ISD::MUL , VT, Expand);
678 setOperationAction(ISD::FMUL, VT, Expand);
679 setOperationAction(ISD::SDIV, VT, Expand);
680 setOperationAction(ISD::UDIV, VT, Expand);
681 setOperationAction(ISD::FDIV, VT, Expand);
682 setOperationAction(ISD::SREM, VT, Expand);
683 setOperationAction(ISD::UREM, VT, Expand);
684 setOperationAction(ISD::LOAD, VT, Expand);
685 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
686 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
687 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
688 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
689 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
690 setOperationAction(ISD::FABS, VT, Expand);
691 setOperationAction(ISD::FSIN, VT, Expand);
692 setOperationAction(ISD::FSINCOS, VT, Expand);
693 setOperationAction(ISD::FCOS, VT, Expand);
694 setOperationAction(ISD::FSINCOS, VT, Expand);
695 setOperationAction(ISD::FREM, VT, Expand);
696 setOperationAction(ISD::FMA, VT, Expand);
697 setOperationAction(ISD::FPOWI, VT, Expand);
698 setOperationAction(ISD::FSQRT, VT, Expand);
699 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
700 setOperationAction(ISD::FFLOOR, VT, Expand);
701 setOperationAction(ISD::FCEIL, VT, Expand);
702 setOperationAction(ISD::FTRUNC, VT, Expand);
703 setOperationAction(ISD::FRINT, VT, Expand);
704 setOperationAction(ISD::FNEARBYINT, VT, Expand);
705 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
706 setOperationAction(ISD::MULHS, VT, Expand);
707 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
708 setOperationAction(ISD::MULHU, VT, Expand);
709 setOperationAction(ISD::SDIVREM, VT, Expand);
710 setOperationAction(ISD::UDIVREM, VT, Expand);
711 setOperationAction(ISD::FPOW, VT, Expand);
712 setOperationAction(ISD::CTPOP, VT, Expand);
713 setOperationAction(ISD::CTTZ, VT, Expand);
714 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
715 setOperationAction(ISD::CTLZ, VT, Expand);
716 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
717 setOperationAction(ISD::SHL, VT, Expand);
718 setOperationAction(ISD::SRA, VT, Expand);
719 setOperationAction(ISD::SRL, VT, Expand);
720 setOperationAction(ISD::ROTL, VT, Expand);
721 setOperationAction(ISD::ROTR, VT, Expand);
722 setOperationAction(ISD::BSWAP, VT, Expand);
723 setOperationAction(ISD::SETCC, VT, Expand);
724 setOperationAction(ISD::FLOG, VT, Expand);
725 setOperationAction(ISD::FLOG2, VT, Expand);
726 setOperationAction(ISD::FLOG10, VT, Expand);
727 setOperationAction(ISD::FEXP, VT, Expand);
728 setOperationAction(ISD::FEXP2, VT, Expand);
729 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
730 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
731 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
732 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
733 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
734 setOperationAction(ISD::TRUNCATE, VT, Expand);
735 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
736 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
737 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
738 setOperationAction(ISD::VSELECT, VT, Expand);
739 setOperationAction(ISD::SELECT_CC, VT, Expand);
740 for (MVT InnerVT : MVT::vector_valuetypes()) {
741 setTruncStoreAction(InnerVT, VT, Expand);
743 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
744 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
746 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
747 // types, we have to deal with them whether we ask for Expansion or not.
748 // Setting Expand causes its own optimisation problems though, so leave
750 if (VT.getVectorElementType() == MVT::i1)
751 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
753 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
754 // split/scalarized right now.
755 if (VT.getVectorElementType() == MVT::f16)
756 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
760 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
761 // with -msoft-float, disable use of MMX as well.
762 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
763 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
764 // No operations on x86mmx supported, everything uses intrinsics.
767 // MMX-sized vectors (other than x86mmx) are expected to be expanded
768 // into smaller operations.
769 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
770 setOperationAction(ISD::MULHS, MMXTy, Expand);
771 setOperationAction(ISD::AND, MMXTy, Expand);
772 setOperationAction(ISD::OR, MMXTy, Expand);
773 setOperationAction(ISD::XOR, MMXTy, Expand);
774 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
775 setOperationAction(ISD::SELECT, MMXTy, Expand);
776 setOperationAction(ISD::BITCAST, MMXTy, Expand);
778 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
780 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
781 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
783 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
784 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
785 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
786 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
787 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
788 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
789 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
790 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
791 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
792 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
793 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
794 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
795 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
796 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
799 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
800 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
802 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
803 // registers cannot be used even for integer operations.
804 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
805 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
806 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
807 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
809 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
810 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
811 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
812 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
813 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
814 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
815 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
816 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
817 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
818 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
819 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
820 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
821 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
822 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
823 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
824 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
825 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
826 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
827 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
828 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
829 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
830 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
831 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
833 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
834 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
835 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
836 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
838 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
839 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
840 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
841 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
843 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
844 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
845 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
846 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
847 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
849 setOperationAction(ISD::CTPOP, MVT::v16i8, Custom);
850 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
851 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
852 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
854 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
855 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
856 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
857 // ISD::CTTZ v2i64 - scalarization is faster.
858 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
859 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
860 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
861 // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
863 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
864 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
865 MVT VT = (MVT::SimpleValueType)i;
866 // Do not attempt to custom lower non-power-of-2 vectors
867 if (!isPowerOf2_32(VT.getVectorNumElements()))
869 // Do not attempt to custom lower non-128-bit vectors
870 if (!VT.is128BitVector())
872 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
873 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
874 setOperationAction(ISD::VSELECT, VT, Custom);
875 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
878 // We support custom legalizing of sext and anyext loads for specific
879 // memory vector types which we can load as a scalar (or sequence of
880 // scalars) and extend in-register to a legal 128-bit vector type. For sext
881 // loads these must work with a single scalar load.
882 for (MVT VT : MVT::integer_vector_valuetypes()) {
883 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
884 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
885 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
886 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
887 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
888 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
889 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
890 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
891 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
894 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
895 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
896 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
897 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
898 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
899 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
900 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
901 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
903 if (Subtarget->is64Bit()) {
904 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
905 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
908 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
909 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
910 MVT VT = (MVT::SimpleValueType)i;
912 // Do not attempt to promote non-128-bit vectors
913 if (!VT.is128BitVector())
916 setOperationAction(ISD::AND, VT, Promote);
917 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
918 setOperationAction(ISD::OR, VT, Promote);
919 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
920 setOperationAction(ISD::XOR, VT, Promote);
921 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
922 setOperationAction(ISD::LOAD, VT, Promote);
923 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
924 setOperationAction(ISD::SELECT, VT, Promote);
925 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
928 // Custom lower v2i64 and v2f64 selects.
929 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
930 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
931 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
932 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
934 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
935 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
937 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
939 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
940 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
941 // As there is no 64-bit GPR available, we need build a special custom
942 // sequence to convert from v2i32 to v2f32.
943 if (!Subtarget->is64Bit())
944 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
946 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
947 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
949 for (MVT VT : MVT::fp_vector_valuetypes())
950 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
952 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
953 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
954 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
957 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
958 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
959 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
960 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
961 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
962 setOperationAction(ISD::FRINT, RoundedTy, Legal);
963 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
966 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
967 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
968 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
969 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
970 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
971 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
972 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
973 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
975 // FIXME: Do we need to handle scalar-to-vector here?
976 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
978 // We directly match byte blends in the backend as they match the VSELECT
980 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
982 // SSE41 brings specific instructions for doing vector sign extend even in
983 // cases where we don't have SRA.
984 for (MVT VT : MVT::integer_vector_valuetypes()) {
985 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
986 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
987 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
990 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
991 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
992 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
993 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
994 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
995 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
996 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
998 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
999 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1000 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1001 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1002 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1003 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1005 // i8 and i16 vectors are custom because the source register and source
1006 // source memory operand types are not the same width. f32 vectors are
1007 // custom since the immediate controlling the insert encodes additional
1009 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1010 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1011 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1012 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1014 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1015 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1016 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1017 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1019 // FIXME: these should be Legal, but that's only for the case where
1020 // the index is constant. For now custom expand to deal with that.
1021 if (Subtarget->is64Bit()) {
1022 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1023 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1027 if (Subtarget->hasSSE2()) {
1028 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1029 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1030 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1032 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1033 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1035 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1036 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1038 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1039 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1041 // In the customized shift lowering, the legal cases in AVX2 will be
1043 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1044 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1046 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1047 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1049 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1050 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1053 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1054 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1055 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1056 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1057 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1058 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1059 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1061 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1062 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1063 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1065 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1066 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1067 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1068 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1069 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1070 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1071 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1072 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1073 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1074 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1075 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1076 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1078 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1079 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1080 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1081 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1082 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1083 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1084 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1085 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1086 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1087 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1088 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1089 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1091 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1092 // even though v8i16 is a legal type.
1093 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1094 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1095 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1097 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1098 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1099 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1101 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1102 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1104 for (MVT VT : MVT::fp_vector_valuetypes())
1105 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1107 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1108 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1110 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1111 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1113 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1114 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1116 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1117 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1118 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1119 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1121 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1122 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1123 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1125 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1126 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1127 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1128 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1129 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1130 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1131 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1132 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1133 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1134 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1135 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1136 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1138 setOperationAction(ISD::CTPOP, MVT::v32i8, Custom);
1139 setOperationAction(ISD::CTPOP, MVT::v16i16, Custom);
1140 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1141 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1143 setOperationAction(ISD::CTTZ, MVT::v32i8, Custom);
1144 setOperationAction(ISD::CTTZ, MVT::v16i16, Custom);
1145 setOperationAction(ISD::CTTZ, MVT::v8i32, Custom);
1146 setOperationAction(ISD::CTTZ, MVT::v4i64, Custom);
1147 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v32i8, Custom);
1148 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i16, Custom);
1149 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i32, Custom);
1150 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i64, Custom);
1152 if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1153 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1154 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1155 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1156 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1157 setOperationAction(ISD::FMA, MVT::f32, Legal);
1158 setOperationAction(ISD::FMA, MVT::f64, Legal);
1161 if (Subtarget->hasInt256()) {
1162 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1163 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1164 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1165 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1167 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1168 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1169 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1170 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1172 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1173 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1174 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1175 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1177 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1178 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1179 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1180 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1182 setOperationAction(ISD::SMAX, MVT::v32i8, Legal);
1183 setOperationAction(ISD::SMAX, MVT::v16i16, Legal);
1184 setOperationAction(ISD::SMAX, MVT::v8i32, Legal);
1185 setOperationAction(ISD::UMAX, MVT::v32i8, Legal);
1186 setOperationAction(ISD::UMAX, MVT::v16i16, Legal);
1187 setOperationAction(ISD::UMAX, MVT::v8i32, Legal);
1188 setOperationAction(ISD::SMIN, MVT::v32i8, Legal);
1189 setOperationAction(ISD::SMIN, MVT::v16i16, Legal);
1190 setOperationAction(ISD::SMIN, MVT::v8i32, Legal);
1191 setOperationAction(ISD::UMIN, MVT::v32i8, Legal);
1192 setOperationAction(ISD::UMIN, MVT::v16i16, Legal);
1193 setOperationAction(ISD::UMIN, MVT::v8i32, Legal);
1195 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1196 // when we have a 256bit-wide blend with immediate.
1197 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1199 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1200 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1201 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1202 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1203 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1204 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1205 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1207 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1208 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1209 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1210 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1211 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1212 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1214 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1215 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1216 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1217 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1219 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1220 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1221 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1222 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1224 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1225 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1226 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1227 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1229 setOperationAction(ISD::SMAX, MVT::v32i8, Custom);
1230 setOperationAction(ISD::SMAX, MVT::v16i16, Custom);
1231 setOperationAction(ISD::SMAX, MVT::v8i32, Custom);
1232 setOperationAction(ISD::UMAX, MVT::v32i8, Custom);
1233 setOperationAction(ISD::UMAX, MVT::v16i16, Custom);
1234 setOperationAction(ISD::UMAX, MVT::v8i32, Custom);
1235 setOperationAction(ISD::SMIN, MVT::v32i8, Custom);
1236 setOperationAction(ISD::SMIN, MVT::v16i16, Custom);
1237 setOperationAction(ISD::SMIN, MVT::v8i32, Custom);
1238 setOperationAction(ISD::UMIN, MVT::v32i8, Custom);
1239 setOperationAction(ISD::UMIN, MVT::v16i16, Custom);
1240 setOperationAction(ISD::UMIN, MVT::v8i32, Custom);
1243 // In the customized shift lowering, the legal cases in AVX2 will be
1245 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1246 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1248 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1249 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1251 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1252 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1254 // Custom lower several nodes for 256-bit types.
1255 for (MVT VT : MVT::vector_valuetypes()) {
1256 if (VT.getScalarSizeInBits() >= 32) {
1257 setOperationAction(ISD::MLOAD, VT, Legal);
1258 setOperationAction(ISD::MSTORE, VT, Legal);
1260 // Extract subvector is special because the value type
1261 // (result) is 128-bit but the source is 256-bit wide.
1262 if (VT.is128BitVector()) {
1263 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1265 // Do not attempt to custom lower other non-256-bit vectors
1266 if (!VT.is256BitVector())
1269 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1270 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1271 setOperationAction(ISD::VSELECT, VT, Custom);
1272 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1273 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1274 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1275 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1276 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1279 if (Subtarget->hasInt256())
1280 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1283 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1284 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1285 MVT VT = (MVT::SimpleValueType)i;
1287 // Do not attempt to promote non-256-bit vectors
1288 if (!VT.is256BitVector())
1291 setOperationAction(ISD::AND, VT, Promote);
1292 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1293 setOperationAction(ISD::OR, VT, Promote);
1294 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1295 setOperationAction(ISD::XOR, VT, Promote);
1296 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1297 setOperationAction(ISD::LOAD, VT, Promote);
1298 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1299 setOperationAction(ISD::SELECT, VT, Promote);
1300 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1304 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1305 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1306 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1307 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1308 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1310 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1311 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1312 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1314 for (MVT VT : MVT::fp_vector_valuetypes())
1315 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1317 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1318 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1319 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1320 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1321 setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1322 setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1323 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1324 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1325 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1326 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1327 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1328 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1330 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1331 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1332 setOperationAction(ISD::XOR, MVT::i1, Legal);
1333 setOperationAction(ISD::OR, MVT::i1, Legal);
1334 setOperationAction(ISD::AND, MVT::i1, Legal);
1335 setOperationAction(ISD::SUB, MVT::i1, Custom);
1336 setOperationAction(ISD::ADD, MVT::i1, Custom);
1337 setOperationAction(ISD::MUL, MVT::i1, Custom);
1338 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1339 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1340 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1341 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1342 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1344 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1345 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1346 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1347 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1348 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1349 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1351 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1352 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1353 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1354 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1355 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1356 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1357 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1358 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1360 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1361 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1362 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1363 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1364 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1365 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1366 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1367 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1368 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1369 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1370 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1371 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1372 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1373 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1374 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1375 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1377 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1378 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1379 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1380 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1381 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1382 if (Subtarget->hasVLX()){
1383 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1384 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1385 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1386 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1387 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1389 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1390 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1391 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1392 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1393 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1395 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1396 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1397 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1398 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i1, Custom);
1399 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i1, Custom);
1400 if (Subtarget->hasDQI()) {
1401 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1402 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1404 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1405 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1406 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1407 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1408 if (Subtarget->hasVLX()) {
1409 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1410 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1411 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1412 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1413 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1414 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1415 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1416 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1419 if (Subtarget->hasVLX()) {
1420 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1421 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1422 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1423 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1424 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1425 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1426 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1427 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1429 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1430 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1431 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1432 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1433 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1434 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1435 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1436 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1437 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1438 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1439 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1440 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1441 if (Subtarget->hasDQI()) {
1442 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1443 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1445 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1446 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1447 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1448 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1449 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1450 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1451 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1452 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1453 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1454 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1456 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1457 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1458 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1459 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1460 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1462 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1463 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1465 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1467 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1468 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1469 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1470 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1471 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1472 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1473 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1474 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1475 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1476 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1477 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1479 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1480 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1481 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1482 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1483 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1484 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1485 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1486 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1488 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1489 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1491 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1492 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1494 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1496 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1497 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1499 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1500 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1502 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1503 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1505 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1506 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1507 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1508 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1509 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1510 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1512 if (Subtarget->hasCDI()) {
1513 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1514 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1515 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i64, Legal);
1516 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i32, Legal);
1518 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i64, Custom);
1519 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i32, Custom);
1521 if (Subtarget->hasVLX() && Subtarget->hasCDI()) {
1522 setOperationAction(ISD::CTLZ, MVT::v4i64, Legal);
1523 setOperationAction(ISD::CTLZ, MVT::v8i32, Legal);
1524 setOperationAction(ISD::CTLZ, MVT::v2i64, Legal);
1525 setOperationAction(ISD::CTLZ, MVT::v4i32, Legal);
1526 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i64, Legal);
1527 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i32, Legal);
1528 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v2i64, Legal);
1529 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i32, Legal);
1531 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i64, Custom);
1532 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i32, Custom);
1533 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
1534 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
1536 if (Subtarget->hasDQI()) {
1537 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1538 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1539 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1541 // Custom lower several nodes.
1542 for (MVT VT : MVT::vector_valuetypes()) {
1543 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1545 setOperationAction(ISD::AND, VT, Legal);
1546 setOperationAction(ISD::OR, VT, Legal);
1547 setOperationAction(ISD::XOR, VT, Legal);
1549 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1550 setOperationAction(ISD::MGATHER, VT, Custom);
1551 setOperationAction(ISD::MSCATTER, VT, Custom);
1553 // Extract subvector is special because the value type
1554 // (result) is 256/128-bit but the source is 512-bit wide.
1555 if (VT.is128BitVector() || VT.is256BitVector()) {
1556 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1558 if (VT.getVectorElementType() == MVT::i1)
1559 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1561 // Do not attempt to custom lower other non-512-bit vectors
1562 if (!VT.is512BitVector())
1565 if (EltSize >= 32) {
1566 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1567 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1568 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1569 setOperationAction(ISD::VSELECT, VT, Legal);
1570 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1571 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1572 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1573 setOperationAction(ISD::MLOAD, VT, Legal);
1574 setOperationAction(ISD::MSTORE, VT, Legal);
1577 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1578 MVT VT = (MVT::SimpleValueType)i;
1580 // Do not attempt to promote non-512-bit vectors.
1581 if (!VT.is512BitVector())
1584 setOperationAction(ISD::SELECT, VT, Promote);
1585 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1589 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1590 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1591 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1593 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1594 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1596 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1597 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1598 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1599 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1600 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1601 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1602 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1603 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1604 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1605 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1606 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1607 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Legal);
1608 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Legal);
1609 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1610 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1611 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1612 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1613 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1614 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1615 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1616 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1617 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i16, Custom);
1618 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1619 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1620 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1621 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1622 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1623 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1624 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1625 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1626 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1627 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i1, Custom);
1628 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i1, Custom);
1630 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1631 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1632 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1633 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1634 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1635 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1636 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1637 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1639 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1640 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1641 if (Subtarget->hasVLX())
1642 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1644 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1645 const MVT VT = (MVT::SimpleValueType)i;
1647 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1649 // Do not attempt to promote non-512-bit vectors.
1650 if (!VT.is512BitVector())
1654 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1655 setOperationAction(ISD::VSELECT, VT, Legal);
1660 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1661 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1662 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1664 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1665 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1666 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1667 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1668 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1669 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1670 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1671 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1672 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1673 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1674 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i1, Custom);
1675 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i1, Custom);
1677 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1678 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1679 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1680 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1681 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1682 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1683 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1684 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1686 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1687 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1688 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1689 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1690 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1691 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1692 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1693 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1696 // We want to custom lower some of our intrinsics.
1697 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1698 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1699 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1700 if (!Subtarget->is64Bit())
1701 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1703 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1704 // handle type legalization for these operations here.
1706 // FIXME: We really should do custom legalization for addition and
1707 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1708 // than generic legalization for 64-bit multiplication-with-overflow, though.
1709 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1710 // Add/Sub/Mul with overflow operations are custom lowered.
1712 setOperationAction(ISD::SADDO, VT, Custom);
1713 setOperationAction(ISD::UADDO, VT, Custom);
1714 setOperationAction(ISD::SSUBO, VT, Custom);
1715 setOperationAction(ISD::USUBO, VT, Custom);
1716 setOperationAction(ISD::SMULO, VT, Custom);
1717 setOperationAction(ISD::UMULO, VT, Custom);
1721 if (!Subtarget->is64Bit()) {
1722 // These libcalls are not available in 32-bit.
1723 setLibcallName(RTLIB::SHL_I128, nullptr);
1724 setLibcallName(RTLIB::SRL_I128, nullptr);
1725 setLibcallName(RTLIB::SRA_I128, nullptr);
1728 // Combine sin / cos into one node or libcall if possible.
1729 if (Subtarget->hasSinCos()) {
1730 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1731 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1732 if (Subtarget->isTargetDarwin()) {
1733 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1734 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1735 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1736 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1740 if (Subtarget->isTargetWin64()) {
1741 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1742 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1743 setOperationAction(ISD::SREM, MVT::i128, Custom);
1744 setOperationAction(ISD::UREM, MVT::i128, Custom);
1745 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1746 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1749 // We have target-specific dag combine patterns for the following nodes:
1750 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1751 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1752 setTargetDAGCombine(ISD::BITCAST);
1753 setTargetDAGCombine(ISD::VSELECT);
1754 setTargetDAGCombine(ISD::SELECT);
1755 setTargetDAGCombine(ISD::SHL);
1756 setTargetDAGCombine(ISD::SRA);
1757 setTargetDAGCombine(ISD::SRL);
1758 setTargetDAGCombine(ISD::OR);
1759 setTargetDAGCombine(ISD::AND);
1760 setTargetDAGCombine(ISD::ADD);
1761 setTargetDAGCombine(ISD::FADD);
1762 setTargetDAGCombine(ISD::FSUB);
1763 setTargetDAGCombine(ISD::FMA);
1764 setTargetDAGCombine(ISD::SUB);
1765 setTargetDAGCombine(ISD::LOAD);
1766 setTargetDAGCombine(ISD::MLOAD);
1767 setTargetDAGCombine(ISD::STORE);
1768 setTargetDAGCombine(ISD::MSTORE);
1769 setTargetDAGCombine(ISD::ZERO_EXTEND);
1770 setTargetDAGCombine(ISD::ANY_EXTEND);
1771 setTargetDAGCombine(ISD::SIGN_EXTEND);
1772 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1773 setTargetDAGCombine(ISD::SINT_TO_FP);
1774 setTargetDAGCombine(ISD::UINT_TO_FP);
1775 setTargetDAGCombine(ISD::SETCC);
1776 setTargetDAGCombine(ISD::BUILD_VECTOR);
1777 setTargetDAGCombine(ISD::MUL);
1778 setTargetDAGCombine(ISD::XOR);
1780 computeRegisterProperties(Subtarget->getRegisterInfo());
1782 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1783 MaxStoresPerMemsetOptSize = 8;
1784 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1785 MaxStoresPerMemcpyOptSize = 4;
1786 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1787 MaxStoresPerMemmoveOptSize = 4;
1788 setPrefLoopAlignment(4); // 2^4 bytes.
1790 // Predictable cmov don't hurt on atom because it's in-order.
1791 PredictableSelectIsExpensive = !Subtarget->isAtom();
1792 EnableExtLdPromotion = true;
1793 setPrefFunctionAlignment(4); // 2^4 bytes.
1795 verifyIntrinsicTables();
1798 // This has so far only been implemented for 64-bit MachO.
1799 bool X86TargetLowering::useLoadStackGuardNode() const {
1800 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1803 TargetLoweringBase::LegalizeTypeAction
1804 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1805 if (ExperimentalVectorWideningLegalization &&
1806 VT.getVectorNumElements() != 1 &&
1807 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1808 return TypeWidenVector;
1810 return TargetLoweringBase::getPreferredVectorAction(VT);
1813 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1816 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1818 const unsigned NumElts = VT.getVectorNumElements();
1819 const EVT EltVT = VT.getVectorElementType();
1820 if (VT.is512BitVector()) {
1821 if (Subtarget->hasAVX512())
1822 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1823 EltVT == MVT::f32 || EltVT == MVT::f64)
1825 case 8: return MVT::v8i1;
1826 case 16: return MVT::v16i1;
1828 if (Subtarget->hasBWI())
1829 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1831 case 32: return MVT::v32i1;
1832 case 64: return MVT::v64i1;
1836 if (VT.is256BitVector() || VT.is128BitVector()) {
1837 if (Subtarget->hasVLX())
1838 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1839 EltVT == MVT::f32 || EltVT == MVT::f64)
1841 case 2: return MVT::v2i1;
1842 case 4: return MVT::v4i1;
1843 case 8: return MVT::v8i1;
1845 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1846 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1848 case 8: return MVT::v8i1;
1849 case 16: return MVT::v16i1;
1850 case 32: return MVT::v32i1;
1854 return VT.changeVectorElementTypeToInteger();
1857 /// Helper for getByValTypeAlignment to determine
1858 /// the desired ByVal argument alignment.
1859 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1862 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1863 if (VTy->getBitWidth() == 128)
1865 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1866 unsigned EltAlign = 0;
1867 getMaxByValAlign(ATy->getElementType(), EltAlign);
1868 if (EltAlign > MaxAlign)
1869 MaxAlign = EltAlign;
1870 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1871 for (auto *EltTy : STy->elements()) {
1872 unsigned EltAlign = 0;
1873 getMaxByValAlign(EltTy, EltAlign);
1874 if (EltAlign > MaxAlign)
1875 MaxAlign = EltAlign;
1882 /// Return the desired alignment for ByVal aggregate
1883 /// function arguments in the caller parameter area. For X86, aggregates
1884 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1885 /// are at 4-byte boundaries.
1886 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1887 const DataLayout &DL) const {
1888 if (Subtarget->is64Bit()) {
1889 // Max of 8 and alignment of type.
1890 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1897 if (Subtarget->hasSSE1())
1898 getMaxByValAlign(Ty, Align);
1902 /// Returns the target specific optimal type for load
1903 /// and store operations as a result of memset, memcpy, and memmove
1904 /// lowering. If DstAlign is zero that means it's safe to destination
1905 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1906 /// means there isn't a need to check it against alignment requirement,
1907 /// probably because the source does not need to be loaded. If 'IsMemset' is
1908 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1909 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1910 /// source is constant so it does not need to be loaded.
1911 /// It returns EVT::Other if the type should be determined using generic
1912 /// target-independent logic.
1914 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1915 unsigned DstAlign, unsigned SrcAlign,
1916 bool IsMemset, bool ZeroMemset,
1918 MachineFunction &MF) const {
1919 const Function *F = MF.getFunction();
1920 if ((!IsMemset || ZeroMemset) &&
1921 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1923 (!Subtarget->isUnalignedMem16Slow() ||
1924 ((DstAlign == 0 || DstAlign >= 16) &&
1925 (SrcAlign == 0 || SrcAlign >= 16)))) {
1927 // FIXME: Check if unaligned 32-byte accesses are slow.
1928 if (Subtarget->hasInt256())
1930 if (Subtarget->hasFp256())
1933 if (Subtarget->hasSSE2())
1935 if (Subtarget->hasSSE1())
1937 } else if (!MemcpyStrSrc && Size >= 8 &&
1938 !Subtarget->is64Bit() &&
1939 Subtarget->hasSSE2()) {
1940 // Do not use f64 to lower memcpy if source is string constant. It's
1941 // better to use i32 to avoid the loads.
1945 // This is a compromise. If we reach here, unaligned accesses may be slow on
1946 // this target. However, creating smaller, aligned accesses could be even
1947 // slower and would certainly be a lot more code.
1948 if (Subtarget->is64Bit() && Size >= 8)
1953 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1955 return X86ScalarSSEf32;
1956 else if (VT == MVT::f64)
1957 return X86ScalarSSEf64;
1962 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1967 switch (VT.getSizeInBits()) {
1969 // 8-byte and under are always assumed to be fast.
1973 *Fast = !Subtarget->isUnalignedMem16Slow();
1976 *Fast = !Subtarget->isUnalignedMem32Slow();
1978 // TODO: What about AVX-512 (512-bit) accesses?
1981 // Misaligned accesses of any size are always allowed.
1985 /// Return the entry encoding for a jump table in the
1986 /// current function. The returned value is a member of the
1987 /// MachineJumpTableInfo::JTEntryKind enum.
1988 unsigned X86TargetLowering::getJumpTableEncoding() const {
1989 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1991 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1992 Subtarget->isPICStyleGOT())
1993 return MachineJumpTableInfo::EK_Custom32;
1995 // Otherwise, use the normal jump table encoding heuristics.
1996 return TargetLowering::getJumpTableEncoding();
1999 bool X86TargetLowering::useSoftFloat() const {
2000 return Subtarget->useSoftFloat();
2004 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2005 const MachineBasicBlock *MBB,
2006 unsigned uid,MCContext &Ctx) const{
2007 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2008 Subtarget->isPICStyleGOT());
2009 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2011 return MCSymbolRefExpr::create(MBB->getSymbol(),
2012 MCSymbolRefExpr::VK_GOTOFF, Ctx);
2015 /// Returns relocation base for the given PIC jumptable.
2016 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2017 SelectionDAG &DAG) const {
2018 if (!Subtarget->is64Bit())
2019 // This doesn't have SDLoc associated with it, but is not really the
2020 // same as a Register.
2021 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2022 getPointerTy(DAG.getDataLayout()));
2026 /// This returns the relocation base for the given PIC jumptable,
2027 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2028 const MCExpr *X86TargetLowering::
2029 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2030 MCContext &Ctx) const {
2031 // X86-64 uses RIP relative addressing based on the jump table label.
2032 if (Subtarget->isPICStyleRIPRel())
2033 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2035 // Otherwise, the reference is relative to the PIC base.
2036 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2039 std::pair<const TargetRegisterClass *, uint8_t>
2040 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2042 const TargetRegisterClass *RRC = nullptr;
2044 switch (VT.SimpleTy) {
2046 return TargetLowering::findRepresentativeClass(TRI, VT);
2047 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2048 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2051 RRC = &X86::VR64RegClass;
2053 case MVT::f32: case MVT::f64:
2054 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2055 case MVT::v4f32: case MVT::v2f64:
2056 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2058 RRC = &X86::VR128RegClass;
2061 return std::make_pair(RRC, Cost);
2064 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2065 unsigned &Offset) const {
2066 if (!Subtarget->isTargetLinux())
2069 if (Subtarget->is64Bit()) {
2070 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2072 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2084 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2085 unsigned DestAS) const {
2086 assert(SrcAS != DestAS && "Expected different address spaces!");
2088 return SrcAS < 256 && DestAS < 256;
2091 //===----------------------------------------------------------------------===//
2092 // Return Value Calling Convention Implementation
2093 //===----------------------------------------------------------------------===//
2095 #include "X86GenCallingConv.inc"
2098 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2099 MachineFunction &MF, bool isVarArg,
2100 const SmallVectorImpl<ISD::OutputArg> &Outs,
2101 LLVMContext &Context) const {
2102 SmallVector<CCValAssign, 16> RVLocs;
2103 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2104 return CCInfo.CheckReturn(Outs, RetCC_X86);
2107 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2108 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2113 X86TargetLowering::LowerReturn(SDValue Chain,
2114 CallingConv::ID CallConv, bool isVarArg,
2115 const SmallVectorImpl<ISD::OutputArg> &Outs,
2116 const SmallVectorImpl<SDValue> &OutVals,
2117 SDLoc dl, SelectionDAG &DAG) const {
2118 MachineFunction &MF = DAG.getMachineFunction();
2119 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2121 SmallVector<CCValAssign, 16> RVLocs;
2122 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2123 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2126 SmallVector<SDValue, 6> RetOps;
2127 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2128 // Operand #1 = Bytes To Pop
2129 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2132 // Copy the result values into the output registers.
2133 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2134 CCValAssign &VA = RVLocs[i];
2135 assert(VA.isRegLoc() && "Can only return in registers!");
2136 SDValue ValToCopy = OutVals[i];
2137 EVT ValVT = ValToCopy.getValueType();
2139 // Promote values to the appropriate types.
2140 if (VA.getLocInfo() == CCValAssign::SExt)
2141 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2142 else if (VA.getLocInfo() == CCValAssign::ZExt)
2143 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2144 else if (VA.getLocInfo() == CCValAssign::AExt) {
2145 if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2146 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2148 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2150 else if (VA.getLocInfo() == CCValAssign::BCvt)
2151 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2153 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2154 "Unexpected FP-extend for return value.");
2156 // If this is x86-64, and we disabled SSE, we can't return FP values,
2157 // or SSE or MMX vectors.
2158 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2159 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2160 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2161 report_fatal_error("SSE register return with SSE disabled");
2163 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2164 // llvm-gcc has never done it right and no one has noticed, so this
2165 // should be OK for now.
2166 if (ValVT == MVT::f64 &&
2167 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2168 report_fatal_error("SSE2 register return with SSE2 disabled");
2170 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2171 // the RET instruction and handled by the FP Stackifier.
2172 if (VA.getLocReg() == X86::FP0 ||
2173 VA.getLocReg() == X86::FP1) {
2174 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2175 // change the value to the FP stack register class.
2176 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2177 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2178 RetOps.push_back(ValToCopy);
2179 // Don't emit a copytoreg.
2183 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2184 // which is returned in RAX / RDX.
2185 if (Subtarget->is64Bit()) {
2186 if (ValVT == MVT::x86mmx) {
2187 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2188 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2189 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2191 // If we don't have SSE2 available, convert to v4f32 so the generated
2192 // register is legal.
2193 if (!Subtarget->hasSSE2())
2194 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2199 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2200 Flag = Chain.getValue(1);
2201 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2204 // All x86 ABIs require that for returning structs by value we copy
2205 // the sret argument into %rax/%eax (depending on ABI) for the return.
2206 // We saved the argument into a virtual register in the entry block,
2207 // so now we copy the value out and into %rax/%eax.
2209 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2210 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2211 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2212 // either case FuncInfo->setSRetReturnReg() will have been called.
2213 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2214 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2215 getPointerTy(MF.getDataLayout()));
2218 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2219 X86::RAX : X86::EAX;
2220 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2221 Flag = Chain.getValue(1);
2223 // RAX/EAX now acts like a return value.
2225 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2228 RetOps[0] = Chain; // Update chain.
2230 // Add the flag if we have it.
2232 RetOps.push_back(Flag);
2234 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2237 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2238 if (N->getNumValues() != 1)
2240 if (!N->hasNUsesOfValue(1, 0))
2243 SDValue TCChain = Chain;
2244 SDNode *Copy = *N->use_begin();
2245 if (Copy->getOpcode() == ISD::CopyToReg) {
2246 // If the copy has a glue operand, we conservatively assume it isn't safe to
2247 // perform a tail call.
2248 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2250 TCChain = Copy->getOperand(0);
2251 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2254 bool HasRet = false;
2255 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2257 if (UI->getOpcode() != X86ISD::RET_FLAG)
2259 // If we are returning more than one value, we can definitely
2260 // not make a tail call see PR19530
2261 if (UI->getNumOperands() > 4)
2263 if (UI->getNumOperands() == 4 &&
2264 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2277 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2278 ISD::NodeType ExtendKind) const {
2280 // TODO: Is this also valid on 32-bit?
2281 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2282 ReturnMVT = MVT::i8;
2284 ReturnMVT = MVT::i32;
2286 EVT MinVT = getRegisterType(Context, ReturnMVT);
2287 return VT.bitsLT(MinVT) ? MinVT : VT;
2290 /// Lower the result values of a call into the
2291 /// appropriate copies out of appropriate physical registers.
2294 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2295 CallingConv::ID CallConv, bool isVarArg,
2296 const SmallVectorImpl<ISD::InputArg> &Ins,
2297 SDLoc dl, SelectionDAG &DAG,
2298 SmallVectorImpl<SDValue> &InVals) const {
2300 // Assign locations to each value returned by this call.
2301 SmallVector<CCValAssign, 16> RVLocs;
2302 bool Is64Bit = Subtarget->is64Bit();
2303 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2305 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2307 // Copy all of the result registers out of their specified physreg.
2308 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2309 CCValAssign &VA = RVLocs[i];
2310 EVT CopyVT = VA.getLocVT();
2312 // If this is x86-64, and we disabled SSE, we can't return FP values
2313 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2314 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2315 report_fatal_error("SSE register return with SSE disabled");
2318 // If we prefer to use the value in xmm registers, copy it out as f80 and
2319 // use a truncate to move it from fp stack reg to xmm reg.
2320 bool RoundAfterCopy = false;
2321 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2322 isScalarFPTypeInSSEReg(VA.getValVT())) {
2324 RoundAfterCopy = (CopyVT != VA.getLocVT());
2327 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2328 CopyVT, InFlag).getValue(1);
2329 SDValue Val = Chain.getValue(0);
2332 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2333 // This truncation won't change the value.
2334 DAG.getIntPtrConstant(1, dl));
2336 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2337 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2339 InFlag = Chain.getValue(2);
2340 InVals.push_back(Val);
2346 //===----------------------------------------------------------------------===//
2347 // C & StdCall & Fast Calling Convention implementation
2348 //===----------------------------------------------------------------------===//
2349 // StdCall calling convention seems to be standard for many Windows' API
2350 // routines and around. It differs from C calling convention just a little:
2351 // callee should clean up the stack, not caller. Symbols should be also
2352 // decorated in some fancy way :) It doesn't support any vector arguments.
2353 // For info on fast calling convention see Fast Calling Convention (tail call)
2354 // implementation LowerX86_32FastCCCallTo.
2356 /// CallIsStructReturn - Determines whether a call uses struct return
2358 enum StructReturnType {
2363 static StructReturnType
2364 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2366 return NotStructReturn;
2368 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2369 if (!Flags.isSRet())
2370 return NotStructReturn;
2371 if (Flags.isInReg())
2372 return RegStructReturn;
2373 return StackStructReturn;
2376 /// Determines whether a function uses struct return semantics.
2377 static StructReturnType
2378 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2380 return NotStructReturn;
2382 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2383 if (!Flags.isSRet())
2384 return NotStructReturn;
2385 if (Flags.isInReg())
2386 return RegStructReturn;
2387 return StackStructReturn;
2390 /// Make a copy of an aggregate at address specified by "Src" to address
2391 /// "Dst" with size and alignment information specified by the specific
2392 /// parameter attribute. The copy will be passed as a byval function parameter.
2394 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2395 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2397 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2399 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2400 /*isVolatile*/false, /*AlwaysInline=*/true,
2401 /*isTailCall*/false,
2402 MachinePointerInfo(), MachinePointerInfo());
2405 /// Return true if the calling convention is one that
2406 /// supports tail call optimization.
2407 static bool IsTailCallConvention(CallingConv::ID CC) {
2408 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2409 CC == CallingConv::HiPE);
2412 /// \brief Return true if the calling convention is a C calling convention.
2413 static bool IsCCallConvention(CallingConv::ID CC) {
2414 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2415 CC == CallingConv::X86_64_SysV);
2418 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2420 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2421 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2425 CallingConv::ID CalleeCC = CS.getCallingConv();
2426 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2432 /// Return true if the function is being made into
2433 /// a tailcall target by changing its ABI.
2434 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2435 bool GuaranteedTailCallOpt) {
2436 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2440 X86TargetLowering::LowerMemArgument(SDValue Chain,
2441 CallingConv::ID CallConv,
2442 const SmallVectorImpl<ISD::InputArg> &Ins,
2443 SDLoc dl, SelectionDAG &DAG,
2444 const CCValAssign &VA,
2445 MachineFrameInfo *MFI,
2447 // Create the nodes corresponding to a load from this parameter slot.
2448 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2449 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2450 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2451 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2454 // If value is passed by pointer we have address passed instead of the value
2456 bool ExtendedInMem = VA.isExtInLoc() &&
2457 VA.getValVT().getScalarType() == MVT::i1;
2459 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2460 ValVT = VA.getLocVT();
2462 ValVT = VA.getValVT();
2464 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2465 // changed with more analysis.
2466 // In case of tail call optimization mark all arguments mutable. Since they
2467 // could be overwritten by lowering of arguments in case of a tail call.
2468 if (Flags.isByVal()) {
2469 unsigned Bytes = Flags.getByValSize();
2470 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2471 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2472 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2474 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2475 VA.getLocMemOffset(), isImmutable);
2476 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2477 SDValue Val = DAG.getLoad(
2478 ValVT, dl, Chain, FIN,
2479 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2481 return ExtendedInMem ?
2482 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2486 // FIXME: Get this from tablegen.
2487 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2488 const X86Subtarget *Subtarget) {
2489 assert(Subtarget->is64Bit());
2491 if (Subtarget->isCallingConvWin64(CallConv)) {
2492 static const MCPhysReg GPR64ArgRegsWin64[] = {
2493 X86::RCX, X86::RDX, X86::R8, X86::R9
2495 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2498 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2499 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2501 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2504 // FIXME: Get this from tablegen.
2505 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2506 CallingConv::ID CallConv,
2507 const X86Subtarget *Subtarget) {
2508 assert(Subtarget->is64Bit());
2509 if (Subtarget->isCallingConvWin64(CallConv)) {
2510 // The XMM registers which might contain var arg parameters are shadowed
2511 // in their paired GPR. So we only need to save the GPR to their home
2513 // TODO: __vectorcall will change this.
2517 const Function *Fn = MF.getFunction();
2518 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2519 bool isSoftFloat = Subtarget->useSoftFloat();
2520 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2521 "SSE register cannot be used when SSE is disabled!");
2522 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2523 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2527 static const MCPhysReg XMMArgRegs64Bit[] = {
2528 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2529 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2531 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2535 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2536 CallingConv::ID CallConv,
2538 const SmallVectorImpl<ISD::InputArg> &Ins,
2541 SmallVectorImpl<SDValue> &InVals)
2543 MachineFunction &MF = DAG.getMachineFunction();
2544 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2545 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2547 const Function* Fn = MF.getFunction();
2548 if (Fn->hasExternalLinkage() &&
2549 Subtarget->isTargetCygMing() &&
2550 Fn->getName() == "main")
2551 FuncInfo->setForceFramePointer(true);
2553 MachineFrameInfo *MFI = MF.getFrameInfo();
2554 bool Is64Bit = Subtarget->is64Bit();
2555 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2557 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2558 "Var args not supported with calling convention fastcc, ghc or hipe");
2560 // Assign locations to all of the incoming arguments.
2561 SmallVector<CCValAssign, 16> ArgLocs;
2562 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2564 // Allocate shadow area for Win64
2566 CCInfo.AllocateStack(32, 8);
2568 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2570 unsigned LastVal = ~0U;
2572 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2573 CCValAssign &VA = ArgLocs[i];
2574 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2576 assert(VA.getValNo() != LastVal &&
2577 "Don't support value assigned to multiple locs yet");
2579 LastVal = VA.getValNo();
2581 if (VA.isRegLoc()) {
2582 EVT RegVT = VA.getLocVT();
2583 const TargetRegisterClass *RC;
2584 if (RegVT == MVT::i32)
2585 RC = &X86::GR32RegClass;
2586 else if (Is64Bit && RegVT == MVT::i64)
2587 RC = &X86::GR64RegClass;
2588 else if (RegVT == MVT::f32)
2589 RC = &X86::FR32RegClass;
2590 else if (RegVT == MVT::f64)
2591 RC = &X86::FR64RegClass;
2592 else if (RegVT.is512BitVector())
2593 RC = &X86::VR512RegClass;
2594 else if (RegVT.is256BitVector())
2595 RC = &X86::VR256RegClass;
2596 else if (RegVT.is128BitVector())
2597 RC = &X86::VR128RegClass;
2598 else if (RegVT == MVT::x86mmx)
2599 RC = &X86::VR64RegClass;
2600 else if (RegVT == MVT::i1)
2601 RC = &X86::VK1RegClass;
2602 else if (RegVT == MVT::v8i1)
2603 RC = &X86::VK8RegClass;
2604 else if (RegVT == MVT::v16i1)
2605 RC = &X86::VK16RegClass;
2606 else if (RegVT == MVT::v32i1)
2607 RC = &X86::VK32RegClass;
2608 else if (RegVT == MVT::v64i1)
2609 RC = &X86::VK64RegClass;
2611 llvm_unreachable("Unknown argument type!");
2613 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2614 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2616 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2617 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2619 if (VA.getLocInfo() == CCValAssign::SExt)
2620 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2621 DAG.getValueType(VA.getValVT()));
2622 else if (VA.getLocInfo() == CCValAssign::ZExt)
2623 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2624 DAG.getValueType(VA.getValVT()));
2625 else if (VA.getLocInfo() == CCValAssign::BCvt)
2626 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2628 if (VA.isExtInLoc()) {
2629 // Handle MMX values passed in XMM regs.
2630 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2631 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2633 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2636 assert(VA.isMemLoc());
2637 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2640 // If value is passed via pointer - do a load.
2641 if (VA.getLocInfo() == CCValAssign::Indirect)
2642 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2643 MachinePointerInfo(), false, false, false, 0);
2645 InVals.push_back(ArgValue);
2648 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2649 // All x86 ABIs require that for returning structs by value we copy the
2650 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2651 // the argument into a virtual register so that we can access it from the
2653 if (Ins[i].Flags.isSRet()) {
2654 unsigned Reg = FuncInfo->getSRetReturnReg();
2656 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2657 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2658 FuncInfo->setSRetReturnReg(Reg);
2660 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2661 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2666 unsigned StackSize = CCInfo.getNextStackOffset();
2667 // Align stack specially for tail calls.
2668 if (FuncIsMadeTailCallSafe(CallConv,
2669 MF.getTarget().Options.GuaranteedTailCallOpt))
2670 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2672 // If the function takes variable number of arguments, make a frame index for
2673 // the start of the first vararg value... for expansion of llvm.va_start. We
2674 // can skip this if there are no va_start calls.
2675 if (MFI->hasVAStart() &&
2676 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2677 CallConv != CallingConv::X86_ThisCall))) {
2678 FuncInfo->setVarArgsFrameIndex(
2679 MFI->CreateFixedObject(1, StackSize, true));
2682 MachineModuleInfo &MMI = MF.getMMI();
2683 const Function *WinEHParent = nullptr;
2684 if (MMI.hasWinEHFuncInfo(Fn))
2685 WinEHParent = MMI.getWinEHParent(Fn);
2686 bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2688 // Figure out if XMM registers are in use.
2689 assert(!(Subtarget->useSoftFloat() &&
2690 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2691 "SSE register cannot be used when SSE is disabled!");
2693 // 64-bit calling conventions support varargs and register parameters, so we
2694 // have to do extra work to spill them in the prologue.
2695 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2696 // Find the first unallocated argument registers.
2697 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2698 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2699 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2700 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2701 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2702 "SSE register cannot be used when SSE is disabled!");
2704 // Gather all the live in physical registers.
2705 SmallVector<SDValue, 6> LiveGPRs;
2706 SmallVector<SDValue, 8> LiveXMMRegs;
2708 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2709 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2711 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2713 if (!ArgXMMs.empty()) {
2714 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2715 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2716 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2717 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2718 LiveXMMRegs.push_back(
2719 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2724 // Get to the caller-allocated home save location. Add 8 to account
2725 // for the return address.
2726 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2727 FuncInfo->setRegSaveFrameIndex(
2728 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2729 // Fixup to set vararg frame on shadow area (4 x i64).
2731 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2733 // For X86-64, if there are vararg parameters that are passed via
2734 // registers, then we must store them to their spots on the stack so
2735 // they may be loaded by deferencing the result of va_next.
2736 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2737 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2738 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2739 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2742 // Store the integer parameter registers.
2743 SmallVector<SDValue, 8> MemOps;
2744 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2745 getPointerTy(DAG.getDataLayout()));
2746 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2747 for (SDValue Val : LiveGPRs) {
2748 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2749 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2751 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2752 MachinePointerInfo::getFixedStack(
2753 DAG.getMachineFunction(),
2754 FuncInfo->getRegSaveFrameIndex(), Offset),
2756 MemOps.push_back(Store);
2760 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2761 // Now store the XMM (fp + vector) parameter registers.
2762 SmallVector<SDValue, 12> SaveXMMOps;
2763 SaveXMMOps.push_back(Chain);
2764 SaveXMMOps.push_back(ALVal);
2765 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2766 FuncInfo->getRegSaveFrameIndex(), dl));
2767 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2768 FuncInfo->getVarArgsFPOffset(), dl));
2769 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2771 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2772 MVT::Other, SaveXMMOps));
2775 if (!MemOps.empty())
2776 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2779 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2780 // Find the largest legal vector type.
2781 MVT VecVT = MVT::Other;
2782 // FIXME: Only some x86_32 calling conventions support AVX512.
2783 if (Subtarget->hasAVX512() &&
2784 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2785 CallConv == CallingConv::Intel_OCL_BI)))
2786 VecVT = MVT::v16f32;
2787 else if (Subtarget->hasAVX())
2789 else if (Subtarget->hasSSE2())
2792 // We forward some GPRs and some vector types.
2793 SmallVector<MVT, 2> RegParmTypes;
2794 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2795 RegParmTypes.push_back(IntVT);
2796 if (VecVT != MVT::Other)
2797 RegParmTypes.push_back(VecVT);
2799 // Compute the set of forwarded registers. The rest are scratch.
2800 SmallVectorImpl<ForwardedRegister> &Forwards =
2801 FuncInfo->getForwardedMustTailRegParms();
2802 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2804 // Conservatively forward AL on x86_64, since it might be used for varargs.
2805 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2806 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2807 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2810 // Copy all forwards from physical to virtual registers.
2811 for (ForwardedRegister &F : Forwards) {
2812 // FIXME: Can we use a less constrained schedule?
2813 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2814 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2815 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2819 // Some CCs need callee pop.
2820 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2821 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2822 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2824 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2825 // If this is an sret function, the return should pop the hidden pointer.
2826 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2827 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2828 argsAreStructReturn(Ins) == StackStructReturn)
2829 FuncInfo->setBytesToPopOnReturn(4);
2833 // RegSaveFrameIndex is X86-64 only.
2834 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2835 if (CallConv == CallingConv::X86_FastCall ||
2836 CallConv == CallingConv::X86_ThisCall)
2837 // fastcc functions can't have varargs.
2838 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2841 FuncInfo->setArgumentStackSize(StackSize);
2843 if (IsWinEHParent) {
2845 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2846 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2847 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2848 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2849 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2850 MachinePointerInfo::getFixedStack(
2851 DAG.getMachineFunction(), UnwindHelpFI),
2852 /*isVolatile=*/true,
2853 /*isNonTemporal=*/false, /*Alignment=*/0);
2855 // Functions using Win32 EH are considered to have opaque SP adjustments
2856 // to force local variables to be addressed from the frame or base
2858 MFI->setHasOpaqueSPAdjustment(true);
2866 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2867 SDValue StackPtr, SDValue Arg,
2868 SDLoc dl, SelectionDAG &DAG,
2869 const CCValAssign &VA,
2870 ISD::ArgFlagsTy Flags) const {
2871 unsigned LocMemOffset = VA.getLocMemOffset();
2872 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2873 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2875 if (Flags.isByVal())
2876 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2878 return DAG.getStore(
2879 Chain, dl, Arg, PtrOff,
2880 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2884 /// Emit a load of return address if tail call
2885 /// optimization is performed and it is required.
2887 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2888 SDValue &OutRetAddr, SDValue Chain,
2889 bool IsTailCall, bool Is64Bit,
2890 int FPDiff, SDLoc dl) const {
2891 // Adjust the Return address stack slot.
2892 EVT VT = getPointerTy(DAG.getDataLayout());
2893 OutRetAddr = getReturnAddressFrameIndex(DAG);
2895 // Load the "old" Return address.
2896 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2897 false, false, false, 0);
2898 return SDValue(OutRetAddr.getNode(), 1);
2901 /// Emit a store of the return address if tail call
2902 /// optimization is performed and it is required (FPDiff!=0).
2903 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2904 SDValue Chain, SDValue RetAddrFrIdx,
2905 EVT PtrVT, unsigned SlotSize,
2906 int FPDiff, SDLoc dl) {
2907 // Store the return address to the appropriate stack slot.
2908 if (!FPDiff) return Chain;
2909 // Calculate the new stack slot for the return address.
2910 int NewReturnAddrFI =
2911 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2913 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2914 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2915 MachinePointerInfo::getFixedStack(
2916 DAG.getMachineFunction(), NewReturnAddrFI),
2921 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2922 /// operation of specified width.
2923 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2925 unsigned NumElems = VT.getVectorNumElements();
2926 SmallVector<int, 8> Mask;
2927 Mask.push_back(NumElems);
2928 for (unsigned i = 1; i != NumElems; ++i)
2930 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2934 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2935 SmallVectorImpl<SDValue> &InVals) const {
2936 SelectionDAG &DAG = CLI.DAG;
2938 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2939 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2940 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2941 SDValue Chain = CLI.Chain;
2942 SDValue Callee = CLI.Callee;
2943 CallingConv::ID CallConv = CLI.CallConv;
2944 bool &isTailCall = CLI.IsTailCall;
2945 bool isVarArg = CLI.IsVarArg;
2947 MachineFunction &MF = DAG.getMachineFunction();
2948 bool Is64Bit = Subtarget->is64Bit();
2949 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2950 StructReturnType SR = callIsStructReturn(Outs);
2951 bool IsSibcall = false;
2952 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2953 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2955 if (Attr.getValueAsString() == "true")
2958 if (Subtarget->isPICStyleGOT() &&
2959 !MF.getTarget().Options.GuaranteedTailCallOpt) {
2960 // If we are using a GOT, disable tail calls to external symbols with
2961 // default visibility. Tail calling such a symbol requires using a GOT
2962 // relocation, which forces early binding of the symbol. This breaks code
2963 // that require lazy function symbol resolution. Using musttail or
2964 // GuaranteedTailCallOpt will override this.
2965 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2966 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2967 G->getGlobal()->hasDefaultVisibility()))
2971 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2973 // Force this to be a tail call. The verifier rules are enough to ensure
2974 // that we can lower this successfully without moving the return address
2977 } else if (isTailCall) {
2978 // Check if it's really possible to do a tail call.
2979 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2980 isVarArg, SR != NotStructReturn,
2981 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2982 Outs, OutVals, Ins, DAG);
2984 // Sibcalls are automatically detected tailcalls which do not require
2986 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2993 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2994 "Var args not supported with calling convention fastcc, ghc or hipe");
2996 // Analyze operands of the call, assigning locations to each operand.
2997 SmallVector<CCValAssign, 16> ArgLocs;
2998 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3000 // Allocate shadow area for Win64
3002 CCInfo.AllocateStack(32, 8);
3004 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3006 // Get a count of how many bytes are to be pushed on the stack.
3007 unsigned NumBytes = CCInfo.getNextStackOffset();
3009 // This is a sibcall. The memory operands are available in caller's
3010 // own caller's stack.
3012 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3013 IsTailCallConvention(CallConv))
3014 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3017 if (isTailCall && !IsSibcall && !IsMustTail) {
3018 // Lower arguments at fp - stackoffset + fpdiff.
3019 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3021 FPDiff = NumBytesCallerPushed - NumBytes;
3023 // Set the delta of movement of the returnaddr stackslot.
3024 // But only set if delta is greater than previous delta.
3025 if (FPDiff < X86Info->getTCReturnAddrDelta())
3026 X86Info->setTCReturnAddrDelta(FPDiff);
3029 unsigned NumBytesToPush = NumBytes;
3030 unsigned NumBytesToPop = NumBytes;
3032 // If we have an inalloca argument, all stack space has already been allocated
3033 // for us and be right at the top of the stack. We don't support multiple
3034 // arguments passed in memory when using inalloca.
3035 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3037 if (!ArgLocs.back().isMemLoc())
3038 report_fatal_error("cannot use inalloca attribute on a register "
3040 if (ArgLocs.back().getLocMemOffset() != 0)
3041 report_fatal_error("any parameter with the inalloca attribute must be "
3042 "the only memory argument");
3046 Chain = DAG.getCALLSEQ_START(
3047 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3049 SDValue RetAddrFrIdx;
3050 // Load return address for tail calls.
3051 if (isTailCall && FPDiff)
3052 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3053 Is64Bit, FPDiff, dl);
3055 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3056 SmallVector<SDValue, 8> MemOpChains;
3059 // Walk the register/memloc assignments, inserting copies/loads. In the case
3060 // of tail call optimization arguments are handle later.
3061 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3062 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3063 // Skip inalloca arguments, they have already been written.
3064 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3065 if (Flags.isInAlloca())
3068 CCValAssign &VA = ArgLocs[i];
3069 EVT RegVT = VA.getLocVT();
3070 SDValue Arg = OutVals[i];
3071 bool isByVal = Flags.isByVal();
3073 // Promote the value if needed.
3074 switch (VA.getLocInfo()) {
3075 default: llvm_unreachable("Unknown loc info!");
3076 case CCValAssign::Full: break;
3077 case CCValAssign::SExt:
3078 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3080 case CCValAssign::ZExt:
3081 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3083 case CCValAssign::AExt:
3084 if (Arg.getValueType().isVector() &&
3085 Arg.getValueType().getScalarType() == MVT::i1)
3086 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3087 else if (RegVT.is128BitVector()) {
3088 // Special case: passing MMX values in XMM registers.
3089 Arg = DAG.getBitcast(MVT::i64, Arg);
3090 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3091 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3093 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3095 case CCValAssign::BCvt:
3096 Arg = DAG.getBitcast(RegVT, Arg);
3098 case CCValAssign::Indirect: {
3099 // Store the argument.
3100 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3101 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3102 Chain = DAG.getStore(
3103 Chain, dl, Arg, SpillSlot,
3104 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3111 if (VA.isRegLoc()) {
3112 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3113 if (isVarArg && IsWin64) {
3114 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3115 // shadow reg if callee is a varargs function.
3116 unsigned ShadowReg = 0;
3117 switch (VA.getLocReg()) {
3118 case X86::XMM0: ShadowReg = X86::RCX; break;
3119 case X86::XMM1: ShadowReg = X86::RDX; break;
3120 case X86::XMM2: ShadowReg = X86::R8; break;
3121 case X86::XMM3: ShadowReg = X86::R9; break;
3124 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3126 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3127 assert(VA.isMemLoc());
3128 if (!StackPtr.getNode())
3129 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3130 getPointerTy(DAG.getDataLayout()));
3131 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3132 dl, DAG, VA, Flags));
3136 if (!MemOpChains.empty())
3137 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3139 if (Subtarget->isPICStyleGOT()) {
3140 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3143 RegsToPass.push_back(std::make_pair(
3144 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3145 getPointerTy(DAG.getDataLayout()))));
3147 // If we are tail calling and generating PIC/GOT style code load the
3148 // address of the callee into ECX. The value in ecx is used as target of
3149 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3150 // for tail calls on PIC/GOT architectures. Normally we would just put the
3151 // address of GOT into ebx and then call target@PLT. But for tail calls
3152 // ebx would be restored (since ebx is callee saved) before jumping to the
3155 // Note: The actual moving to ECX is done further down.
3156 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3157 if (G && !G->getGlobal()->hasLocalLinkage() &&
3158 G->getGlobal()->hasDefaultVisibility())
3159 Callee = LowerGlobalAddress(Callee, DAG);
3160 else if (isa<ExternalSymbolSDNode>(Callee))
3161 Callee = LowerExternalSymbol(Callee, DAG);
3165 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3166 // From AMD64 ABI document:
3167 // For calls that may call functions that use varargs or stdargs
3168 // (prototype-less calls or calls to functions containing ellipsis (...) in
3169 // the declaration) %al is used as hidden argument to specify the number
3170 // of SSE registers used. The contents of %al do not need to match exactly
3171 // the number of registers, but must be an ubound on the number of SSE
3172 // registers used and is in the range 0 - 8 inclusive.
3174 // Count the number of XMM registers allocated.
3175 static const MCPhysReg XMMArgRegs[] = {
3176 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3177 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3179 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3180 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3181 && "SSE registers cannot be used when SSE is disabled");
3183 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3184 DAG.getConstant(NumXMMRegs, dl,
3188 if (isVarArg && IsMustTail) {
3189 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3190 for (const auto &F : Forwards) {
3191 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3192 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3196 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3197 // don't need this because the eligibility check rejects calls that require
3198 // shuffling arguments passed in memory.
3199 if (!IsSibcall && isTailCall) {
3200 // Force all the incoming stack arguments to be loaded from the stack
3201 // before any new outgoing arguments are stored to the stack, because the
3202 // outgoing stack slots may alias the incoming argument stack slots, and
3203 // the alias isn't otherwise explicit. This is slightly more conservative
3204 // than necessary, because it means that each store effectively depends
3205 // on every argument instead of just those arguments it would clobber.
3206 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3208 SmallVector<SDValue, 8> MemOpChains2;
3211 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3212 CCValAssign &VA = ArgLocs[i];
3215 assert(VA.isMemLoc());
3216 SDValue Arg = OutVals[i];
3217 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3218 // Skip inalloca arguments. They don't require any work.
3219 if (Flags.isInAlloca())
3221 // Create frame index.
3222 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3223 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3224 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3225 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3227 if (Flags.isByVal()) {
3228 // Copy relative to framepointer.
3229 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3230 if (!StackPtr.getNode())
3231 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3232 getPointerTy(DAG.getDataLayout()));
3233 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3236 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3240 // Store relative to framepointer.
3241 MemOpChains2.push_back(DAG.getStore(
3242 ArgChain, dl, Arg, FIN,
3243 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3248 if (!MemOpChains2.empty())
3249 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3251 // Store the return address to the appropriate stack slot.
3252 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3253 getPointerTy(DAG.getDataLayout()),
3254 RegInfo->getSlotSize(), FPDiff, dl);
3257 // Build a sequence of copy-to-reg nodes chained together with token chain
3258 // and flag operands which copy the outgoing args into registers.
3260 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3261 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3262 RegsToPass[i].second, InFlag);
3263 InFlag = Chain.getValue(1);
3266 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3267 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3268 // In the 64-bit large code model, we have to make all calls
3269 // through a register, since the call instruction's 32-bit
3270 // pc-relative offset may not be large enough to hold the whole
3272 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3273 // If the callee is a GlobalAddress node (quite common, every direct call
3274 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3276 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3278 // We should use extra load for direct calls to dllimported functions in
3280 const GlobalValue *GV = G->getGlobal();
3281 if (!GV->hasDLLImportStorageClass()) {
3282 unsigned char OpFlags = 0;
3283 bool ExtraLoad = false;
3284 unsigned WrapperKind = ISD::DELETED_NODE;
3286 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3287 // external symbols most go through the PLT in PIC mode. If the symbol
3288 // has hidden or protected visibility, or if it is static or local, then
3289 // we don't need to use the PLT - we can directly call it.
3290 if (Subtarget->isTargetELF() &&
3291 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3292 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3293 OpFlags = X86II::MO_PLT;
3294 } else if (Subtarget->isPICStyleStubAny() &&
3295 !GV->isStrongDefinitionForLinker() &&
3296 (!Subtarget->getTargetTriple().isMacOSX() ||
3297 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3298 // PC-relative references to external symbols should go through $stub,
3299 // unless we're building with the leopard linker or later, which
3300 // automatically synthesizes these stubs.
3301 OpFlags = X86II::MO_DARWIN_STUB;
3302 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3303 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3304 // If the function is marked as non-lazy, generate an indirect call
3305 // which loads from the GOT directly. This avoids runtime overhead
3306 // at the cost of eager binding (and one extra byte of encoding).
3307 OpFlags = X86II::MO_GOTPCREL;
3308 WrapperKind = X86ISD::WrapperRIP;
3312 Callee = DAG.getTargetGlobalAddress(
3313 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3315 // Add a wrapper if needed.
3316 if (WrapperKind != ISD::DELETED_NODE)
3317 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3318 getPointerTy(DAG.getDataLayout()), Callee);
3319 // Add extra indirection if needed.
3321 Callee = DAG.getLoad(
3322 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3323 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3326 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3327 unsigned char OpFlags = 0;
3329 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3330 // external symbols should go through the PLT.
3331 if (Subtarget->isTargetELF() &&
3332 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3333 OpFlags = X86II::MO_PLT;
3334 } else if (Subtarget->isPICStyleStubAny() &&
3335 (!Subtarget->getTargetTriple().isMacOSX() ||
3336 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3337 // PC-relative references to external symbols should go through $stub,
3338 // unless we're building with the leopard linker or later, which
3339 // automatically synthesizes these stubs.
3340 OpFlags = X86II::MO_DARWIN_STUB;
3343 Callee = DAG.getTargetExternalSymbol(
3344 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3345 } else if (Subtarget->isTarget64BitILP32() &&
3346 Callee->getValueType(0) == MVT::i32) {
3347 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3348 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3351 // Returns a chain & a flag for retval copy to use.
3352 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3353 SmallVector<SDValue, 8> Ops;
3355 if (!IsSibcall && isTailCall) {
3356 Chain = DAG.getCALLSEQ_END(Chain,
3357 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3358 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3359 InFlag = Chain.getValue(1);
3362 Ops.push_back(Chain);
3363 Ops.push_back(Callee);
3366 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3368 // Add argument registers to the end of the list so that they are known live
3370 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3371 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3372 RegsToPass[i].second.getValueType()));
3374 // Add a register mask operand representing the call-preserved registers.
3375 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3376 assert(Mask && "Missing call preserved mask for calling convention");
3378 // If this is an invoke in a 32-bit function using an MSVC personality, assume
3379 // the function clobbers all registers. If an exception is thrown, the runtime
3380 // will not restore CSRs.
3381 // FIXME: Model this more precisely so that we can register allocate across
3382 // the normal edge and spill and fill across the exceptional edge.
3383 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3384 const Function *CallerFn = MF.getFunction();
3385 EHPersonality Pers =
3386 CallerFn->hasPersonalityFn()
3387 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3388 : EHPersonality::Unknown;
3389 if (isMSVCEHPersonality(Pers))
3390 Mask = RegInfo->getNoPreservedMask();
3393 Ops.push_back(DAG.getRegisterMask(Mask));
3395 if (InFlag.getNode())
3396 Ops.push_back(InFlag);
3400 //// If this is the first return lowered for this function, add the regs
3401 //// to the liveout set for the function.
3402 // This isn't right, although it's probably harmless on x86; liveouts
3403 // should be computed from returns not tail calls. Consider a void
3404 // function making a tail call to a function returning int.
3405 MF.getFrameInfo()->setHasTailCall();
3406 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3409 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3410 InFlag = Chain.getValue(1);
3412 // Create the CALLSEQ_END node.
3413 unsigned NumBytesForCalleeToPop;
3414 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3415 DAG.getTarget().Options.GuaranteedTailCallOpt))
3416 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3417 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3418 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3419 SR == StackStructReturn)
3420 // If this is a call to a struct-return function, the callee
3421 // pops the hidden struct pointer, so we have to push it back.
3422 // This is common for Darwin/X86, Linux & Mingw32 targets.
3423 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3424 NumBytesForCalleeToPop = 4;
3426 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3428 // Returns a flag for retval copy to use.
3430 Chain = DAG.getCALLSEQ_END(Chain,
3431 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3432 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3435 InFlag = Chain.getValue(1);
3438 // Handle result values, copying them out of physregs into vregs that we
3440 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3441 Ins, dl, DAG, InVals);
3444 //===----------------------------------------------------------------------===//
3445 // Fast Calling Convention (tail call) implementation
3446 //===----------------------------------------------------------------------===//
3448 // Like std call, callee cleans arguments, convention except that ECX is
3449 // reserved for storing the tail called function address. Only 2 registers are
3450 // free for argument passing (inreg). Tail call optimization is performed
3452 // * tailcallopt is enabled
3453 // * caller/callee are fastcc
3454 // On X86_64 architecture with GOT-style position independent code only local
3455 // (within module) calls are supported at the moment.
3456 // To keep the stack aligned according to platform abi the function
3457 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3458 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3459 // If a tail called function callee has more arguments than the caller the
3460 // caller needs to make sure that there is room to move the RETADDR to. This is
3461 // achieved by reserving an area the size of the argument delta right after the
3462 // original RETADDR, but before the saved framepointer or the spilled registers
3463 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3475 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3478 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3479 SelectionDAG& DAG) const {
3480 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3481 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3482 unsigned StackAlignment = TFI.getStackAlignment();
3483 uint64_t AlignMask = StackAlignment - 1;
3484 int64_t Offset = StackSize;
3485 unsigned SlotSize = RegInfo->getSlotSize();
3486 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3487 // Number smaller than 12 so just add the difference.
3488 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3490 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3491 Offset = ((~AlignMask) & Offset) + StackAlignment +
3492 (StackAlignment-SlotSize);
3497 /// Return true if the given stack call argument is already available in the
3498 /// same position (relatively) of the caller's incoming argument stack.
3500 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3501 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3502 const X86InstrInfo *TII) {
3503 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3505 if (Arg.getOpcode() == ISD::CopyFromReg) {
3506 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3507 if (!TargetRegisterInfo::isVirtualRegister(VR))
3509 MachineInstr *Def = MRI->getVRegDef(VR);
3512 if (!Flags.isByVal()) {
3513 if (!TII->isLoadFromStackSlot(Def, FI))
3516 unsigned Opcode = Def->getOpcode();
3517 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3518 Opcode == X86::LEA64_32r) &&
3519 Def->getOperand(1).isFI()) {
3520 FI = Def->getOperand(1).getIndex();
3521 Bytes = Flags.getByValSize();
3525 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3526 if (Flags.isByVal())
3527 // ByVal argument is passed in as a pointer but it's now being
3528 // dereferenced. e.g.
3529 // define @foo(%struct.X* %A) {
3530 // tail call @bar(%struct.X* byval %A)
3533 SDValue Ptr = Ld->getBasePtr();
3534 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3537 FI = FINode->getIndex();
3538 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3539 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3540 FI = FINode->getIndex();
3541 Bytes = Flags.getByValSize();
3545 assert(FI != INT_MAX);
3546 if (!MFI->isFixedObjectIndex(FI))
3548 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3551 /// Check whether the call is eligible for tail call optimization. Targets
3552 /// that want to do tail call optimization should implement this function.
3554 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3555 CallingConv::ID CalleeCC,
3557 bool isCalleeStructRet,
3558 bool isCallerStructRet,
3560 const SmallVectorImpl<ISD::OutputArg> &Outs,
3561 const SmallVectorImpl<SDValue> &OutVals,
3562 const SmallVectorImpl<ISD::InputArg> &Ins,
3563 SelectionDAG &DAG) const {
3564 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3567 // If -tailcallopt is specified, make fastcc functions tail-callable.
3568 const MachineFunction &MF = DAG.getMachineFunction();
3569 const Function *CallerF = MF.getFunction();
3571 // If the function return type is x86_fp80 and the callee return type is not,
3572 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3573 // perform a tailcall optimization here.
3574 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3577 CallingConv::ID CallerCC = CallerF->getCallingConv();
3578 bool CCMatch = CallerCC == CalleeCC;
3579 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3580 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3582 // Win64 functions have extra shadow space for argument homing. Don't do the
3583 // sibcall if the caller and callee have mismatched expectations for this
3585 if (IsCalleeWin64 != IsCallerWin64)
3588 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3589 if (IsTailCallConvention(CalleeCC) && CCMatch)
3594 // Look for obvious safe cases to perform tail call optimization that do not
3595 // require ABI changes. This is what gcc calls sibcall.
3597 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3598 // emit a special epilogue.
3599 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3600 if (RegInfo->needsStackRealignment(MF))
3603 // Also avoid sibcall optimization if either caller or callee uses struct
3604 // return semantics.
3605 if (isCalleeStructRet || isCallerStructRet)
3608 // An stdcall/thiscall caller is expected to clean up its arguments; the
3609 // callee isn't going to do that.
3610 // FIXME: this is more restrictive than needed. We could produce a tailcall
3611 // when the stack adjustment matches. For example, with a thiscall that takes
3612 // only one argument.
3613 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3614 CallerCC == CallingConv::X86_ThisCall))
3617 // Do not sibcall optimize vararg calls unless all arguments are passed via
3619 if (isVarArg && !Outs.empty()) {
3621 // Optimizing for varargs on Win64 is unlikely to be safe without
3622 // additional testing.
3623 if (IsCalleeWin64 || IsCallerWin64)
3626 SmallVector<CCValAssign, 16> ArgLocs;
3627 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3630 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3631 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3632 if (!ArgLocs[i].isRegLoc())
3636 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3637 // stack. Therefore, if it's not used by the call it is not safe to optimize
3638 // this into a sibcall.
3639 bool Unused = false;
3640 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3647 SmallVector<CCValAssign, 16> RVLocs;
3648 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3650 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3651 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3652 CCValAssign &VA = RVLocs[i];
3653 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3658 // If the calling conventions do not match, then we'd better make sure the
3659 // results are returned in the same way as what the caller expects.
3661 SmallVector<CCValAssign, 16> RVLocs1;
3662 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3664 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3666 SmallVector<CCValAssign, 16> RVLocs2;
3667 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3669 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3671 if (RVLocs1.size() != RVLocs2.size())
3673 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3674 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3676 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3678 if (RVLocs1[i].isRegLoc()) {
3679 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3682 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3688 // If the callee takes no arguments then go on to check the results of the
3690 if (!Outs.empty()) {
3691 // Check if stack adjustment is needed. For now, do not do this if any
3692 // argument is passed on the stack.
3693 SmallVector<CCValAssign, 16> ArgLocs;
3694 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3697 // Allocate shadow area for Win64
3699 CCInfo.AllocateStack(32, 8);
3701 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3702 if (CCInfo.getNextStackOffset()) {
3703 MachineFunction &MF = DAG.getMachineFunction();
3704 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3707 // Check if the arguments are already laid out in the right way as
3708 // the caller's fixed stack objects.
3709 MachineFrameInfo *MFI = MF.getFrameInfo();
3710 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3711 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3712 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3713 CCValAssign &VA = ArgLocs[i];
3714 SDValue Arg = OutVals[i];
3715 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3716 if (VA.getLocInfo() == CCValAssign::Indirect)
3718 if (!VA.isRegLoc()) {
3719 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3726 // If the tailcall address may be in a register, then make sure it's
3727 // possible to register allocate for it. In 32-bit, the call address can
3728 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3729 // callee-saved registers are restored. These happen to be the same
3730 // registers used to pass 'inreg' arguments so watch out for those.
3731 if (!Subtarget->is64Bit() &&
3732 ((!isa<GlobalAddressSDNode>(Callee) &&
3733 !isa<ExternalSymbolSDNode>(Callee)) ||
3734 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3735 unsigned NumInRegs = 0;
3736 // In PIC we need an extra register to formulate the address computation
3738 unsigned MaxInRegs =
3739 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3741 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3742 CCValAssign &VA = ArgLocs[i];
3745 unsigned Reg = VA.getLocReg();
3748 case X86::EAX: case X86::EDX: case X86::ECX:
3749 if (++NumInRegs == MaxInRegs)
3761 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3762 const TargetLibraryInfo *libInfo) const {
3763 return X86::createFastISel(funcInfo, libInfo);
3766 //===----------------------------------------------------------------------===//
3767 // Other Lowering Hooks
3768 //===----------------------------------------------------------------------===//
3770 static bool MayFoldLoad(SDValue Op) {
3771 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3774 static bool MayFoldIntoStore(SDValue Op) {
3775 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3778 static bool isTargetShuffle(unsigned Opcode) {
3780 default: return false;
3781 case X86ISD::BLENDI:
3782 case X86ISD::PSHUFB:
3783 case X86ISD::PSHUFD:
3784 case X86ISD::PSHUFHW:
3785 case X86ISD::PSHUFLW:
3787 case X86ISD::PALIGNR:
3788 case X86ISD::MOVLHPS:
3789 case X86ISD::MOVLHPD:
3790 case X86ISD::MOVHLPS:
3791 case X86ISD::MOVLPS:
3792 case X86ISD::MOVLPD:
3793 case X86ISD::MOVSHDUP:
3794 case X86ISD::MOVSLDUP:
3795 case X86ISD::MOVDDUP:
3798 case X86ISD::UNPCKL:
3799 case X86ISD::UNPCKH:
3800 case X86ISD::VPERMILPI:
3801 case X86ISD::VPERM2X128:
3802 case X86ISD::VPERMI:
3803 case X86ISD::VPERMV:
3804 case X86ISD::VPERMV3:
3809 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3810 SDValue V1, unsigned TargetMask,
3811 SelectionDAG &DAG) {
3813 default: llvm_unreachable("Unknown x86 shuffle node");
3814 case X86ISD::PSHUFD:
3815 case X86ISD::PSHUFHW:
3816 case X86ISD::PSHUFLW:
3817 case X86ISD::VPERMILPI:
3818 case X86ISD::VPERMI:
3819 return DAG.getNode(Opc, dl, VT, V1,
3820 DAG.getConstant(TargetMask, dl, MVT::i8));
3824 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3825 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3827 default: llvm_unreachable("Unknown x86 shuffle node");
3828 case X86ISD::MOVLHPS:
3829 case X86ISD::MOVLHPD:
3830 case X86ISD::MOVHLPS:
3831 case X86ISD::MOVLPS:
3832 case X86ISD::MOVLPD:
3835 case X86ISD::UNPCKL:
3836 case X86ISD::UNPCKH:
3837 return DAG.getNode(Opc, dl, VT, V1, V2);
3841 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3842 MachineFunction &MF = DAG.getMachineFunction();
3843 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3844 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3845 int ReturnAddrIndex = FuncInfo->getRAIndex();
3847 if (ReturnAddrIndex == 0) {
3848 // Set up a frame object for the return address.
3849 unsigned SlotSize = RegInfo->getSlotSize();
3850 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3853 FuncInfo->setRAIndex(ReturnAddrIndex);
3856 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3859 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3860 bool hasSymbolicDisplacement) {
3861 // Offset should fit into 32 bit immediate field.
3862 if (!isInt<32>(Offset))
3865 // If we don't have a symbolic displacement - we don't have any extra
3867 if (!hasSymbolicDisplacement)
3870 // FIXME: Some tweaks might be needed for medium code model.
3871 if (M != CodeModel::Small && M != CodeModel::Kernel)
3874 // For small code model we assume that latest object is 16MB before end of 31
3875 // bits boundary. We may also accept pretty large negative constants knowing
3876 // that all objects are in the positive half of address space.
3877 if (M == CodeModel::Small && Offset < 16*1024*1024)
3880 // For kernel code model we know that all object resist in the negative half
3881 // of 32bits address space. We may not accept negative offsets, since they may
3882 // be just off and we may accept pretty large positive ones.
3883 if (M == CodeModel::Kernel && Offset >= 0)
3889 /// Determines whether the callee is required to pop its own arguments.
3890 /// Callee pop is necessary to support tail calls.
3891 bool X86::isCalleePop(CallingConv::ID CallingConv,
3892 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3893 switch (CallingConv) {
3896 case CallingConv::X86_StdCall:
3897 case CallingConv::X86_FastCall:
3898 case CallingConv::X86_ThisCall:
3900 case CallingConv::Fast:
3901 case CallingConv::GHC:
3902 case CallingConv::HiPE:
3909 /// \brief Return true if the condition is an unsigned comparison operation.
3910 static bool isX86CCUnsigned(unsigned X86CC) {
3912 default: llvm_unreachable("Invalid integer condition!");
3913 case X86::COND_E: return true;
3914 case X86::COND_G: return false;
3915 case X86::COND_GE: return false;
3916 case X86::COND_L: return false;
3917 case X86::COND_LE: return false;
3918 case X86::COND_NE: return true;
3919 case X86::COND_B: return true;
3920 case X86::COND_A: return true;
3921 case X86::COND_BE: return true;
3922 case X86::COND_AE: return true;
3924 llvm_unreachable("covered switch fell through?!");
3927 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3928 /// condition code, returning the condition code and the LHS/RHS of the
3929 /// comparison to make.
3930 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3931 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3933 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3934 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3935 // X > -1 -> X == 0, jump !sign.
3936 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3937 return X86::COND_NS;
3939 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3940 // X < 0 -> X == 0, jump on sign.
3943 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3945 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3946 return X86::COND_LE;
3950 switch (SetCCOpcode) {
3951 default: llvm_unreachable("Invalid integer condition!");
3952 case ISD::SETEQ: return X86::COND_E;
3953 case ISD::SETGT: return X86::COND_G;
3954 case ISD::SETGE: return X86::COND_GE;
3955 case ISD::SETLT: return X86::COND_L;
3956 case ISD::SETLE: return X86::COND_LE;
3957 case ISD::SETNE: return X86::COND_NE;
3958 case ISD::SETULT: return X86::COND_B;
3959 case ISD::SETUGT: return X86::COND_A;
3960 case ISD::SETULE: return X86::COND_BE;
3961 case ISD::SETUGE: return X86::COND_AE;
3965 // First determine if it is required or is profitable to flip the operands.
3967 // If LHS is a foldable load, but RHS is not, flip the condition.
3968 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3969 !ISD::isNON_EXTLoad(RHS.getNode())) {
3970 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3971 std::swap(LHS, RHS);
3974 switch (SetCCOpcode) {
3980 std::swap(LHS, RHS);
3984 // On a floating point condition, the flags are set as follows:
3986 // 0 | 0 | 0 | X > Y
3987 // 0 | 0 | 1 | X < Y
3988 // 1 | 0 | 0 | X == Y
3989 // 1 | 1 | 1 | unordered
3990 switch (SetCCOpcode) {
3991 default: llvm_unreachable("Condcode should be pre-legalized away");
3993 case ISD::SETEQ: return X86::COND_E;
3994 case ISD::SETOLT: // flipped
3996 case ISD::SETGT: return X86::COND_A;
3997 case ISD::SETOLE: // flipped
3999 case ISD::SETGE: return X86::COND_AE;
4000 case ISD::SETUGT: // flipped
4002 case ISD::SETLT: return X86::COND_B;
4003 case ISD::SETUGE: // flipped
4005 case ISD::SETLE: return X86::COND_BE;
4007 case ISD::SETNE: return X86::COND_NE;
4008 case ISD::SETUO: return X86::COND_P;
4009 case ISD::SETO: return X86::COND_NP;
4011 case ISD::SETUNE: return X86::COND_INVALID;
4015 /// Is there a floating point cmov for the specific X86 condition code?
4016 /// Current x86 isa includes the following FP cmov instructions:
4017 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4018 static bool hasFPCMov(unsigned X86CC) {
4034 /// Returns true if the target can instruction select the
4035 /// specified FP immediate natively. If false, the legalizer will
4036 /// materialize the FP immediate as a load from a constant pool.
4037 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4038 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4039 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4045 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4046 ISD::LoadExtType ExtTy,
4048 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4049 // relocation target a movq or addq instruction: don't let the load shrink.
4050 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4051 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4052 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4053 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4057 /// \brief Returns true if it is beneficial to convert a load of a constant
4058 /// to just the constant itself.
4059 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4061 assert(Ty->isIntegerTy());
4063 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4064 if (BitSize == 0 || BitSize > 64)
4069 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4070 unsigned Index) const {
4071 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4074 return (Index == 0 || Index == ResVT.getVectorNumElements());
4077 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4078 // Speculate cttz only if we can directly use TZCNT.
4079 return Subtarget->hasBMI();
4082 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4083 // Speculate ctlz only if we can directly use LZCNT.
4084 return Subtarget->hasLZCNT();
4087 /// Return true if every element in Mask, beginning
4088 /// from position Pos and ending in Pos+Size is undef.
4089 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4090 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4096 /// Return true if Val is undef or if its value falls within the
4097 /// specified range (L, H].
4098 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4099 return (Val < 0) || (Val >= Low && Val < Hi);
4102 /// Val is either less than zero (undef) or equal to the specified value.
4103 static bool isUndefOrEqual(int Val, int CmpVal) {
4104 return (Val < 0 || Val == CmpVal);
4107 /// Return true if every element in Mask, beginning
4108 /// from position Pos and ending in Pos+Size, falls within the specified
4109 /// sequential range (Low, Low+Size]. or is undef.
4110 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4111 unsigned Pos, unsigned Size, int Low) {
4112 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4113 if (!isUndefOrEqual(Mask[i], Low))
4118 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4119 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4120 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4121 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4122 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4125 // The index should be aligned on a vecWidth-bit boundary.
4127 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4129 MVT VT = N->getSimpleValueType(0);
4130 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4131 bool Result = (Index * ElSize) % vecWidth == 0;
4136 /// Return true if the specified INSERT_SUBVECTOR
4137 /// operand specifies a subvector insert that is suitable for input to
4138 /// insertion of 128 or 256-bit subvectors
4139 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4140 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4141 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4143 // The index should be aligned on a vecWidth-bit boundary.
4145 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4147 MVT VT = N->getSimpleValueType(0);
4148 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4149 bool Result = (Index * ElSize) % vecWidth == 0;
4154 bool X86::isVINSERT128Index(SDNode *N) {
4155 return isVINSERTIndex(N, 128);
4158 bool X86::isVINSERT256Index(SDNode *N) {
4159 return isVINSERTIndex(N, 256);
4162 bool X86::isVEXTRACT128Index(SDNode *N) {
4163 return isVEXTRACTIndex(N, 128);
4166 bool X86::isVEXTRACT256Index(SDNode *N) {
4167 return isVEXTRACTIndex(N, 256);
4170 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4171 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4172 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4173 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4176 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4178 MVT VecVT = N->getOperand(0).getSimpleValueType();
4179 MVT ElVT = VecVT.getVectorElementType();
4181 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4182 return Index / NumElemsPerChunk;
4185 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4186 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4187 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4188 llvm_unreachable("Illegal insert subvector for VINSERT");
4191 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4193 MVT VecVT = N->getSimpleValueType(0);
4194 MVT ElVT = VecVT.getVectorElementType();
4196 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4197 return Index / NumElemsPerChunk;
4200 /// Return the appropriate immediate to extract the specified
4201 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4202 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4203 return getExtractVEXTRACTImmediate(N, 128);
4206 /// Return the appropriate immediate to extract the specified
4207 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4208 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4209 return getExtractVEXTRACTImmediate(N, 256);
4212 /// Return the appropriate immediate to insert at the specified
4213 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4214 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4215 return getInsertVINSERTImmediate(N, 128);
4218 /// Return the appropriate immediate to insert at the specified
4219 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4220 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4221 return getInsertVINSERTImmediate(N, 256);
4224 /// Returns true if Elt is a constant integer zero
4225 static bool isZero(SDValue V) {
4226 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4227 return C && C->isNullValue();
4230 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4231 bool X86::isZeroNode(SDValue Elt) {
4234 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4235 return CFP->getValueAPF().isPosZero();
4239 /// Returns a vector of specified type with all zero elements.
4240 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4241 SelectionDAG &DAG, SDLoc dl) {
4242 assert(VT.isVector() && "Expected a vector type");
4244 // Always build SSE zero vectors as <4 x i32> bitcasted
4245 // to their dest type. This ensures they get CSE'd.
4247 if (VT.is128BitVector()) { // SSE
4248 if (Subtarget->hasSSE2()) { // SSE2
4249 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4250 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4252 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4253 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4255 } else if (VT.is256BitVector()) { // AVX
4256 if (Subtarget->hasInt256()) { // AVX2
4257 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4258 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4259 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4261 // 256-bit logic and arithmetic instructions in AVX are all
4262 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4263 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4264 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4265 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4267 } else if (VT.is512BitVector()) { // AVX-512
4268 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4269 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4270 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4271 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4272 } else if (VT.getScalarType() == MVT::i1) {
4274 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4275 && "Unexpected vector type");
4276 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4277 && "Unexpected vector type");
4278 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4279 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4280 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4282 llvm_unreachable("Unexpected vector type");
4284 return DAG.getBitcast(VT, Vec);
4287 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4288 SelectionDAG &DAG, SDLoc dl,
4289 unsigned vectorWidth) {
4290 assert((vectorWidth == 128 || vectorWidth == 256) &&
4291 "Unsupported vector width");
4292 EVT VT = Vec.getValueType();
4293 EVT ElVT = VT.getVectorElementType();
4294 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4295 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4296 VT.getVectorNumElements()/Factor);
4298 // Extract from UNDEF is UNDEF.
4299 if (Vec.getOpcode() == ISD::UNDEF)
4300 return DAG.getUNDEF(ResultVT);
4302 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4303 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4305 // This is the index of the first element of the vectorWidth-bit chunk
4307 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4310 // If the input is a buildvector just emit a smaller one.
4311 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4312 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4313 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4316 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4317 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4320 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4321 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4322 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4323 /// instructions or a simple subregister reference. Idx is an index in the
4324 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4325 /// lowering EXTRACT_VECTOR_ELT operations easier.
4326 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4327 SelectionDAG &DAG, SDLoc dl) {
4328 assert((Vec.getValueType().is256BitVector() ||
4329 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4330 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4333 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4334 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4335 SelectionDAG &DAG, SDLoc dl) {
4336 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4337 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4340 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4341 unsigned IdxVal, SelectionDAG &DAG,
4342 SDLoc dl, unsigned vectorWidth) {
4343 assert((vectorWidth == 128 || vectorWidth == 256) &&
4344 "Unsupported vector width");
4345 // Inserting UNDEF is Result
4346 if (Vec.getOpcode() == ISD::UNDEF)
4348 EVT VT = Vec.getValueType();
4349 EVT ElVT = VT.getVectorElementType();
4350 EVT ResultVT = Result.getValueType();
4352 // Insert the relevant vectorWidth bits.
4353 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4355 // This is the index of the first element of the vectorWidth-bit chunk
4357 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4360 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4361 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4364 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4365 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4366 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4367 /// simple superregister reference. Idx is an index in the 128 bits
4368 /// we want. It need not be aligned to a 128-bit boundary. That makes
4369 /// lowering INSERT_VECTOR_ELT operations easier.
4370 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4371 SelectionDAG &DAG, SDLoc dl) {
4372 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4374 // For insertion into the zero index (low half) of a 256-bit vector, it is
4375 // more efficient to generate a blend with immediate instead of an insert*128.
4376 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4377 // extend the subvector to the size of the result vector. Make sure that
4378 // we are not recursing on that node by checking for undef here.
4379 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4380 Result.getOpcode() != ISD::UNDEF) {
4381 EVT ResultVT = Result.getValueType();
4382 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4383 SDValue Undef = DAG.getUNDEF(ResultVT);
4384 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4387 // The blend instruction, and therefore its mask, depend on the data type.
4388 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4389 if (ScalarType.isFloatingPoint()) {
4390 // Choose either vblendps (float) or vblendpd (double).
4391 unsigned ScalarSize = ScalarType.getSizeInBits();
4392 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4393 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4394 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4395 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4398 const X86Subtarget &Subtarget =
4399 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4401 // AVX2 is needed for 256-bit integer blend support.
4402 // Integers must be cast to 32-bit because there is only vpblendd;
4403 // vpblendw can't be used for this because it has a handicapped mask.
4405 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4406 // is still more efficient than using the wrong domain vinsertf128 that
4407 // will be created by InsertSubVector().
4408 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4410 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4411 Vec256 = DAG.getBitcast(CastVT, Vec256);
4412 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4413 return DAG.getBitcast(ResultVT, Vec256);
4416 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4419 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4420 SelectionDAG &DAG, SDLoc dl) {
4421 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4422 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4425 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4426 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4427 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4428 /// large BUILD_VECTORS.
4429 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4430 unsigned NumElems, SelectionDAG &DAG,
4432 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4433 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4436 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4437 unsigned NumElems, SelectionDAG &DAG,
4439 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4440 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4443 /// Returns a vector of specified type with all bits set.
4444 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4445 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4446 /// Then bitcast to their original type, ensuring they get CSE'd.
4447 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4448 SelectionDAG &DAG, SDLoc dl) {
4449 assert(VT.isVector() && "Expected a vector type");
4451 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4453 if (VT.is512BitVector()) {
4454 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4455 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4456 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4457 } else if (VT.is256BitVector()) {
4458 if (Subtarget->hasInt256()) { // AVX2
4459 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4460 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4462 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4463 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4465 } else if (VT.is128BitVector()) {
4466 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4468 llvm_unreachable("Unexpected vector type");
4470 return DAG.getBitcast(VT, Vec);
4473 /// Returns a vector_shuffle node for an unpackl operation.
4474 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4476 unsigned NumElems = VT.getVectorNumElements();
4477 SmallVector<int, 8> Mask;
4478 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4480 Mask.push_back(i + NumElems);
4482 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4485 /// Returns a vector_shuffle node for an unpackh operation.
4486 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4488 unsigned NumElems = VT.getVectorNumElements();
4489 SmallVector<int, 8> Mask;
4490 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4491 Mask.push_back(i + Half);
4492 Mask.push_back(i + NumElems + Half);
4494 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4497 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4498 /// This produces a shuffle where the low element of V2 is swizzled into the
4499 /// zero/undef vector, landing at element Idx.
4500 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4501 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4503 const X86Subtarget *Subtarget,
4504 SelectionDAG &DAG) {
4505 MVT VT = V2.getSimpleValueType();
4507 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4508 unsigned NumElems = VT.getVectorNumElements();
4509 SmallVector<int, 16> MaskVec;
4510 for (unsigned i = 0; i != NumElems; ++i)
4511 // If this is the insertion idx, put the low elt of V2 here.
4512 MaskVec.push_back(i == Idx ? NumElems : i);
4513 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4516 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4517 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4518 /// uses one source. Note that this will set IsUnary for shuffles which use a
4519 /// single input multiple times, and in those cases it will
4520 /// adjust the mask to only have indices within that single input.
4521 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4522 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4523 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4524 unsigned NumElems = VT.getVectorNumElements();
4528 bool IsFakeUnary = false;
4529 switch(N->getOpcode()) {
4530 case X86ISD::BLENDI:
4531 ImmN = N->getOperand(N->getNumOperands()-1);
4532 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4535 ImmN = N->getOperand(N->getNumOperands()-1);
4536 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4537 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4539 case X86ISD::UNPCKH:
4540 DecodeUNPCKHMask(VT, Mask);
4541 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4543 case X86ISD::UNPCKL:
4544 DecodeUNPCKLMask(VT, Mask);
4545 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4547 case X86ISD::MOVHLPS:
4548 DecodeMOVHLPSMask(NumElems, Mask);
4549 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4551 case X86ISD::MOVLHPS:
4552 DecodeMOVLHPSMask(NumElems, Mask);
4553 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4555 case X86ISD::PALIGNR:
4556 ImmN = N->getOperand(N->getNumOperands()-1);
4557 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4559 case X86ISD::PSHUFD:
4560 case X86ISD::VPERMILPI:
4561 ImmN = N->getOperand(N->getNumOperands()-1);
4562 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4565 case X86ISD::PSHUFHW:
4566 ImmN = N->getOperand(N->getNumOperands()-1);
4567 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4570 case X86ISD::PSHUFLW:
4571 ImmN = N->getOperand(N->getNumOperands()-1);
4572 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4575 case X86ISD::PSHUFB: {
4577 SDValue MaskNode = N->getOperand(1);
4578 while (MaskNode->getOpcode() == ISD::BITCAST)
4579 MaskNode = MaskNode->getOperand(0);
4581 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4582 // If we have a build-vector, then things are easy.
4583 EVT VT = MaskNode.getValueType();
4584 assert(VT.isVector() &&
4585 "Can't produce a non-vector with a build_vector!");
4586 if (!VT.isInteger())
4589 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4591 SmallVector<uint64_t, 32> RawMask;
4592 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4593 SDValue Op = MaskNode->getOperand(i);
4594 if (Op->getOpcode() == ISD::UNDEF) {
4595 RawMask.push_back((uint64_t)SM_SentinelUndef);
4598 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4601 APInt MaskElement = CN->getAPIntValue();
4603 // We now have to decode the element which could be any integer size and
4604 // extract each byte of it.
4605 for (int j = 0; j < NumBytesPerElement; ++j) {
4606 // Note that this is x86 and so always little endian: the low byte is
4607 // the first byte of the mask.
4608 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4609 MaskElement = MaskElement.lshr(8);
4612 DecodePSHUFBMask(RawMask, Mask);
4616 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4620 SDValue Ptr = MaskLoad->getBasePtr();
4621 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4622 Ptr->getOpcode() == X86ISD::WrapperRIP)
4623 Ptr = Ptr->getOperand(0);
4625 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4626 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4629 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4630 DecodePSHUFBMask(C, Mask);
4638 case X86ISD::VPERMI:
4639 ImmN = N->getOperand(N->getNumOperands()-1);
4640 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4645 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4647 case X86ISD::VPERM2X128:
4648 ImmN = N->getOperand(N->getNumOperands()-1);
4649 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4650 if (Mask.empty()) return false;
4651 // Mask only contains negative index if an element is zero.
4652 if (std::any_of(Mask.begin(), Mask.end(),
4653 [](int M){ return M == SM_SentinelZero; }))
4656 case X86ISD::MOVSLDUP:
4657 DecodeMOVSLDUPMask(VT, Mask);
4660 case X86ISD::MOVSHDUP:
4661 DecodeMOVSHDUPMask(VT, Mask);
4664 case X86ISD::MOVDDUP:
4665 DecodeMOVDDUPMask(VT, Mask);
4668 case X86ISD::MOVLHPD:
4669 case X86ISD::MOVLPD:
4670 case X86ISD::MOVLPS:
4671 // Not yet implemented
4673 case X86ISD::VPERMV: {
4675 SDValue MaskNode = N->getOperand(0);
4676 while (MaskNode->getOpcode() == ISD::BITCAST)
4677 MaskNode = MaskNode->getOperand(0);
4679 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4680 SmallVector<uint64_t, 32> RawMask;
4681 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4682 // If we have a build-vector, then things are easy.
4683 assert(MaskNode.getValueType().isInteger() &&
4684 MaskNode.getValueType().getVectorNumElements() ==
4685 VT.getVectorNumElements());
4687 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4688 SDValue Op = MaskNode->getOperand(i);
4689 if (Op->getOpcode() == ISD::UNDEF)
4690 RawMask.push_back((uint64_t)SM_SentinelUndef);
4691 else if (isa<ConstantSDNode>(Op)) {
4692 APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4693 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4697 DecodeVPERMVMask(RawMask, Mask);
4700 if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4701 unsigned NumEltsInMask = MaskNode->getNumOperands();
4702 MaskNode = MaskNode->getOperand(0);
4703 auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4705 APInt MaskEltValue = CN->getAPIntValue();
4706 for (unsigned i = 0; i < NumEltsInMask; ++i)
4707 RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4708 DecodeVPERMVMask(RawMask, Mask);
4711 // It may be a scalar load
4714 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4718 SDValue Ptr = MaskLoad->getBasePtr();
4719 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4720 Ptr->getOpcode() == X86ISD::WrapperRIP)
4721 Ptr = Ptr->getOperand(0);
4723 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4724 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4727 auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4729 DecodeVPERMVMask(C, VT, Mask);
4736 case X86ISD::VPERMV3: {
4738 SDValue MaskNode = N->getOperand(1);
4739 while (MaskNode->getOpcode() == ISD::BITCAST)
4740 MaskNode = MaskNode->getOperand(1);
4742 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4743 // If we have a build-vector, then things are easy.
4744 assert(MaskNode.getValueType().isInteger() &&
4745 MaskNode.getValueType().getVectorNumElements() ==
4746 VT.getVectorNumElements());
4748 SmallVector<uint64_t, 32> RawMask;
4749 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4751 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4752 SDValue Op = MaskNode->getOperand(i);
4753 if (Op->getOpcode() == ISD::UNDEF)
4754 RawMask.push_back((uint64_t)SM_SentinelUndef);
4756 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4759 APInt MaskElement = CN->getAPIntValue();
4760 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4763 DecodeVPERMV3Mask(RawMask, Mask);
4767 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4771 SDValue Ptr = MaskLoad->getBasePtr();
4772 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4773 Ptr->getOpcode() == X86ISD::WrapperRIP)
4774 Ptr = Ptr->getOperand(0);
4776 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4777 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4780 auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4782 DecodeVPERMV3Mask(C, VT, Mask);
4789 default: llvm_unreachable("unknown target shuffle node");
4792 // If we have a fake unary shuffle, the shuffle mask is spread across two
4793 // inputs that are actually the same node. Re-map the mask to always point
4794 // into the first input.
4797 if (M >= (int)Mask.size())
4803 /// Returns the scalar element that will make up the ith
4804 /// element of the result of the vector shuffle.
4805 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4808 return SDValue(); // Limit search depth.
4810 SDValue V = SDValue(N, 0);
4811 EVT VT = V.getValueType();
4812 unsigned Opcode = V.getOpcode();
4814 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4815 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4816 int Elt = SV->getMaskElt(Index);
4819 return DAG.getUNDEF(VT.getVectorElementType());
4821 unsigned NumElems = VT.getVectorNumElements();
4822 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4823 : SV->getOperand(1);
4824 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4827 // Recurse into target specific vector shuffles to find scalars.
4828 if (isTargetShuffle(Opcode)) {
4829 MVT ShufVT = V.getSimpleValueType();
4830 unsigned NumElems = ShufVT.getVectorNumElements();
4831 SmallVector<int, 16> ShuffleMask;
4834 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4837 int Elt = ShuffleMask[Index];
4839 return DAG.getUNDEF(ShufVT.getVectorElementType());
4841 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4843 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4847 // Actual nodes that may contain scalar elements
4848 if (Opcode == ISD::BITCAST) {
4849 V = V.getOperand(0);
4850 EVT SrcVT = V.getValueType();
4851 unsigned NumElems = VT.getVectorNumElements();
4853 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4857 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4858 return (Index == 0) ? V.getOperand(0)
4859 : DAG.getUNDEF(VT.getVectorElementType());
4861 if (V.getOpcode() == ISD::BUILD_VECTOR)
4862 return V.getOperand(Index);
4867 /// Custom lower build_vector of v16i8.
4868 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4869 unsigned NumNonZero, unsigned NumZero,
4871 const X86Subtarget* Subtarget,
4872 const TargetLowering &TLI) {
4880 // SSE4.1 - use PINSRB to insert each byte directly.
4881 if (Subtarget->hasSSE41()) {
4882 for (unsigned i = 0; i < 16; ++i) {
4883 bool isNonZero = (NonZeros & (1 << i)) != 0;
4887 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4889 V = DAG.getUNDEF(MVT::v16i8);
4892 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4893 MVT::v16i8, V, Op.getOperand(i),
4894 DAG.getIntPtrConstant(i, dl));
4901 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4902 for (unsigned i = 0; i < 16; ++i) {
4903 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4904 if (ThisIsNonZero && First) {
4906 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4908 V = DAG.getUNDEF(MVT::v8i16);
4913 SDValue ThisElt, LastElt;
4914 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4915 if (LastIsNonZero) {
4916 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4917 MVT::i16, Op.getOperand(i-1));
4919 if (ThisIsNonZero) {
4920 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4921 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4922 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4924 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4928 if (ThisElt.getNode())
4929 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4930 DAG.getIntPtrConstant(i/2, dl));
4934 return DAG.getBitcast(MVT::v16i8, V);
4937 /// Custom lower build_vector of v8i16.
4938 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4939 unsigned NumNonZero, unsigned NumZero,
4941 const X86Subtarget* Subtarget,
4942 const TargetLowering &TLI) {
4949 for (unsigned i = 0; i < 8; ++i) {
4950 bool isNonZero = (NonZeros & (1 << i)) != 0;
4954 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4956 V = DAG.getUNDEF(MVT::v8i16);
4959 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4960 MVT::v8i16, V, Op.getOperand(i),
4961 DAG.getIntPtrConstant(i, dl));
4968 /// Custom lower build_vector of v4i32 or v4f32.
4969 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4970 const X86Subtarget *Subtarget,
4971 const TargetLowering &TLI) {
4972 // Find all zeroable elements.
4973 std::bitset<4> Zeroable;
4974 for (int i=0; i < 4; ++i) {
4975 SDValue Elt = Op->getOperand(i);
4976 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4978 assert(Zeroable.size() - Zeroable.count() > 1 &&
4979 "We expect at least two non-zero elements!");
4981 // We only know how to deal with build_vector nodes where elements are either
4982 // zeroable or extract_vector_elt with constant index.
4983 SDValue FirstNonZero;
4984 unsigned FirstNonZeroIdx;
4985 for (unsigned i=0; i < 4; ++i) {
4988 SDValue Elt = Op->getOperand(i);
4989 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4990 !isa<ConstantSDNode>(Elt.getOperand(1)))
4992 // Make sure that this node is extracting from a 128-bit vector.
4993 MVT VT = Elt.getOperand(0).getSimpleValueType();
4994 if (!VT.is128BitVector())
4996 if (!FirstNonZero.getNode()) {
4998 FirstNonZeroIdx = i;
5002 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5003 SDValue V1 = FirstNonZero.getOperand(0);
5004 MVT VT = V1.getSimpleValueType();
5006 // See if this build_vector can be lowered as a blend with zero.
5008 unsigned EltMaskIdx, EltIdx;
5010 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5011 if (Zeroable[EltIdx]) {
5012 // The zero vector will be on the right hand side.
5013 Mask[EltIdx] = EltIdx+4;
5017 Elt = Op->getOperand(EltIdx);
5018 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5019 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5020 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5022 Mask[EltIdx] = EltIdx;
5026 // Let the shuffle legalizer deal with blend operations.
5027 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5028 if (V1.getSimpleValueType() != VT)
5029 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5030 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5033 // See if we can lower this build_vector to a INSERTPS.
5034 if (!Subtarget->hasSSE41())
5037 SDValue V2 = Elt.getOperand(0);
5038 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5041 bool CanFold = true;
5042 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5046 SDValue Current = Op->getOperand(i);
5047 SDValue SrcVector = Current->getOperand(0);
5050 CanFold = SrcVector == V1 &&
5051 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5057 assert(V1.getNode() && "Expected at least two non-zero elements!");
5058 if (V1.getSimpleValueType() != MVT::v4f32)
5059 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5060 if (V2.getSimpleValueType() != MVT::v4f32)
5061 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5063 // Ok, we can emit an INSERTPS instruction.
5064 unsigned ZMask = Zeroable.to_ulong();
5066 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5067 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5069 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5070 DAG.getIntPtrConstant(InsertPSMask, DL));
5071 return DAG.getBitcast(VT, Result);
5074 /// Return a vector logical shift node.
5075 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5076 unsigned NumBits, SelectionDAG &DAG,
5077 const TargetLowering &TLI, SDLoc dl) {
5078 assert(VT.is128BitVector() && "Unknown type for VShift");
5079 MVT ShVT = MVT::v2i64;
5080 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5081 SrcOp = DAG.getBitcast(ShVT, SrcOp);
5082 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5083 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5084 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5085 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5089 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5091 // Check if the scalar load can be widened into a vector load. And if
5092 // the address is "base + cst" see if the cst can be "absorbed" into
5093 // the shuffle mask.
5094 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5095 SDValue Ptr = LD->getBasePtr();
5096 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5098 EVT PVT = LD->getValueType(0);
5099 if (PVT != MVT::i32 && PVT != MVT::f32)
5104 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5105 FI = FINode->getIndex();
5107 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5108 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5109 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5110 Offset = Ptr.getConstantOperandVal(1);
5111 Ptr = Ptr.getOperand(0);
5116 // FIXME: 256-bit vector instructions don't require a strict alignment,
5117 // improve this code to support it better.
5118 unsigned RequiredAlign = VT.getSizeInBits()/8;
5119 SDValue Chain = LD->getChain();
5120 // Make sure the stack object alignment is at least 16 or 32.
5121 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5122 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5123 if (MFI->isFixedObjectIndex(FI)) {
5124 // Can't change the alignment. FIXME: It's possible to compute
5125 // the exact stack offset and reference FI + adjust offset instead.
5126 // If someone *really* cares about this. That's the way to implement it.
5129 MFI->setObjectAlignment(FI, RequiredAlign);
5133 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5134 // Ptr + (Offset & ~15).
5137 if ((Offset % RequiredAlign) & 3)
5139 int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5142 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5143 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5146 int EltNo = (Offset - StartOffset) >> 2;
5147 unsigned NumElems = VT.getVectorNumElements();
5149 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5150 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5151 LD->getPointerInfo().getWithOffset(StartOffset),
5152 false, false, false, 0);
5154 SmallVector<int, 8> Mask(NumElems, EltNo);
5156 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5162 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5163 /// elements can be replaced by a single large load which has the same value as
5164 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5166 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5168 /// FIXME: we'd also like to handle the case where the last elements are zero
5169 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5170 /// There's even a handy isZeroNode for that purpose.
5171 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5172 SDLoc &DL, SelectionDAG &DAG,
5173 bool isAfterLegalize) {
5174 unsigned NumElems = Elts.size();
5176 LoadSDNode *LDBase = nullptr;
5177 unsigned LastLoadedElt = -1U;
5179 // For each element in the initializer, see if we've found a load or an undef.
5180 // If we don't find an initial load element, or later load elements are
5181 // non-consecutive, bail out.
5182 for (unsigned i = 0; i < NumElems; ++i) {
5183 SDValue Elt = Elts[i];
5184 // Look through a bitcast.
5185 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5186 Elt = Elt.getOperand(0);
5187 if (!Elt.getNode() ||
5188 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5191 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5193 LDBase = cast<LoadSDNode>(Elt.getNode());
5197 if (Elt.getOpcode() == ISD::UNDEF)
5200 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5201 EVT LdVT = Elt.getValueType();
5202 // Each loaded element must be the correct fractional portion of the
5203 // requested vector load.
5204 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5206 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5211 // If we have found an entire vector of loads and undefs, then return a large
5212 // load of the entire vector width starting at the base pointer. If we found
5213 // consecutive loads for the low half, generate a vzext_load node.
5214 if (LastLoadedElt == NumElems - 1) {
5215 assert(LDBase && "Did not find base load for merging consecutive loads");
5216 EVT EltVT = LDBase->getValueType(0);
5217 // Ensure that the input vector size for the merged loads matches the
5218 // cumulative size of the input elements.
5219 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5222 if (isAfterLegalize &&
5223 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5226 SDValue NewLd = SDValue();
5228 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5229 LDBase->getPointerInfo(), LDBase->isVolatile(),
5230 LDBase->isNonTemporal(), LDBase->isInvariant(),
5231 LDBase->getAlignment());
5233 if (LDBase->hasAnyUseOfValue(1)) {
5234 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5236 SDValue(NewLd.getNode(), 1));
5237 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5238 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5239 SDValue(NewLd.getNode(), 1));
5245 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5246 //of a v4i32 / v4f32. It's probably worth generalizing.
5247 EVT EltVT = VT.getVectorElementType();
5248 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5249 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5250 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5251 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5253 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5254 LDBase->getPointerInfo(),
5255 LDBase->getAlignment(),
5256 false/*isVolatile*/, true/*ReadMem*/,
5259 // Make sure the newly-created LOAD is in the same position as LDBase in
5260 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5261 // update uses of LDBase's output chain to use the TokenFactor.
5262 if (LDBase->hasAnyUseOfValue(1)) {
5263 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5264 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5265 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5266 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5267 SDValue(ResNode.getNode(), 1));
5270 return DAG.getBitcast(VT, ResNode);
5275 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5276 /// to generate a splat value for the following cases:
5277 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5278 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5279 /// a scalar load, or a constant.
5280 /// The VBROADCAST node is returned when a pattern is found,
5281 /// or SDValue() otherwise.
5282 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5283 SelectionDAG &DAG) {
5284 // VBROADCAST requires AVX.
5285 // TODO: Splats could be generated for non-AVX CPUs using SSE
5286 // instructions, but there's less potential gain for only 128-bit vectors.
5287 if (!Subtarget->hasAVX())
5290 MVT VT = Op.getSimpleValueType();
5293 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5294 "Unsupported vector type for broadcast.");
5299 switch (Op.getOpcode()) {
5301 // Unknown pattern found.
5304 case ISD::BUILD_VECTOR: {
5305 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5306 BitVector UndefElements;
5307 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5309 // We need a splat of a single value to use broadcast, and it doesn't
5310 // make any sense if the value is only in one element of the vector.
5311 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5315 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5316 Ld.getOpcode() == ISD::ConstantFP);
5318 // Make sure that all of the users of a non-constant load are from the
5319 // BUILD_VECTOR node.
5320 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5325 case ISD::VECTOR_SHUFFLE: {
5326 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5328 // Shuffles must have a splat mask where the first element is
5330 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5333 SDValue Sc = Op.getOperand(0);
5334 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5335 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5337 if (!Subtarget->hasInt256())
5340 // Use the register form of the broadcast instruction available on AVX2.
5341 if (VT.getSizeInBits() >= 256)
5342 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5343 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5346 Ld = Sc.getOperand(0);
5347 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5348 Ld.getOpcode() == ISD::ConstantFP);
5350 // The scalar_to_vector node and the suspected
5351 // load node must have exactly one user.
5352 // Constants may have multiple users.
5354 // AVX-512 has register version of the broadcast
5355 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5356 Ld.getValueType().getSizeInBits() >= 32;
5357 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5364 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5365 bool IsGE256 = (VT.getSizeInBits() >= 256);
5367 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5368 // instruction to save 8 or more bytes of constant pool data.
5369 // TODO: If multiple splats are generated to load the same constant,
5370 // it may be detrimental to overall size. There needs to be a way to detect
5371 // that condition to know if this is truly a size win.
5372 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5374 // Handle broadcasting a single constant scalar from the constant pool
5376 // On Sandybridge (no AVX2), it is still better to load a constant vector
5377 // from the constant pool and not to broadcast it from a scalar.
5378 // But override that restriction when optimizing for size.
5379 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5380 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5381 EVT CVT = Ld.getValueType();
5382 assert(!CVT.isVector() && "Must not broadcast a vector type");
5384 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5385 // For size optimization, also splat v2f64 and v2i64, and for size opt
5386 // with AVX2, also splat i8 and i16.
5387 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5388 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5389 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5390 const Constant *C = nullptr;
5391 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5392 C = CI->getConstantIntValue();
5393 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5394 C = CF->getConstantFPValue();
5396 assert(C && "Invalid constant type");
5398 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5400 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5401 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5403 CVT, dl, DAG.getEntryNode(), CP,
5404 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5405 false, false, Alignment);
5407 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5411 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5413 // Handle AVX2 in-register broadcasts.
5414 if (!IsLoad && Subtarget->hasInt256() &&
5415 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5416 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5418 // The scalar source must be a normal load.
5422 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5423 (Subtarget->hasVLX() && ScalarSize == 64))
5424 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5426 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5427 // double since there is no vbroadcastsd xmm
5428 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5429 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5430 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5433 // Unsupported broadcast.
5437 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5438 /// underlying vector and index.
5440 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5442 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5444 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5445 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5448 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5450 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5452 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5453 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5456 // In this case the vector is the extract_subvector expression and the index
5457 // is 2, as specified by the shuffle.
5458 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5459 SDValue ShuffleVec = SVOp->getOperand(0);
5460 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5461 assert(ShuffleVecVT.getVectorElementType() ==
5462 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5464 int ShuffleIdx = SVOp->getMaskElt(Idx);
5465 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5466 ExtractedFromVec = ShuffleVec;
5472 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5473 MVT VT = Op.getSimpleValueType();
5475 // Skip if insert_vec_elt is not supported.
5476 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5477 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5481 unsigned NumElems = Op.getNumOperands();
5485 SmallVector<unsigned, 4> InsertIndices;
5486 SmallVector<int, 8> Mask(NumElems, -1);
5488 for (unsigned i = 0; i != NumElems; ++i) {
5489 unsigned Opc = Op.getOperand(i).getOpcode();
5491 if (Opc == ISD::UNDEF)
5494 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5495 // Quit if more than 1 elements need inserting.
5496 if (InsertIndices.size() > 1)
5499 InsertIndices.push_back(i);
5503 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5504 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5505 // Quit if non-constant index.
5506 if (!isa<ConstantSDNode>(ExtIdx))
5508 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5510 // Quit if extracted from vector of different type.
5511 if (ExtractedFromVec.getValueType() != VT)
5514 if (!VecIn1.getNode())
5515 VecIn1 = ExtractedFromVec;
5516 else if (VecIn1 != ExtractedFromVec) {
5517 if (!VecIn2.getNode())
5518 VecIn2 = ExtractedFromVec;
5519 else if (VecIn2 != ExtractedFromVec)
5520 // Quit if more than 2 vectors to shuffle
5524 if (ExtractedFromVec == VecIn1)
5526 else if (ExtractedFromVec == VecIn2)
5527 Mask[i] = Idx + NumElems;
5530 if (!VecIn1.getNode())
5533 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5534 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5535 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5536 unsigned Idx = InsertIndices[i];
5537 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5538 DAG.getIntPtrConstant(Idx, DL));
5544 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5545 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5546 Op.getScalarValueSizeInBits() == 1 &&
5547 "Can not convert non-constant vector");
5548 uint64_t Immediate = 0;
5549 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5550 SDValue In = Op.getOperand(idx);
5551 if (In.getOpcode() != ISD::UNDEF)
5552 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5556 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5557 return DAG.getConstant(Immediate, dl, VT);
5559 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5561 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5563 MVT VT = Op.getSimpleValueType();
5564 assert((VT.getVectorElementType() == MVT::i1) &&
5565 "Unexpected type in LowerBUILD_VECTORvXi1!");
5568 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5569 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5570 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5571 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5574 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5575 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5576 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5577 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5580 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5581 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5582 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5583 return DAG.getBitcast(VT, Imm);
5584 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5585 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5586 DAG.getIntPtrConstant(0, dl));
5589 // Vector has one or more non-const elements
5590 uint64_t Immediate = 0;
5591 SmallVector<unsigned, 16> NonConstIdx;
5592 bool IsSplat = true;
5593 bool HasConstElts = false;
5595 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5596 SDValue In = Op.getOperand(idx);
5597 if (In.getOpcode() == ISD::UNDEF)
5599 if (!isa<ConstantSDNode>(In))
5600 NonConstIdx.push_back(idx);
5602 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5603 HasConstElts = true;
5607 else if (In != Op.getOperand(SplatIdx))
5611 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5613 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5614 DAG.getConstant(1, dl, VT),
5615 DAG.getConstant(0, dl, VT));
5617 // insert elements one by one
5621 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5622 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5624 else if (HasConstElts)
5625 Imm = DAG.getConstant(0, dl, VT);
5627 Imm = DAG.getUNDEF(VT);
5628 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5629 DstVec = DAG.getBitcast(VT, Imm);
5631 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5632 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5633 DAG.getIntPtrConstant(0, dl));
5636 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5637 unsigned InsertIdx = NonConstIdx[i];
5638 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5639 Op.getOperand(InsertIdx),
5640 DAG.getIntPtrConstant(InsertIdx, dl));
5645 /// \brief Return true if \p N implements a horizontal binop and return the
5646 /// operands for the horizontal binop into V0 and V1.
5648 /// This is a helper function of LowerToHorizontalOp().
5649 /// This function checks that the build_vector \p N in input implements a
5650 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5651 /// operation to match.
5652 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5653 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5654 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5657 /// This function only analyzes elements of \p N whose indices are
5658 /// in range [BaseIdx, LastIdx).
5659 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5661 unsigned BaseIdx, unsigned LastIdx,
5662 SDValue &V0, SDValue &V1) {
5663 EVT VT = N->getValueType(0);
5665 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5666 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5667 "Invalid Vector in input!");
5669 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5670 bool CanFold = true;
5671 unsigned ExpectedVExtractIdx = BaseIdx;
5672 unsigned NumElts = LastIdx - BaseIdx;
5673 V0 = DAG.getUNDEF(VT);
5674 V1 = DAG.getUNDEF(VT);
5676 // Check if N implements a horizontal binop.
5677 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5678 SDValue Op = N->getOperand(i + BaseIdx);
5681 if (Op->getOpcode() == ISD::UNDEF) {
5682 // Update the expected vector extract index.
5683 if (i * 2 == NumElts)
5684 ExpectedVExtractIdx = BaseIdx;
5685 ExpectedVExtractIdx += 2;
5689 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5694 SDValue Op0 = Op.getOperand(0);
5695 SDValue Op1 = Op.getOperand(1);
5697 // Try to match the following pattern:
5698 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5699 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5700 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5701 Op0.getOperand(0) == Op1.getOperand(0) &&
5702 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5703 isa<ConstantSDNode>(Op1.getOperand(1)));
5707 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5708 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5710 if (i * 2 < NumElts) {
5711 if (V0.getOpcode() == ISD::UNDEF) {
5712 V0 = Op0.getOperand(0);
5713 if (V0.getValueType() != VT)
5717 if (V1.getOpcode() == ISD::UNDEF) {
5718 V1 = Op0.getOperand(0);
5719 if (V1.getValueType() != VT)
5722 if (i * 2 == NumElts)
5723 ExpectedVExtractIdx = BaseIdx;
5726 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5727 if (I0 == ExpectedVExtractIdx)
5728 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5729 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5730 // Try to match the following dag sequence:
5731 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5732 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5736 ExpectedVExtractIdx += 2;
5742 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5743 /// a concat_vector.
5745 /// This is a helper function of LowerToHorizontalOp().
5746 /// This function expects two 256-bit vectors called V0 and V1.
5747 /// At first, each vector is split into two separate 128-bit vectors.
5748 /// Then, the resulting 128-bit vectors are used to implement two
5749 /// horizontal binary operations.
5751 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5753 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5754 /// the two new horizontal binop.
5755 /// When Mode is set, the first horizontal binop dag node would take as input
5756 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5757 /// horizontal binop dag node would take as input the lower 128-bit of V1
5758 /// and the upper 128-bit of V1.
5760 /// HADD V0_LO, V0_HI
5761 /// HADD V1_LO, V1_HI
5763 /// Otherwise, the first horizontal binop dag node takes as input the lower
5764 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5765 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5767 /// HADD V0_LO, V1_LO
5768 /// HADD V0_HI, V1_HI
5770 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5771 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5772 /// the upper 128-bits of the result.
5773 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5774 SDLoc DL, SelectionDAG &DAG,
5775 unsigned X86Opcode, bool Mode,
5776 bool isUndefLO, bool isUndefHI) {
5777 EVT VT = V0.getValueType();
5778 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5779 "Invalid nodes in input!");
5781 unsigned NumElts = VT.getVectorNumElements();
5782 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5783 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5784 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5785 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5786 EVT NewVT = V0_LO.getValueType();
5788 SDValue LO = DAG.getUNDEF(NewVT);
5789 SDValue HI = DAG.getUNDEF(NewVT);
5792 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5793 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5794 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5795 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5796 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5798 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5799 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5800 V1_LO->getOpcode() != ISD::UNDEF))
5801 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5803 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5804 V1_HI->getOpcode() != ISD::UNDEF))
5805 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5808 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5811 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5813 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5814 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5815 EVT VT = BV->getValueType(0);
5816 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5817 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5821 unsigned NumElts = VT.getVectorNumElements();
5822 SDValue InVec0 = DAG.getUNDEF(VT);
5823 SDValue InVec1 = DAG.getUNDEF(VT);
5825 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5826 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5828 // Odd-numbered elements in the input build vector are obtained from
5829 // adding two integer/float elements.
5830 // Even-numbered elements in the input build vector are obtained from
5831 // subtracting two integer/float elements.
5832 unsigned ExpectedOpcode = ISD::FSUB;
5833 unsigned NextExpectedOpcode = ISD::FADD;
5834 bool AddFound = false;
5835 bool SubFound = false;
5837 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5838 SDValue Op = BV->getOperand(i);
5840 // Skip 'undef' values.
5841 unsigned Opcode = Op.getOpcode();
5842 if (Opcode == ISD::UNDEF) {
5843 std::swap(ExpectedOpcode, NextExpectedOpcode);
5847 // Early exit if we found an unexpected opcode.
5848 if (Opcode != ExpectedOpcode)
5851 SDValue Op0 = Op.getOperand(0);
5852 SDValue Op1 = Op.getOperand(1);
5854 // Try to match the following pattern:
5855 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5856 // Early exit if we cannot match that sequence.
5857 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5858 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5859 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5860 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5861 Op0.getOperand(1) != Op1.getOperand(1))
5864 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5868 // We found a valid add/sub node. Update the information accordingly.
5874 // Update InVec0 and InVec1.
5875 if (InVec0.getOpcode() == ISD::UNDEF) {
5876 InVec0 = Op0.getOperand(0);
5877 if (InVec0.getValueType() != VT)
5880 if (InVec1.getOpcode() == ISD::UNDEF) {
5881 InVec1 = Op1.getOperand(0);
5882 if (InVec1.getValueType() != VT)
5886 // Make sure that operands in input to each add/sub node always
5887 // come from a same pair of vectors.
5888 if (InVec0 != Op0.getOperand(0)) {
5889 if (ExpectedOpcode == ISD::FSUB)
5892 // FADD is commutable. Try to commute the operands
5893 // and then test again.
5894 std::swap(Op0, Op1);
5895 if (InVec0 != Op0.getOperand(0))
5899 if (InVec1 != Op1.getOperand(0))
5902 // Update the pair of expected opcodes.
5903 std::swap(ExpectedOpcode, NextExpectedOpcode);
5906 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5907 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5908 InVec1.getOpcode() != ISD::UNDEF)
5909 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5914 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5915 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5916 const X86Subtarget *Subtarget,
5917 SelectionDAG &DAG) {
5918 EVT VT = BV->getValueType(0);
5919 unsigned NumElts = VT.getVectorNumElements();
5920 unsigned NumUndefsLO = 0;
5921 unsigned NumUndefsHI = 0;
5922 unsigned Half = NumElts/2;
5924 // Count the number of UNDEF operands in the build_vector in input.
5925 for (unsigned i = 0, e = Half; i != e; ++i)
5926 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5929 for (unsigned i = Half, e = NumElts; i != e; ++i)
5930 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5933 // Early exit if this is either a build_vector of all UNDEFs or all the
5934 // operands but one are UNDEF.
5935 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5939 SDValue InVec0, InVec1;
5940 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5941 // Try to match an SSE3 float HADD/HSUB.
5942 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5943 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5945 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5946 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5947 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5948 // Try to match an SSSE3 integer HADD/HSUB.
5949 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5950 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5952 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5953 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5956 if (!Subtarget->hasAVX())
5959 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5960 // Try to match an AVX horizontal add/sub of packed single/double
5961 // precision floating point values from 256-bit vectors.
5962 SDValue InVec2, InVec3;
5963 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5964 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5965 ((InVec0.getOpcode() == ISD::UNDEF ||
5966 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5967 ((InVec1.getOpcode() == ISD::UNDEF ||
5968 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5969 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5971 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5972 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5973 ((InVec0.getOpcode() == ISD::UNDEF ||
5974 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5975 ((InVec1.getOpcode() == ISD::UNDEF ||
5976 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5977 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5978 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5979 // Try to match an AVX2 horizontal add/sub of signed integers.
5980 SDValue InVec2, InVec3;
5982 bool CanFold = true;
5984 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5985 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5986 ((InVec0.getOpcode() == ISD::UNDEF ||
5987 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5988 ((InVec1.getOpcode() == ISD::UNDEF ||
5989 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5990 X86Opcode = X86ISD::HADD;
5991 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5992 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5993 ((InVec0.getOpcode() == ISD::UNDEF ||
5994 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5995 ((InVec1.getOpcode() == ISD::UNDEF ||
5996 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5997 X86Opcode = X86ISD::HSUB;
6002 // Fold this build_vector into a single horizontal add/sub.
6003 // Do this only if the target has AVX2.
6004 if (Subtarget->hasAVX2())
6005 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6007 // Do not try to expand this build_vector into a pair of horizontal
6008 // add/sub if we can emit a pair of scalar add/sub.
6009 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6012 // Convert this build_vector into a pair of horizontal binop followed by
6014 bool isUndefLO = NumUndefsLO == Half;
6015 bool isUndefHI = NumUndefsHI == Half;
6016 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6017 isUndefLO, isUndefHI);
6021 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6022 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6024 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6025 X86Opcode = X86ISD::HADD;
6026 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6027 X86Opcode = X86ISD::HSUB;
6028 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6029 X86Opcode = X86ISD::FHADD;
6030 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6031 X86Opcode = X86ISD::FHSUB;
6035 // Don't try to expand this build_vector into a pair of horizontal add/sub
6036 // if we can simply emit a pair of scalar add/sub.
6037 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6040 // Convert this build_vector into two horizontal add/sub followed by
6042 bool isUndefLO = NumUndefsLO == Half;
6043 bool isUndefHI = NumUndefsHI == Half;
6044 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6045 isUndefLO, isUndefHI);
6052 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6055 MVT VT = Op.getSimpleValueType();
6056 MVT ExtVT = VT.getVectorElementType();
6057 unsigned NumElems = Op.getNumOperands();
6059 // Generate vectors for predicate vectors.
6060 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6061 return LowerBUILD_VECTORvXi1(Op, DAG);
6063 // Vectors containing all zeros can be matched by pxor and xorps later
6064 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6065 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6066 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6067 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6070 return getZeroVector(VT, Subtarget, DAG, dl);
6073 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6074 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6075 // vpcmpeqd on 256-bit vectors.
6076 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6077 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6080 if (!VT.is512BitVector())
6081 return getOnesVector(VT, Subtarget, DAG, dl);
6084 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6085 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6087 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6088 return HorizontalOp;
6089 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6092 unsigned EVTBits = ExtVT.getSizeInBits();
6094 unsigned NumZero = 0;
6095 unsigned NumNonZero = 0;
6096 unsigned NonZeros = 0;
6097 bool IsAllConstants = true;
6098 SmallSet<SDValue, 8> Values;
6099 for (unsigned i = 0; i < NumElems; ++i) {
6100 SDValue Elt = Op.getOperand(i);
6101 if (Elt.getOpcode() == ISD::UNDEF)
6104 if (Elt.getOpcode() != ISD::Constant &&
6105 Elt.getOpcode() != ISD::ConstantFP)
6106 IsAllConstants = false;
6107 if (X86::isZeroNode(Elt))
6110 NonZeros |= (1 << i);
6115 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6116 if (NumNonZero == 0)
6117 return DAG.getUNDEF(VT);
6119 // Special case for single non-zero, non-undef, element.
6120 if (NumNonZero == 1) {
6121 unsigned Idx = countTrailingZeros(NonZeros);
6122 SDValue Item = Op.getOperand(Idx);
6124 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6125 // the value are obviously zero, truncate the value to i32 and do the
6126 // insertion that way. Only do this if the value is non-constant or if the
6127 // value is a constant being inserted into element 0. It is cheaper to do
6128 // a constant pool load than it is to do a movd + shuffle.
6129 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6130 (!IsAllConstants || Idx == 0)) {
6131 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6133 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6134 EVT VecVT = MVT::v4i32;
6136 // Truncate the value (which may itself be a constant) to i32, and
6137 // convert it to a vector with movd (S2V+shuffle to zero extend).
6138 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6139 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6140 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6141 Item, Idx * 2, true, Subtarget, DAG));
6145 // If we have a constant or non-constant insertion into the low element of
6146 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6147 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6148 // depending on what the source datatype is.
6151 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6153 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6154 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6155 if (VT.is512BitVector()) {
6156 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6157 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6158 Item, DAG.getIntPtrConstant(0, dl));
6160 assert((VT.is128BitVector() || VT.is256BitVector()) &&
6161 "Expected an SSE value type!");
6162 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6163 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6164 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6167 // We can't directly insert an i8 or i16 into a vector, so zero extend
6169 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6170 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6171 if (VT.is256BitVector()) {
6172 if (Subtarget->hasAVX()) {
6173 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6174 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6176 // Without AVX, we need to extend to a 128-bit vector and then
6177 // insert into the 256-bit vector.
6178 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6179 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6180 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6183 assert(VT.is128BitVector() && "Expected an SSE value type!");
6184 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6185 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6187 return DAG.getBitcast(VT, Item);
6191 // Is it a vector logical left shift?
6192 if (NumElems == 2 && Idx == 1 &&
6193 X86::isZeroNode(Op.getOperand(0)) &&
6194 !X86::isZeroNode(Op.getOperand(1))) {
6195 unsigned NumBits = VT.getSizeInBits();
6196 return getVShift(true, VT,
6197 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6198 VT, Op.getOperand(1)),
6199 NumBits/2, DAG, *this, dl);
6202 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6205 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6206 // is a non-constant being inserted into an element other than the low one,
6207 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6208 // movd/movss) to move this into the low element, then shuffle it into
6210 if (EVTBits == 32) {
6211 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6212 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6216 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6217 if (Values.size() == 1) {
6218 if (EVTBits == 32) {
6219 // Instead of a shuffle like this:
6220 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6221 // Check if it's possible to issue this instead.
6222 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6223 unsigned Idx = countTrailingZeros(NonZeros);
6224 SDValue Item = Op.getOperand(Idx);
6225 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6226 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6231 // A vector full of immediates; various special cases are already
6232 // handled, so this is best done with a single constant-pool load.
6236 // For AVX-length vectors, see if we can use a vector load to get all of the
6237 // elements, otherwise build the individual 128-bit pieces and use
6238 // shuffles to put them in place.
6239 if (VT.is256BitVector() || VT.is512BitVector()) {
6240 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6242 // Check for a build vector of consecutive loads.
6243 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6246 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6248 // Build both the lower and upper subvector.
6249 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6250 makeArrayRef(&V[0], NumElems/2));
6251 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6252 makeArrayRef(&V[NumElems / 2], NumElems/2));
6254 // Recreate the wider vector with the lower and upper part.
6255 if (VT.is256BitVector())
6256 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6257 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6260 // Let legalizer expand 2-wide build_vectors.
6261 if (EVTBits == 64) {
6262 if (NumNonZero == 1) {
6263 // One half is zero or undef.
6264 unsigned Idx = countTrailingZeros(NonZeros);
6265 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6266 Op.getOperand(Idx));
6267 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6272 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6273 if (EVTBits == 8 && NumElems == 16)
6274 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6278 if (EVTBits == 16 && NumElems == 8)
6279 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6283 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6284 if (EVTBits == 32 && NumElems == 4)
6285 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6288 // If element VT is == 32 bits, turn it into a number of shuffles.
6289 SmallVector<SDValue, 8> V(NumElems);
6290 if (NumElems == 4 && NumZero > 0) {
6291 for (unsigned i = 0; i < 4; ++i) {
6292 bool isZero = !(NonZeros & (1 << i));
6294 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6296 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6299 for (unsigned i = 0; i < 2; ++i) {
6300 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6303 V[i] = V[i*2]; // Must be a zero vector.
6306 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6309 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6312 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6317 bool Reverse1 = (NonZeros & 0x3) == 2;
6318 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6322 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6323 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6325 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6328 if (Values.size() > 1 && VT.is128BitVector()) {
6329 // Check for a build vector of consecutive loads.
6330 for (unsigned i = 0; i < NumElems; ++i)
6331 V[i] = Op.getOperand(i);
6333 // Check for elements which are consecutive loads.
6334 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6337 // Check for a build vector from mostly shuffle plus few inserting.
6338 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6341 // For SSE 4.1, use insertps to put the high elements into the low element.
6342 if (Subtarget->hasSSE41()) {
6344 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6345 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6347 Result = DAG.getUNDEF(VT);
6349 for (unsigned i = 1; i < NumElems; ++i) {
6350 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6351 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6352 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6357 // Otherwise, expand into a number of unpckl*, start by extending each of
6358 // our (non-undef) elements to the full vector width with the element in the
6359 // bottom slot of the vector (which generates no code for SSE).
6360 for (unsigned i = 0; i < NumElems; ++i) {
6361 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6362 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6364 V[i] = DAG.getUNDEF(VT);
6367 // Next, we iteratively mix elements, e.g. for v4f32:
6368 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6369 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6370 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6371 unsigned EltStride = NumElems >> 1;
6372 while (EltStride != 0) {
6373 for (unsigned i = 0; i < EltStride; ++i) {
6374 // If V[i+EltStride] is undef and this is the first round of mixing,
6375 // then it is safe to just drop this shuffle: V[i] is already in the
6376 // right place, the one element (since it's the first round) being
6377 // inserted as undef can be dropped. This isn't safe for successive
6378 // rounds because they will permute elements within both vectors.
6379 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6380 EltStride == NumElems/2)
6383 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6392 // 256-bit AVX can use the vinsertf128 instruction
6393 // to create 256-bit vectors from two other 128-bit ones.
6394 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6396 MVT ResVT = Op.getSimpleValueType();
6398 assert((ResVT.is256BitVector() ||
6399 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6401 SDValue V1 = Op.getOperand(0);
6402 SDValue V2 = Op.getOperand(1);
6403 unsigned NumElems = ResVT.getVectorNumElements();
6404 if (ResVT.is256BitVector())
6405 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6407 if (Op.getNumOperands() == 4) {
6408 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6409 ResVT.getVectorNumElements()/2);
6410 SDValue V3 = Op.getOperand(2);
6411 SDValue V4 = Op.getOperand(3);
6412 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6413 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6415 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6418 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6419 const X86Subtarget *Subtarget,
6420 SelectionDAG & DAG) {
6422 MVT ResVT = Op.getSimpleValueType();
6423 unsigned NumOfOperands = Op.getNumOperands();
6425 assert(isPowerOf2_32(NumOfOperands) &&
6426 "Unexpected number of operands in CONCAT_VECTORS");
6428 if (NumOfOperands > 2) {
6429 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6430 ResVT.getVectorNumElements()/2);
6431 SmallVector<SDValue, 2> Ops;
6432 for (unsigned i = 0; i < NumOfOperands/2; i++)
6433 Ops.push_back(Op.getOperand(i));
6434 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6436 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6437 Ops.push_back(Op.getOperand(i));
6438 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6439 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6442 SDValue V1 = Op.getOperand(0);
6443 SDValue V2 = Op.getOperand(1);
6444 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6445 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6447 if (IsZeroV1 && IsZeroV2)
6448 return getZeroVector(ResVT, Subtarget, DAG, dl);
6450 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6451 SDValue Undef = DAG.getUNDEF(ResVT);
6452 unsigned NumElems = ResVT.getVectorNumElements();
6453 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6455 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6456 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6460 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6461 // Zero the upper bits of V1
6462 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6463 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6466 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6469 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6470 const X86Subtarget *Subtarget,
6471 SelectionDAG &DAG) {
6472 MVT VT = Op.getSimpleValueType();
6473 if (VT.getVectorElementType() == MVT::i1)
6474 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6476 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6477 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6478 Op.getNumOperands() == 4)));
6480 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6481 // from two other 128-bit ones.
6483 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6484 return LowerAVXCONCAT_VECTORS(Op, DAG);
6488 //===----------------------------------------------------------------------===//
6489 // Vector shuffle lowering
6491 // This is an experimental code path for lowering vector shuffles on x86. It is
6492 // designed to handle arbitrary vector shuffles and blends, gracefully
6493 // degrading performance as necessary. It works hard to recognize idiomatic
6494 // shuffles and lower them to optimal instruction patterns without leaving
6495 // a framework that allows reasonably efficient handling of all vector shuffle
6497 //===----------------------------------------------------------------------===//
6499 /// \brief Tiny helper function to identify a no-op mask.
6501 /// This is a somewhat boring predicate function. It checks whether the mask
6502 /// array input, which is assumed to be a single-input shuffle mask of the kind
6503 /// used by the X86 shuffle instructions (not a fully general
6504 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6505 /// in-place shuffle are 'no-op's.
6506 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6507 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6508 if (Mask[i] != -1 && Mask[i] != i)
6513 /// \brief Helper function to classify a mask as a single-input mask.
6515 /// This isn't a generic single-input test because in the vector shuffle
6516 /// lowering we canonicalize single inputs to be the first input operand. This
6517 /// means we can more quickly test for a single input by only checking whether
6518 /// an input from the second operand exists. We also assume that the size of
6519 /// mask corresponds to the size of the input vectors which isn't true in the
6520 /// fully general case.
6521 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6523 if (M >= (int)Mask.size())
6528 /// \brief Test whether there are elements crossing 128-bit lanes in this
6531 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6532 /// and we routinely test for these.
6533 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6534 int LaneSize = 128 / VT.getScalarSizeInBits();
6535 int Size = Mask.size();
6536 for (int i = 0; i < Size; ++i)
6537 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6542 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6544 /// This checks a shuffle mask to see if it is performing the same
6545 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6546 /// that it is also not lane-crossing. It may however involve a blend from the
6547 /// same lane of a second vector.
6549 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6550 /// non-trivial to compute in the face of undef lanes. The representation is
6551 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6552 /// entries from both V1 and V2 inputs to the wider mask.
6554 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6555 SmallVectorImpl<int> &RepeatedMask) {
6556 int LaneSize = 128 / VT.getScalarSizeInBits();
6557 RepeatedMask.resize(LaneSize, -1);
6558 int Size = Mask.size();
6559 for (int i = 0; i < Size; ++i) {
6562 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6563 // This entry crosses lanes, so there is no way to model this shuffle.
6566 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6567 if (RepeatedMask[i % LaneSize] == -1)
6568 // This is the first non-undef entry in this slot of a 128-bit lane.
6569 RepeatedMask[i % LaneSize] =
6570 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6571 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6572 // Found a mismatch with the repeated mask.
6578 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6581 /// This is a fast way to test a shuffle mask against a fixed pattern:
6583 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6585 /// It returns true if the mask is exactly as wide as the argument list, and
6586 /// each element of the mask is either -1 (signifying undef) or the value given
6587 /// in the argument.
6588 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6589 ArrayRef<int> ExpectedMask) {
6590 if (Mask.size() != ExpectedMask.size())
6593 int Size = Mask.size();
6595 // If the values are build vectors, we can look through them to find
6596 // equivalent inputs that make the shuffles equivalent.
6597 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6598 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6600 for (int i = 0; i < Size; ++i)
6601 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6602 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6603 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6604 if (!MaskBV || !ExpectedBV ||
6605 MaskBV->getOperand(Mask[i] % Size) !=
6606 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6613 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6615 /// This helper function produces an 8-bit shuffle immediate corresponding to
6616 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6617 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6620 /// NB: We rely heavily on "undef" masks preserving the input lane.
6621 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6622 SelectionDAG &DAG) {
6623 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6624 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6625 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6626 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6627 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6630 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6631 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6632 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6633 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6634 return DAG.getConstant(Imm, DL, MVT::i8);
6637 /// \brief Compute whether each element of a shuffle is zeroable.
6639 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6640 /// Either it is an undef element in the shuffle mask, the element of the input
6641 /// referenced is undef, or the element of the input referenced is known to be
6642 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6643 /// as many lanes with this technique as possible to simplify the remaining
6645 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6646 SDValue V1, SDValue V2) {
6647 SmallBitVector Zeroable(Mask.size(), false);
6649 while (V1.getOpcode() == ISD::BITCAST)
6650 V1 = V1->getOperand(0);
6651 while (V2.getOpcode() == ISD::BITCAST)
6652 V2 = V2->getOperand(0);
6654 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6655 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6657 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6659 // Handle the easy cases.
6660 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6665 // If this is an index into a build_vector node (which has the same number
6666 // of elements), dig out the input value and use it.
6667 SDValue V = M < Size ? V1 : V2;
6668 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6671 SDValue Input = V.getOperand(M % Size);
6672 // The UNDEF opcode check really should be dead code here, but not quite
6673 // worth asserting on (it isn't invalid, just unexpected).
6674 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6681 // X86 has dedicated unpack instructions that can handle specific blend
6682 // operations: UNPCKH and UNPCKL.
6683 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6684 SDValue V1, SDValue V2,
6685 SelectionDAG &DAG) {
6686 int NumElts = VT.getVectorNumElements();
6689 bool UnpcklSwapped = true;
6690 bool UnpckhSwapped = true;
6691 int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6693 for (int i = 0; i < NumElts; ++i) {
6694 unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6696 int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6697 int HiPos = LoPos + NumEltsInLane / 2;
6698 int LoPosSwapped = (LoPos + NumElts) % (NumElts * 2);
6699 int HiPosSwapped = (HiPos + NumElts) % (NumElts * 2);
6703 if (Mask[i] != LoPos)
6705 if (Mask[i] != HiPos)
6707 if (Mask[i] != LoPosSwapped)
6708 UnpcklSwapped = false;
6709 if (Mask[i] != HiPosSwapped)
6710 UnpckhSwapped = false;
6711 if (!Unpckl && !Unpckh && !UnpcklSwapped && !UnpckhSwapped)
6715 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6717 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6719 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6721 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6723 llvm_unreachable("Unexpected result of UNPCK mask analysis");
6727 /// \brief Try to emit a bitmask instruction for a shuffle.
6729 /// This handles cases where we can model a blend exactly as a bitmask due to
6730 /// one of the inputs being zeroable.
6731 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6732 SDValue V2, ArrayRef<int> Mask,
6733 SelectionDAG &DAG) {
6734 MVT EltVT = VT.getScalarType();
6735 int NumEltBits = EltVT.getSizeInBits();
6736 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6737 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6738 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6740 if (EltVT.isFloatingPoint()) {
6741 Zero = DAG.getBitcast(EltVT, Zero);
6742 AllOnes = DAG.getBitcast(EltVT, AllOnes);
6744 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6745 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6747 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6750 if (Mask[i] % Size != i)
6751 return SDValue(); // Not a blend.
6753 V = Mask[i] < Size ? V1 : V2;
6754 else if (V != (Mask[i] < Size ? V1 : V2))
6755 return SDValue(); // Can only let one input through the mask.
6757 VMaskOps[i] = AllOnes;
6760 return SDValue(); // No non-zeroable elements!
6762 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6763 V = DAG.getNode(VT.isFloatingPoint()
6764 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6769 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6771 /// This is used as a fallback approach when first class blend instructions are
6772 /// unavailable. Currently it is only suitable for integer vectors, but could
6773 /// be generalized for floating point vectors if desirable.
6774 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6775 SDValue V2, ArrayRef<int> Mask,
6776 SelectionDAG &DAG) {
6777 assert(VT.isInteger() && "Only supports integer vector types!");
6778 MVT EltVT = VT.getScalarType();
6779 int NumEltBits = EltVT.getSizeInBits();
6780 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6781 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6783 SmallVector<SDValue, 16> MaskOps;
6784 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6785 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6786 return SDValue(); // Shuffled input!
6787 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6790 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6791 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6792 // We have to cast V2 around.
6793 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6794 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6795 DAG.getBitcast(MaskVT, V1Mask),
6796 DAG.getBitcast(MaskVT, V2)));
6797 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6800 /// \brief Try to emit a blend instruction for a shuffle.
6802 /// This doesn't do any checks for the availability of instructions for blending
6803 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6804 /// be matched in the backend with the type given. What it does check for is
6805 /// that the shuffle mask is in fact a blend.
6806 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6807 SDValue V2, ArrayRef<int> Mask,
6808 const X86Subtarget *Subtarget,
6809 SelectionDAG &DAG) {
6810 unsigned BlendMask = 0;
6811 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6812 if (Mask[i] >= Size) {
6813 if (Mask[i] != i + Size)
6814 return SDValue(); // Shuffled V2 input!
6815 BlendMask |= 1u << i;
6818 if (Mask[i] >= 0 && Mask[i] != i)
6819 return SDValue(); // Shuffled V1 input!
6821 switch (VT.SimpleTy) {
6826 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6827 DAG.getConstant(BlendMask, DL, MVT::i8));
6831 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6835 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6836 // that instruction.
6837 if (Subtarget->hasAVX2()) {
6838 // Scale the blend by the number of 32-bit dwords per element.
6839 int Scale = VT.getScalarSizeInBits() / 32;
6841 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6842 if (Mask[i] >= Size)
6843 for (int j = 0; j < Scale; ++j)
6844 BlendMask |= 1u << (i * Scale + j);
6846 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6847 V1 = DAG.getBitcast(BlendVT, V1);
6848 V2 = DAG.getBitcast(BlendVT, V2);
6849 return DAG.getBitcast(
6850 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6851 DAG.getConstant(BlendMask, DL, MVT::i8)));
6855 // For integer shuffles we need to expand the mask and cast the inputs to
6856 // v8i16s prior to blending.
6857 int Scale = 8 / VT.getVectorNumElements();
6859 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6860 if (Mask[i] >= Size)
6861 for (int j = 0; j < Scale; ++j)
6862 BlendMask |= 1u << (i * Scale + j);
6864 V1 = DAG.getBitcast(MVT::v8i16, V1);
6865 V2 = DAG.getBitcast(MVT::v8i16, V2);
6866 return DAG.getBitcast(VT,
6867 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6868 DAG.getConstant(BlendMask, DL, MVT::i8)));
6872 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6873 SmallVector<int, 8> RepeatedMask;
6874 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6875 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6876 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6878 for (int i = 0; i < 8; ++i)
6879 if (RepeatedMask[i] >= 16)
6880 BlendMask |= 1u << i;
6881 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6882 DAG.getConstant(BlendMask, DL, MVT::i8));
6888 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6889 "256-bit byte-blends require AVX2 support!");
6891 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6892 if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6895 // Scale the blend by the number of bytes per element.
6896 int Scale = VT.getScalarSizeInBits() / 8;
6898 // This form of blend is always done on bytes. Compute the byte vector
6900 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6902 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6903 // mix of LLVM's code generator and the x86 backend. We tell the code
6904 // generator that boolean values in the elements of an x86 vector register
6905 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6906 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6907 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6908 // of the element (the remaining are ignored) and 0 in that high bit would
6909 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6910 // the LLVM model for boolean values in vector elements gets the relevant
6911 // bit set, it is set backwards and over constrained relative to x86's
6913 SmallVector<SDValue, 32> VSELECTMask;
6914 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6915 for (int j = 0; j < Scale; ++j)
6916 VSELECTMask.push_back(
6917 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6918 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6921 V1 = DAG.getBitcast(BlendVT, V1);
6922 V2 = DAG.getBitcast(BlendVT, V2);
6923 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6924 DAG.getNode(ISD::BUILD_VECTOR, DL,
6925 BlendVT, VSELECTMask),
6930 llvm_unreachable("Not a supported integer vector type!");
6934 /// \brief Try to lower as a blend of elements from two inputs followed by
6935 /// a single-input permutation.
6937 /// This matches the pattern where we can blend elements from two inputs and
6938 /// then reduce the shuffle to a single-input permutation.
6939 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6942 SelectionDAG &DAG) {
6943 // We build up the blend mask while checking whether a blend is a viable way
6944 // to reduce the shuffle.
6945 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6946 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6948 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6952 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6954 if (BlendMask[Mask[i] % Size] == -1)
6955 BlendMask[Mask[i] % Size] = Mask[i];
6956 else if (BlendMask[Mask[i] % Size] != Mask[i])
6957 return SDValue(); // Can't blend in the needed input!
6959 PermuteMask[i] = Mask[i] % Size;
6962 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6963 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6966 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6967 /// blends and permutes.
6969 /// This matches the extremely common pattern for handling combined
6970 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6971 /// operations. It will try to pick the best arrangement of shuffles and
6973 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6977 SelectionDAG &DAG) {
6978 // Shuffle the input elements into the desired positions in V1 and V2 and
6979 // blend them together.
6980 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6981 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6982 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6983 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6984 if (Mask[i] >= 0 && Mask[i] < Size) {
6985 V1Mask[i] = Mask[i];
6987 } else if (Mask[i] >= Size) {
6988 V2Mask[i] = Mask[i] - Size;
6989 BlendMask[i] = i + Size;
6992 // Try to lower with the simpler initial blend strategy unless one of the
6993 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6994 // shuffle may be able to fold with a load or other benefit. However, when
6995 // we'll have to do 2x as many shuffles in order to achieve this, blending
6996 // first is a better strategy.
6997 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6998 if (SDValue BlendPerm =
6999 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7002 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7003 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7004 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7007 /// \brief Try to lower a vector shuffle as a byte rotation.
7009 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7010 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7011 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7012 /// try to generically lower a vector shuffle through such an pattern. It
7013 /// does not check for the profitability of lowering either as PALIGNR or
7014 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7015 /// This matches shuffle vectors that look like:
7017 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7019 /// Essentially it concatenates V1 and V2, shifts right by some number of
7020 /// elements, and takes the low elements as the result. Note that while this is
7021 /// specified as a *right shift* because x86 is little-endian, it is a *left
7022 /// rotate* of the vector lanes.
7023 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7026 const X86Subtarget *Subtarget,
7027 SelectionDAG &DAG) {
7028 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7030 int NumElts = Mask.size();
7031 int NumLanes = VT.getSizeInBits() / 128;
7032 int NumLaneElts = NumElts / NumLanes;
7034 // We need to detect various ways of spelling a rotation:
7035 // [11, 12, 13, 14, 15, 0, 1, 2]
7036 // [-1, 12, 13, 14, -1, -1, 1, -1]
7037 // [-1, -1, -1, -1, -1, -1, 1, 2]
7038 // [ 3, 4, 5, 6, 7, 8, 9, 10]
7039 // [-1, 4, 5, 6, -1, -1, 9, -1]
7040 // [-1, 4, 5, 6, -1, -1, -1, -1]
7043 for (int l = 0; l < NumElts; l += NumLaneElts) {
7044 for (int i = 0; i < NumLaneElts; ++i) {
7045 if (Mask[l + i] == -1)
7047 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7049 // Get the mod-Size index and lane correct it.
7050 int LaneIdx = (Mask[l + i] % NumElts) - l;
7051 // Make sure it was in this lane.
7052 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7055 // Determine where a rotated vector would have started.
7056 int StartIdx = i - LaneIdx;
7058 // The identity rotation isn't interesting, stop.
7061 // If we found the tail of a vector the rotation must be the missing
7062 // front. If we found the head of a vector, it must be how much of the
7064 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7067 Rotation = CandidateRotation;
7068 else if (Rotation != CandidateRotation)
7069 // The rotations don't match, so we can't match this mask.
7072 // Compute which value this mask is pointing at.
7073 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7075 // Compute which of the two target values this index should be assigned
7076 // to. This reflects whether the high elements are remaining or the low
7077 // elements are remaining.
7078 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7080 // Either set up this value if we've not encountered it before, or check
7081 // that it remains consistent.
7084 else if (TargetV != MaskV)
7085 // This may be a rotation, but it pulls from the inputs in some
7086 // unsupported interleaving.
7091 // Check that we successfully analyzed the mask, and normalize the results.
7092 assert(Rotation != 0 && "Failed to locate a viable rotation!");
7093 assert((Lo || Hi) && "Failed to find a rotated input vector!");
7099 // The actual rotate instruction rotates bytes, so we need to scale the
7100 // rotation based on how many bytes are in the vector lane.
7101 int Scale = 16 / NumLaneElts;
7103 // SSSE3 targets can use the palignr instruction.
7104 if (Subtarget->hasSSSE3()) {
7105 // Cast the inputs to i8 vector of correct length to match PALIGNR.
7106 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7107 Lo = DAG.getBitcast(AlignVT, Lo);
7108 Hi = DAG.getBitcast(AlignVT, Hi);
7110 return DAG.getBitcast(
7111 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7112 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7115 assert(VT.getSizeInBits() == 128 &&
7116 "Rotate-based lowering only supports 128-bit lowering!");
7117 assert(Mask.size() <= 16 &&
7118 "Can shuffle at most 16 bytes in a 128-bit vector!");
7120 // Default SSE2 implementation
7121 int LoByteShift = 16 - Rotation * Scale;
7122 int HiByteShift = Rotation * Scale;
7124 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7125 Lo = DAG.getBitcast(MVT::v2i64, Lo);
7126 Hi = DAG.getBitcast(MVT::v2i64, Hi);
7128 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7129 DAG.getConstant(LoByteShift, DL, MVT::i8));
7130 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7131 DAG.getConstant(HiByteShift, DL, MVT::i8));
7132 return DAG.getBitcast(VT,
7133 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7136 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7138 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7139 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7140 /// matches elements from one of the input vectors shuffled to the left or
7141 /// right with zeroable elements 'shifted in'. It handles both the strictly
7142 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7145 /// PSHL : (little-endian) left bit shift.
7146 /// [ zz, 0, zz, 2 ]
7147 /// [ -1, 4, zz, -1 ]
7148 /// PSRL : (little-endian) right bit shift.
7150 /// [ -1, -1, 7, zz]
7151 /// PSLLDQ : (little-endian) left byte shift
7152 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
7153 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
7154 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
7155 /// PSRLDQ : (little-endian) right byte shift
7156 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
7157 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
7158 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
7159 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7160 SDValue V2, ArrayRef<int> Mask,
7161 SelectionDAG &DAG) {
7162 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7164 int Size = Mask.size();
7165 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7167 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7168 for (int i = 0; i < Size; i += Scale)
7169 for (int j = 0; j < Shift; ++j)
7170 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7176 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7177 for (int i = 0; i != Size; i += Scale) {
7178 unsigned Pos = Left ? i + Shift : i;
7179 unsigned Low = Left ? i : i + Shift;
7180 unsigned Len = Scale - Shift;
7181 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7182 Low + (V == V1 ? 0 : Size)))
7186 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7187 bool ByteShift = ShiftEltBits > 64;
7188 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7189 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7190 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7192 // Normalize the scale for byte shifts to still produce an i64 element
7194 Scale = ByteShift ? Scale / 2 : Scale;
7196 // We need to round trip through the appropriate type for the shift.
7197 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7198 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7199 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7200 "Illegal integer vector type");
7201 V = DAG.getBitcast(ShiftVT, V);
7203 V = DAG.getNode(OpCode, DL, ShiftVT, V,
7204 DAG.getConstant(ShiftAmt, DL, MVT::i8));
7205 return DAG.getBitcast(VT, V);
7208 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7209 // keep doubling the size of the integer elements up to that. We can
7210 // then shift the elements of the integer vector by whole multiples of
7211 // their width within the elements of the larger integer vector. Test each
7212 // multiple to see if we can find a match with the moved element indices
7213 // and that the shifted in elements are all zeroable.
7214 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7215 for (int Shift = 1; Shift != Scale; ++Shift)
7216 for (bool Left : {true, false})
7217 if (CheckZeros(Shift, Scale, Left))
7218 for (SDValue V : {V1, V2})
7219 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7226 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7227 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7228 SDValue V2, ArrayRef<int> Mask,
7229 SelectionDAG &DAG) {
7230 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7231 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7233 int Size = Mask.size();
7234 int HalfSize = Size / 2;
7235 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7237 // Upper half must be undefined.
7238 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7241 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7242 // Remainder of lower half result is zero and upper half is all undef.
7243 auto LowerAsEXTRQ = [&]() {
7244 // Determine the extraction length from the part of the
7245 // lower half that isn't zeroable.
7247 for (; Len >= 0; --Len)
7248 if (!Zeroable[Len - 1])
7250 assert(Len > 0 && "Zeroable shuffle mask");
7252 // Attempt to match first Len sequential elements from the lower half.
7255 for (int i = 0; i != Len; ++i) {
7259 SDValue &V = (M < Size ? V1 : V2);
7262 // All mask elements must be in the lower half.
7266 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7277 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7278 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7279 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7280 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7281 DAG.getConstant(BitLen, DL, MVT::i8),
7282 DAG.getConstant(BitIdx, DL, MVT::i8));
7285 if (SDValue ExtrQ = LowerAsEXTRQ())
7288 // INSERTQ: Extract lowest Len elements from lower half of second source and
7289 // insert over first source, starting at Idx.
7290 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7291 auto LowerAsInsertQ = [&]() {
7292 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7295 // Attempt to match first source from mask before insertion point.
7296 if (isUndefInRange(Mask, 0, Idx)) {
7298 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7300 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7306 // Extend the extraction length looking to match both the insertion of
7307 // the second source and the remaining elements of the first.
7308 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7313 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7315 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7321 // Match the remaining elements of the lower half.
7322 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7324 } else if ((!Base || (Base == V1)) &&
7325 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7327 } else if ((!Base || (Base == V2)) &&
7328 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7335 // We may not have a base (first source) - this can safely be undefined.
7337 Base = DAG.getUNDEF(VT);
7339 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7340 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7341 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7342 DAG.getConstant(BitLen, DL, MVT::i8),
7343 DAG.getConstant(BitIdx, DL, MVT::i8));
7350 if (SDValue InsertQ = LowerAsInsertQ())
7356 /// \brief Lower a vector shuffle as a zero or any extension.
7358 /// Given a specific number of elements, element bit width, and extension
7359 /// stride, produce either a zero or any extension based on the available
7360 /// features of the subtarget. The extended elements are consecutive and
7361 /// begin and can start from an offseted element index in the input; to
7362 /// avoid excess shuffling the offset must either being in the bottom lane
7363 /// or at the start of a higher lane. All extended elements must be from
7365 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7366 SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7367 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7368 assert(Scale > 1 && "Need a scale to extend.");
7369 int EltBits = VT.getScalarSizeInBits();
7370 int NumElements = VT.getVectorNumElements();
7371 int NumEltsPerLane = 128 / EltBits;
7372 int OffsetLane = Offset / NumEltsPerLane;
7373 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7374 "Only 8, 16, and 32 bit elements can be extended.");
7375 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7376 assert(0 <= Offset && "Extension offset must be positive.");
7377 assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7378 "Extension offset must be in the first lane or start an upper lane.");
7380 // Check that an index is in same lane as the base offset.
7381 auto SafeOffset = [&](int Idx) {
7382 return OffsetLane == (Idx / NumEltsPerLane);
7385 // Shift along an input so that the offset base moves to the first element.
7386 auto ShuffleOffset = [&](SDValue V) {
7390 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7391 for (int i = 0; i * Scale < NumElements; ++i) {
7392 int SrcIdx = i + Offset;
7393 ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7395 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7398 // Found a valid zext mask! Try various lowering strategies based on the
7399 // input type and available ISA extensions.
7400 if (Subtarget->hasSSE41()) {
7401 // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7402 // PUNPCK will catch this in a later shuffle match.
7403 if (Offset && Scale == 2 && VT.getSizeInBits() == 128)
7405 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7406 NumElements / Scale);
7407 InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7408 return DAG.getBitcast(VT, InputV);
7411 assert(VT.getSizeInBits() == 128 && "Only 128-bit vectors can be extended.");
7413 // For any extends we can cheat for larger element sizes and use shuffle
7414 // instructions that can fold with a load and/or copy.
7415 if (AnyExt && EltBits == 32) {
7416 int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7418 return DAG.getBitcast(
7419 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7420 DAG.getBitcast(MVT::v4i32, InputV),
7421 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7423 if (AnyExt && EltBits == 16 && Scale > 2) {
7424 int PSHUFDMask[4] = {Offset / 2, -1,
7425 SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7426 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7427 DAG.getBitcast(MVT::v4i32, InputV),
7428 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7429 int PSHUFWMask[4] = {1, -1, -1, -1};
7430 unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7431 return DAG.getBitcast(
7432 VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7433 DAG.getBitcast(MVT::v8i16, InputV),
7434 getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7437 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7439 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7440 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7441 assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7443 int LoIdx = Offset * EltBits;
7444 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7445 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7446 DAG.getConstant(EltBits, DL, MVT::i8),
7447 DAG.getConstant(LoIdx, DL, MVT::i8)));
7449 if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7450 !SafeOffset(Offset + 1))
7451 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7453 int HiIdx = (Offset + 1) * EltBits;
7454 SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7455 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7456 DAG.getConstant(EltBits, DL, MVT::i8),
7457 DAG.getConstant(HiIdx, DL, MVT::i8)));
7458 return DAG.getNode(ISD::BITCAST, DL, VT,
7459 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7462 // If this would require more than 2 unpack instructions to expand, use
7463 // pshufb when available. We can only use more than 2 unpack instructions
7464 // when zero extending i8 elements which also makes it easier to use pshufb.
7465 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7466 assert(NumElements == 16 && "Unexpected byte vector width!");
7467 SDValue PSHUFBMask[16];
7468 for (int i = 0; i < 16; ++i) {
7469 int Idx = Offset + (i / Scale);
7470 PSHUFBMask[i] = DAG.getConstant(
7471 (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7473 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7474 return DAG.getBitcast(VT,
7475 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7476 DAG.getNode(ISD::BUILD_VECTOR, DL,
7477 MVT::v16i8, PSHUFBMask)));
7480 // If we are extending from an (odd)offset, shuffle them by 1 element.
7482 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7483 for (int i = 1; i < NumElements; ++i)
7485 InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7489 // Otherwise emit a sequence of unpacks.
7491 unsigned UnpackLoHi = X86ISD::UNPCKL;
7492 if (Offset >= (NumElements / 2)) {
7493 UnpackLoHi = X86ISD::UNPCKH;
7494 Offset -= (NumElements / 2);
7497 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7498 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7499 : getZeroVector(InputVT, Subtarget, DAG, DL);
7500 InputV = DAG.getBitcast(InputVT, InputV);
7501 InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7505 } while (Scale > 1);
7506 return DAG.getBitcast(VT, InputV);
7509 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7511 /// This routine will try to do everything in its power to cleverly lower
7512 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7513 /// check for the profitability of this lowering, it tries to aggressively
7514 /// match this pattern. It will use all of the micro-architectural details it
7515 /// can to emit an efficient lowering. It handles both blends with all-zero
7516 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7517 /// masking out later).
7519 /// The reason we have dedicated lowering for zext-style shuffles is that they
7520 /// are both incredibly common and often quite performance sensitive.
7521 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7522 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7523 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7524 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7526 int Bits = VT.getSizeInBits();
7527 int NumLanes = Bits / 128;
7528 int NumElements = VT.getVectorNumElements();
7529 int NumEltsPerLane = NumElements / NumLanes;
7530 assert(VT.getScalarSizeInBits() <= 32 &&
7531 "Exceeds 32-bit integer zero extension limit");
7532 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7534 // Define a helper function to check a particular ext-scale and lower to it if
7536 auto Lower = [&](int Scale) -> SDValue {
7541 for (int i = 0; i < NumElements; ++i) {
7544 continue; // Valid anywhere but doesn't tell us anything.
7545 if (i % Scale != 0) {
7546 // Each of the extended elements need to be zeroable.
7550 // We no longer are in the anyext case.
7555 // Each of the base elements needs to be consecutive indices into the
7556 // same input vector.
7557 SDValue V = M < NumElements ? V1 : V2;
7558 M = M % NumElements;
7561 Offset = M - (i / Scale);
7562 } else if (InputV != V)
7563 return SDValue(); // Flip-flopping inputs.
7565 // Offset must start in the lowest 128-bit lane or at the start of an
7567 // FIXME: Is it ever worth allowing a negative base offset?
7568 if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7569 (Offset % NumEltsPerLane) == 0))
7572 // If we are offsetting, all referenced entries must come from the same
7574 if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7577 if ((M % NumElements) != (Offset + (i / Scale)))
7578 return SDValue(); // Non-consecutive strided elements.
7582 // If we fail to find an input, we have a zero-shuffle which should always
7583 // have already been handled.
7584 // FIXME: Maybe handle this here in case during blending we end up with one?
7588 // If we are offsetting, don't extend if we only match a single input, we
7589 // can always do better by using a basic PSHUF or PUNPCK.
7590 if (Offset != 0 && Matches < 2)
7593 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7594 DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7597 // The widest scale possible for extending is to a 64-bit integer.
7598 assert(Bits % 64 == 0 &&
7599 "The number of bits in a vector must be divisible by 64 on x86!");
7600 int NumExtElements = Bits / 64;
7602 // Each iteration, try extending the elements half as much, but into twice as
7604 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7605 assert(NumElements % NumExtElements == 0 &&
7606 "The input vector size must be divisible by the extended size.");
7607 if (SDValue V = Lower(NumElements / NumExtElements))
7611 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7615 // Returns one of the source operands if the shuffle can be reduced to a
7616 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7617 auto CanZExtLowHalf = [&]() {
7618 for (int i = NumElements / 2; i != NumElements; ++i)
7621 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7623 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7628 if (SDValue V = CanZExtLowHalf()) {
7629 V = DAG.getBitcast(MVT::v2i64, V);
7630 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7631 return DAG.getBitcast(VT, V);
7634 // No viable ext lowering found.
7638 /// \brief Try to get a scalar value for a specific element of a vector.
7640 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7641 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7642 SelectionDAG &DAG) {
7643 MVT VT = V.getSimpleValueType();
7644 MVT EltVT = VT.getVectorElementType();
7645 while (V.getOpcode() == ISD::BITCAST)
7646 V = V.getOperand(0);
7647 // If the bitcasts shift the element size, we can't extract an equivalent
7649 MVT NewVT = V.getSimpleValueType();
7650 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7653 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7654 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7655 // Ensure the scalar operand is the same size as the destination.
7656 // FIXME: Add support for scalar truncation where possible.
7657 SDValue S = V.getOperand(Idx);
7658 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7659 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7665 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7667 /// This is particularly important because the set of instructions varies
7668 /// significantly based on whether the operand is a load or not.
7669 static bool isShuffleFoldableLoad(SDValue V) {
7670 while (V.getOpcode() == ISD::BITCAST)
7671 V = V.getOperand(0);
7673 return ISD::isNON_EXTLoad(V.getNode());
7676 /// \brief Try to lower insertion of a single element into a zero vector.
7678 /// This is a common pattern that we have especially efficient patterns to lower
7679 /// across all subtarget feature sets.
7680 static SDValue lowerVectorShuffleAsElementInsertion(
7681 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7682 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7683 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7685 MVT EltVT = VT.getVectorElementType();
7687 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7688 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7690 bool IsV1Zeroable = true;
7691 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7692 if (i != V2Index && !Zeroable[i]) {
7693 IsV1Zeroable = false;
7697 // Check for a single input from a SCALAR_TO_VECTOR node.
7698 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7699 // all the smarts here sunk into that routine. However, the current
7700 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7701 // vector shuffle lowering is dead.
7702 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7704 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7705 // We need to zext the scalar if it is smaller than an i32.
7706 V2S = DAG.getBitcast(EltVT, V2S);
7707 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7708 // Using zext to expand a narrow element won't work for non-zero
7713 // Zero-extend directly to i32.
7715 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7717 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7718 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7719 EltVT == MVT::i16) {
7720 // Either not inserting from the low element of the input or the input
7721 // element size is too small to use VZEXT_MOVL to clear the high bits.
7725 if (!IsV1Zeroable) {
7726 // If V1 can't be treated as a zero vector we have fewer options to lower
7727 // this. We can't support integer vectors or non-zero targets cheaply, and
7728 // the V1 elements can't be permuted in any way.
7729 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7730 if (!VT.isFloatingPoint() || V2Index != 0)
7732 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7733 V1Mask[V2Index] = -1;
7734 if (!isNoopShuffleMask(V1Mask))
7736 // This is essentially a special case blend operation, but if we have
7737 // general purpose blend operations, they are always faster. Bail and let
7738 // the rest of the lowering handle these as blends.
7739 if (Subtarget->hasSSE41())
7742 // Otherwise, use MOVSD or MOVSS.
7743 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7744 "Only two types of floating point element types to handle!");
7745 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7749 // This lowering only works for the low element with floating point vectors.
7750 if (VT.isFloatingPoint() && V2Index != 0)
7753 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7755 V2 = DAG.getBitcast(VT, V2);
7758 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7759 // the desired position. Otherwise it is more efficient to do a vector
7760 // shift left. We know that we can do a vector shift left because all
7761 // the inputs are zero.
7762 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7763 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7764 V2Shuffle[V2Index] = 0;
7765 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7767 V2 = DAG.getBitcast(MVT::v2i64, V2);
7769 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7770 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7771 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7772 DAG.getDataLayout(), VT)));
7773 V2 = DAG.getBitcast(VT, V2);
7779 /// \brief Try to lower broadcast of a single element.
7781 /// For convenience, this code also bundles all of the subtarget feature set
7782 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7783 /// a convenient way to factor it out.
7784 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7786 const X86Subtarget *Subtarget,
7787 SelectionDAG &DAG) {
7788 if (!Subtarget->hasAVX())
7790 if (VT.isInteger() && !Subtarget->hasAVX2())
7793 // Check that the mask is a broadcast.
7794 int BroadcastIdx = -1;
7796 if (M >= 0 && BroadcastIdx == -1)
7798 else if (M >= 0 && M != BroadcastIdx)
7801 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7802 "a sorted mask where the broadcast "
7805 // Go up the chain of (vector) values to find a scalar load that we can
7806 // combine with the broadcast.
7808 switch (V.getOpcode()) {
7809 case ISD::CONCAT_VECTORS: {
7810 int OperandSize = Mask.size() / V.getNumOperands();
7811 V = V.getOperand(BroadcastIdx / OperandSize);
7812 BroadcastIdx %= OperandSize;
7816 case ISD::INSERT_SUBVECTOR: {
7817 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7818 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7822 int BeginIdx = (int)ConstantIdx->getZExtValue();
7824 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7825 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7826 BroadcastIdx -= BeginIdx;
7837 // Check if this is a broadcast of a scalar. We special case lowering
7838 // for scalars so that we can more effectively fold with loads.
7839 // First, look through bitcast: if the original value has a larger element
7840 // type than the shuffle, the broadcast element is in essence truncated.
7841 // Make that explicit to ease folding.
7842 if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7843 EVT EltVT = VT.getVectorElementType();
7844 SDValue V0 = V.getOperand(0);
7845 EVT V0VT = V0.getValueType();
7847 if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7848 ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7849 (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7850 V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7855 // Also check the simpler case, where we can directly reuse the scalar.
7856 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7857 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7858 V = V.getOperand(BroadcastIdx);
7860 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7861 // Only AVX2 has register broadcasts.
7862 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7864 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7865 // We can't broadcast from a vector register without AVX2, and we can only
7866 // broadcast from the zero-element of a vector register.
7870 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7873 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7874 // INSERTPS when the V1 elements are already in the correct locations
7875 // because otherwise we can just always use two SHUFPS instructions which
7876 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7877 // perform INSERTPS if a single V1 element is out of place and all V2
7878 // elements are zeroable.
7879 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7881 SelectionDAG &DAG) {
7882 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7883 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7884 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7885 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7887 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7890 int V1DstIndex = -1;
7891 int V2DstIndex = -1;
7892 bool V1UsedInPlace = false;
7894 for (int i = 0; i < 4; ++i) {
7895 // Synthesize a zero mask from the zeroable elements (includes undefs).
7901 // Flag if we use any V1 inputs in place.
7903 V1UsedInPlace = true;
7907 // We can only insert a single non-zeroable element.
7908 if (V1DstIndex != -1 || V2DstIndex != -1)
7912 // V1 input out of place for insertion.
7915 // V2 input for insertion.
7920 // Don't bother if we have no (non-zeroable) element for insertion.
7921 if (V1DstIndex == -1 && V2DstIndex == -1)
7924 // Determine element insertion src/dst indices. The src index is from the
7925 // start of the inserted vector, not the start of the concatenated vector.
7926 unsigned V2SrcIndex = 0;
7927 if (V1DstIndex != -1) {
7928 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7929 // and don't use the original V2 at all.
7930 V2SrcIndex = Mask[V1DstIndex];
7931 V2DstIndex = V1DstIndex;
7934 V2SrcIndex = Mask[V2DstIndex] - 4;
7937 // If no V1 inputs are used in place, then the result is created only from
7938 // the zero mask and the V2 insertion - so remove V1 dependency.
7940 V1 = DAG.getUNDEF(MVT::v4f32);
7942 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7943 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7945 // Insert the V2 element into the desired position.
7947 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7948 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7951 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7952 /// UNPCK instruction.
7954 /// This specifically targets cases where we end up with alternating between
7955 /// the two inputs, and so can permute them into something that feeds a single
7956 /// UNPCK instruction. Note that this routine only targets integer vectors
7957 /// because for floating point vectors we have a generalized SHUFPS lowering
7958 /// strategy that handles everything that doesn't *exactly* match an unpack,
7959 /// making this clever lowering unnecessary.
7960 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
7961 SDValue V1, SDValue V2,
7963 SelectionDAG &DAG) {
7964 assert(!VT.isFloatingPoint() &&
7965 "This routine only supports integer vectors.");
7966 assert(!isSingleInputShuffleMask(Mask) &&
7967 "This routine should only be used when blending two inputs.");
7968 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7970 int Size = Mask.size();
7972 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7973 return M >= 0 && M % Size < Size / 2;
7975 int NumHiInputs = std::count_if(
7976 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7978 bool UnpackLo = NumLoInputs >= NumHiInputs;
7980 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7981 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7982 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7984 for (int i = 0; i < Size; ++i) {
7988 // Each element of the unpack contains Scale elements from this mask.
7989 int UnpackIdx = i / Scale;
7991 // We only handle the case where V1 feeds the first slots of the unpack.
7992 // We rely on canonicalization to ensure this is the case.
7993 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7996 // Setup the mask for this input. The indexing is tricky as we have to
7997 // handle the unpack stride.
7998 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7999 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8003 // If we will have to shuffle both inputs to use the unpack, check whether
8004 // we can just unpack first and shuffle the result. If so, skip this unpack.
8005 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8006 !isNoopShuffleMask(V2Mask))
8009 // Shuffle the inputs into place.
8010 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8011 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8013 // Cast the inputs to the type we will use to unpack them.
8014 V1 = DAG.getBitcast(UnpackVT, V1);
8015 V2 = DAG.getBitcast(UnpackVT, V2);
8017 // Unpack the inputs and cast the result back to the desired type.
8018 return DAG.getBitcast(
8019 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8023 // We try each unpack from the largest to the smallest to try and find one
8024 // that fits this mask.
8025 int OrigNumElements = VT.getVectorNumElements();
8026 int OrigScalarSize = VT.getScalarSizeInBits();
8027 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8028 int Scale = ScalarSize / OrigScalarSize;
8029 int NumElements = OrigNumElements / Scale;
8030 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8031 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8035 // If none of the unpack-rooted lowerings worked (or were profitable) try an
8037 if (NumLoInputs == 0 || NumHiInputs == 0) {
8038 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8039 "We have to have *some* inputs!");
8040 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8042 // FIXME: We could consider the total complexity of the permute of each
8043 // possible unpacking. Or at the least we should consider how many
8044 // half-crossings are created.
8045 // FIXME: We could consider commuting the unpacks.
8047 SmallVector<int, 32> PermMask;
8048 PermMask.assign(Size, -1);
8049 for (int i = 0; i < Size; ++i) {
8053 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8056 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8058 return DAG.getVectorShuffle(
8059 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8061 DAG.getUNDEF(VT), PermMask);
8067 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8069 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8070 /// support for floating point shuffles but not integer shuffles. These
8071 /// instructions will incur a domain crossing penalty on some chips though so
8072 /// it is better to avoid lowering through this for integer vectors where
8074 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8075 const X86Subtarget *Subtarget,
8076 SelectionDAG &DAG) {
8078 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8079 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8080 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8081 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8082 ArrayRef<int> Mask = SVOp->getMask();
8083 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8085 if (isSingleInputShuffleMask(Mask)) {
8086 // Use low duplicate instructions for masks that match their pattern.
8087 if (Subtarget->hasSSE3())
8088 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8089 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8091 // Straight shuffle of a single input vector. Simulate this by using the
8092 // single input as both of the "inputs" to this instruction..
8093 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8095 if (Subtarget->hasAVX()) {
8096 // If we have AVX, we can use VPERMILPS which will allow folding a load
8097 // into the shuffle.
8098 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8099 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8102 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8103 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8105 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8106 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8108 // If we have a single input, insert that into V1 if we can do so cheaply.
8109 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8110 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8111 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8113 // Try inverting the insertion since for v2 masks it is easy to do and we
8114 // can't reliably sort the mask one way or the other.
8115 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8116 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8117 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8118 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8122 // Try to use one of the special instruction patterns to handle two common
8123 // blend patterns if a zero-blend above didn't work.
8124 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8125 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8126 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8127 // We can either use a special instruction to load over the low double or
8128 // to move just the low double.
8130 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8132 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8134 if (Subtarget->hasSSE41())
8135 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8139 // Use dedicated unpack instructions for masks that match their pattern.
8140 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8141 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8142 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8143 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8145 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8146 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8147 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8150 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8152 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8153 /// the integer unit to minimize domain crossing penalties. However, for blends
8154 /// it falls back to the floating point shuffle operation with appropriate bit
8156 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8157 const X86Subtarget *Subtarget,
8158 SelectionDAG &DAG) {
8160 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8161 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8162 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8163 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8164 ArrayRef<int> Mask = SVOp->getMask();
8165 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8167 if (isSingleInputShuffleMask(Mask)) {
8168 // Check for being able to broadcast a single element.
8169 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8170 Mask, Subtarget, DAG))
8173 // Straight shuffle of a single input vector. For everything from SSE2
8174 // onward this has a single fast instruction with no scary immediates.
8175 // We have to map the mask as it is actually a v4i32 shuffle instruction.
8176 V1 = DAG.getBitcast(MVT::v4i32, V1);
8177 int WidenedMask[4] = {
8178 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8179 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8180 return DAG.getBitcast(
8182 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8183 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8185 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8186 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8187 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8188 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8190 // If we have a blend of two PACKUS operations an the blend aligns with the
8191 // low and half halves, we can just merge the PACKUS operations. This is
8192 // particularly important as it lets us merge shuffles that this routine itself
8194 auto GetPackNode = [](SDValue V) {
8195 while (V.getOpcode() == ISD::BITCAST)
8196 V = V.getOperand(0);
8198 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8200 if (SDValue V1Pack = GetPackNode(V1))
8201 if (SDValue V2Pack = GetPackNode(V2))
8202 return DAG.getBitcast(MVT::v2i64,
8203 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8204 Mask[0] == 0 ? V1Pack.getOperand(0)
8205 : V1Pack.getOperand(1),
8206 Mask[1] == 2 ? V2Pack.getOperand(0)
8207 : V2Pack.getOperand(1)));
8209 // Try to use shift instructions.
8211 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8214 // When loading a scalar and then shuffling it into a vector we can often do
8215 // the insertion cheaply.
8216 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8217 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8219 // Try inverting the insertion since for v2 masks it is easy to do and we
8220 // can't reliably sort the mask one way or the other.
8221 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8222 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8223 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8226 // We have different paths for blend lowering, but they all must use the
8227 // *exact* same predicate.
8228 bool IsBlendSupported = Subtarget->hasSSE41();
8229 if (IsBlendSupported)
8230 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8234 // Use dedicated unpack instructions for masks that match their pattern.
8235 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8236 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8237 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8238 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8240 // Try to use byte rotation instructions.
8241 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8242 if (Subtarget->hasSSSE3())
8243 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8244 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8247 // If we have direct support for blends, we should lower by decomposing into
8248 // a permute. That will be faster than the domain cross.
8249 if (IsBlendSupported)
8250 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8253 // We implement this with SHUFPD which is pretty lame because it will likely
8254 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8255 // However, all the alternatives are still more cycles and newer chips don't
8256 // have this problem. It would be really nice if x86 had better shuffles here.
8257 V1 = DAG.getBitcast(MVT::v2f64, V1);
8258 V2 = DAG.getBitcast(MVT::v2f64, V2);
8259 return DAG.getBitcast(MVT::v2i64,
8260 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8263 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8265 /// This is used to disable more specialized lowerings when the shufps lowering
8266 /// will happen to be efficient.
8267 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8268 // This routine only handles 128-bit shufps.
8269 assert(Mask.size() == 4 && "Unsupported mask size!");
8271 // To lower with a single SHUFPS we need to have the low half and high half
8272 // each requiring a single input.
8273 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8275 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8281 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8283 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8284 /// It makes no assumptions about whether this is the *best* lowering, it simply
8286 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8287 ArrayRef<int> Mask, SDValue V1,
8288 SDValue V2, SelectionDAG &DAG) {
8289 SDValue LowV = V1, HighV = V2;
8290 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8293 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8295 if (NumV2Elements == 1) {
8297 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8300 // Compute the index adjacent to V2Index and in the same half by toggling
8302 int V2AdjIndex = V2Index ^ 1;
8304 if (Mask[V2AdjIndex] == -1) {
8305 // Handles all the cases where we have a single V2 element and an undef.
8306 // This will only ever happen in the high lanes because we commute the
8307 // vector otherwise.
8309 std::swap(LowV, HighV);
8310 NewMask[V2Index] -= 4;
8312 // Handle the case where the V2 element ends up adjacent to a V1 element.
8313 // To make this work, blend them together as the first step.
8314 int V1Index = V2AdjIndex;
8315 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8316 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8317 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8319 // Now proceed to reconstruct the final blend as we have the necessary
8320 // high or low half formed.
8327 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8328 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8330 } else if (NumV2Elements == 2) {
8331 if (Mask[0] < 4 && Mask[1] < 4) {
8332 // Handle the easy case where we have V1 in the low lanes and V2 in the
8336 } else if (Mask[2] < 4 && Mask[3] < 4) {
8337 // We also handle the reversed case because this utility may get called
8338 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8339 // arrange things in the right direction.
8345 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8346 // trying to place elements directly, just blend them and set up the final
8347 // shuffle to place them.
8349 // The first two blend mask elements are for V1, the second two are for
8351 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8352 Mask[2] < 4 ? Mask[2] : Mask[3],
8353 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8354 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8355 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8356 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8358 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8361 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8362 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8363 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8364 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8367 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8368 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8371 /// \brief Lower 4-lane 32-bit floating point shuffles.
8373 /// Uses instructions exclusively from the floating point unit to minimize
8374 /// domain crossing penalties, as these are sufficient to implement all v4f32
8376 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8377 const X86Subtarget *Subtarget,
8378 SelectionDAG &DAG) {
8380 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8381 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8382 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8383 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8384 ArrayRef<int> Mask = SVOp->getMask();
8385 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8388 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8390 if (NumV2Elements == 0) {
8391 // Check for being able to broadcast a single element.
8392 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8393 Mask, Subtarget, DAG))
8396 // Use even/odd duplicate instructions for masks that match their pattern.
8397 if (Subtarget->hasSSE3()) {
8398 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8399 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8400 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8401 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8404 if (Subtarget->hasAVX()) {
8405 // If we have AVX, we can use VPERMILPS which will allow folding a load
8406 // into the shuffle.
8407 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8408 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8411 // Otherwise, use a straight shuffle of a single input vector. We pass the
8412 // input vector to both operands to simulate this with a SHUFPS.
8413 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8414 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8417 // There are special ways we can lower some single-element blends. However, we
8418 // have custom ways we can lower more complex single-element blends below that
8419 // we defer to if both this and BLENDPS fail to match, so restrict this to
8420 // when the V2 input is targeting element 0 of the mask -- that is the fast
8422 if (NumV2Elements == 1 && Mask[0] >= 4)
8423 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8424 Mask, Subtarget, DAG))
8427 if (Subtarget->hasSSE41()) {
8428 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8432 // Use INSERTPS if we can complete the shuffle efficiently.
8433 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8436 if (!isSingleSHUFPSMask(Mask))
8437 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8438 DL, MVT::v4f32, V1, V2, Mask, DAG))
8442 // Use dedicated unpack instructions for masks that match their pattern.
8443 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8444 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8445 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8446 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8447 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8448 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8449 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8450 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8452 // Otherwise fall back to a SHUFPS lowering strategy.
8453 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8456 /// \brief Lower 4-lane i32 vector shuffles.
8458 /// We try to handle these with integer-domain shuffles where we can, but for
8459 /// blends we use the floating point domain blend instructions.
8460 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8461 const X86Subtarget *Subtarget,
8462 SelectionDAG &DAG) {
8464 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8465 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8466 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8467 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8468 ArrayRef<int> Mask = SVOp->getMask();
8469 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8471 // Whenever we can lower this as a zext, that instruction is strictly faster
8472 // than any alternative. It also allows us to fold memory operands into the
8473 // shuffle in many cases.
8474 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8475 Mask, Subtarget, DAG))
8479 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8481 if (NumV2Elements == 0) {
8482 // Check for being able to broadcast a single element.
8483 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8484 Mask, Subtarget, DAG))
8487 // Straight shuffle of a single input vector. For everything from SSE2
8488 // onward this has a single fast instruction with no scary immediates.
8489 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8490 // but we aren't actually going to use the UNPCK instruction because doing
8491 // so prevents folding a load into this instruction or making a copy.
8492 const int UnpackLoMask[] = {0, 0, 1, 1};
8493 const int UnpackHiMask[] = {2, 2, 3, 3};
8494 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8495 Mask = UnpackLoMask;
8496 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8497 Mask = UnpackHiMask;
8499 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8500 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8503 // Try to use shift instructions.
8505 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8508 // There are special ways we can lower some single-element blends.
8509 if (NumV2Elements == 1)
8510 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8511 Mask, Subtarget, DAG))
8514 // We have different paths for blend lowering, but they all must use the
8515 // *exact* same predicate.
8516 bool IsBlendSupported = Subtarget->hasSSE41();
8517 if (IsBlendSupported)
8518 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8522 if (SDValue Masked =
8523 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8526 // Use dedicated unpack instructions for masks that match their pattern.
8527 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8528 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8529 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8530 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8531 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8532 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8533 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8534 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8536 // Try to use byte rotation instructions.
8537 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8538 if (Subtarget->hasSSSE3())
8539 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8540 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8543 // If we have direct support for blends, we should lower by decomposing into
8544 // a permute. That will be faster than the domain cross.
8545 if (IsBlendSupported)
8546 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8549 // Try to lower by permuting the inputs into an unpack instruction.
8550 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8554 // We implement this with SHUFPS because it can blend from two vectors.
8555 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8556 // up the inputs, bypassing domain shift penalties that we would encur if we
8557 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8559 return DAG.getBitcast(
8561 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8562 DAG.getBitcast(MVT::v4f32, V2), Mask));
8565 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8566 /// shuffle lowering, and the most complex part.
8568 /// The lowering strategy is to try to form pairs of input lanes which are
8569 /// targeted at the same half of the final vector, and then use a dword shuffle
8570 /// to place them onto the right half, and finally unpack the paired lanes into
8571 /// their final position.
8573 /// The exact breakdown of how to form these dword pairs and align them on the
8574 /// correct sides is really tricky. See the comments within the function for
8575 /// more of the details.
8577 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8578 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8579 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8580 /// vector, form the analogous 128-bit 8-element Mask.
8581 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8582 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8583 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8584 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8585 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8587 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8588 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8589 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8591 SmallVector<int, 4> LoInputs;
8592 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8593 [](int M) { return M >= 0; });
8594 std::sort(LoInputs.begin(), LoInputs.end());
8595 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8596 SmallVector<int, 4> HiInputs;
8597 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8598 [](int M) { return M >= 0; });
8599 std::sort(HiInputs.begin(), HiInputs.end());
8600 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8602 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8603 int NumHToL = LoInputs.size() - NumLToL;
8605 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8606 int NumHToH = HiInputs.size() - NumLToH;
8607 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8608 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8609 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8610 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8612 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8613 // such inputs we can swap two of the dwords across the half mark and end up
8614 // with <=2 inputs to each half in each half. Once there, we can fall through
8615 // to the generic code below. For example:
8617 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8618 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8620 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8621 // and an existing 2-into-2 on the other half. In this case we may have to
8622 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8623 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8624 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8625 // because any other situation (including a 3-into-1 or 1-into-3 in the other
8626 // half than the one we target for fixing) will be fixed when we re-enter this
8627 // path. We will also combine away any sequence of PSHUFD instructions that
8628 // result into a single instruction. Here is an example of the tricky case:
8630 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8631 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8633 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8635 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8636 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8638 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8639 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8641 // The result is fine to be handled by the generic logic.
8642 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8643 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8644 int AOffset, int BOffset) {
8645 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8646 "Must call this with A having 3 or 1 inputs from the A half.");
8647 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8648 "Must call this with B having 1 or 3 inputs from the B half.");
8649 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8650 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8652 bool ThreeAInputs = AToAInputs.size() == 3;
8654 // Compute the index of dword with only one word among the three inputs in
8655 // a half by taking the sum of the half with three inputs and subtracting
8656 // the sum of the actual three inputs. The difference is the remaining
8659 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8660 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8661 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8662 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8663 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8664 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8665 int TripleNonInputIdx =
8666 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8667 TripleDWord = TripleNonInputIdx / 2;
8669 // We use xor with one to compute the adjacent DWord to whichever one the
8671 OneInputDWord = (OneInput / 2) ^ 1;
8673 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8674 // and BToA inputs. If there is also such a problem with the BToB and AToB
8675 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8676 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8677 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8678 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8679 // Compute how many inputs will be flipped by swapping these DWords. We
8681 // to balance this to ensure we don't form a 3-1 shuffle in the other
8683 int NumFlippedAToBInputs =
8684 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8685 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8686 int NumFlippedBToBInputs =
8687 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8688 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8689 if ((NumFlippedAToBInputs == 1 &&
8690 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8691 (NumFlippedBToBInputs == 1 &&
8692 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8693 // We choose whether to fix the A half or B half based on whether that
8694 // half has zero flipped inputs. At zero, we may not be able to fix it
8695 // with that half. We also bias towards fixing the B half because that
8696 // will more commonly be the high half, and we have to bias one way.
8697 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8698 ArrayRef<int> Inputs) {
8699 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8700 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8701 PinnedIdx ^ 1) != Inputs.end();
8702 // Determine whether the free index is in the flipped dword or the
8703 // unflipped dword based on where the pinned index is. We use this bit
8704 // in an xor to conditionally select the adjacent dword.
8705 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8706 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8707 FixFreeIdx) != Inputs.end();
8708 if (IsFixIdxInput == IsFixFreeIdxInput)
8710 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8711 FixFreeIdx) != Inputs.end();
8712 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8713 "We need to be changing the number of flipped inputs!");
8714 int PSHUFHalfMask[] = {0, 1, 2, 3};
8715 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8716 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8718 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8721 if (M != -1 && M == FixIdx)
8723 else if (M != -1 && M == FixFreeIdx)
8726 if (NumFlippedBToBInputs != 0) {
8728 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8729 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8731 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8732 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8733 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8738 int PSHUFDMask[] = {0, 1, 2, 3};
8739 PSHUFDMask[ADWord] = BDWord;
8740 PSHUFDMask[BDWord] = ADWord;
8743 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8744 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8746 // Adjust the mask to match the new locations of A and B.
8748 if (M != -1 && M/2 == ADWord)
8749 M = 2 * BDWord + M % 2;
8750 else if (M != -1 && M/2 == BDWord)
8751 M = 2 * ADWord + M % 2;
8753 // Recurse back into this routine to re-compute state now that this isn't
8754 // a 3 and 1 problem.
8755 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8758 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8759 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8760 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8761 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8763 // At this point there are at most two inputs to the low and high halves from
8764 // each half. That means the inputs can always be grouped into dwords and
8765 // those dwords can then be moved to the correct half with a dword shuffle.
8766 // We use at most one low and one high word shuffle to collect these paired
8767 // inputs into dwords, and finally a dword shuffle to place them.
8768 int PSHUFLMask[4] = {-1, -1, -1, -1};
8769 int PSHUFHMask[4] = {-1, -1, -1, -1};
8770 int PSHUFDMask[4] = {-1, -1, -1, -1};
8772 // First fix the masks for all the inputs that are staying in their
8773 // original halves. This will then dictate the targets of the cross-half
8775 auto fixInPlaceInputs =
8776 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8777 MutableArrayRef<int> SourceHalfMask,
8778 MutableArrayRef<int> HalfMask, int HalfOffset) {
8779 if (InPlaceInputs.empty())
8781 if (InPlaceInputs.size() == 1) {
8782 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8783 InPlaceInputs[0] - HalfOffset;
8784 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8787 if (IncomingInputs.empty()) {
8788 // Just fix all of the in place inputs.
8789 for (int Input : InPlaceInputs) {
8790 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8791 PSHUFDMask[Input / 2] = Input / 2;
8796 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8797 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8798 InPlaceInputs[0] - HalfOffset;
8799 // Put the second input next to the first so that they are packed into
8800 // a dword. We find the adjacent index by toggling the low bit.
8801 int AdjIndex = InPlaceInputs[0] ^ 1;
8802 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8803 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8804 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8806 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8807 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8809 // Now gather the cross-half inputs and place them into a free dword of
8810 // their target half.
8811 // FIXME: This operation could almost certainly be simplified dramatically to
8812 // look more like the 3-1 fixing operation.
8813 auto moveInputsToRightHalf = [&PSHUFDMask](
8814 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8815 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8816 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8818 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8819 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8821 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8823 int LowWord = Word & ~1;
8824 int HighWord = Word | 1;
8825 return isWordClobbered(SourceHalfMask, LowWord) ||
8826 isWordClobbered(SourceHalfMask, HighWord);
8829 if (IncomingInputs.empty())
8832 if (ExistingInputs.empty()) {
8833 // Map any dwords with inputs from them into the right half.
8834 for (int Input : IncomingInputs) {
8835 // If the source half mask maps over the inputs, turn those into
8836 // swaps and use the swapped lane.
8837 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8838 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8839 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8840 Input - SourceOffset;
8841 // We have to swap the uses in our half mask in one sweep.
8842 for (int &M : HalfMask)
8843 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8845 else if (M == Input)
8846 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8848 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8849 Input - SourceOffset &&
8850 "Previous placement doesn't match!");
8852 // Note that this correctly re-maps both when we do a swap and when
8853 // we observe the other side of the swap above. We rely on that to
8854 // avoid swapping the members of the input list directly.
8855 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8858 // Map the input's dword into the correct half.
8859 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8860 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8862 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8864 "Previous placement doesn't match!");
8867 // And just directly shift any other-half mask elements to be same-half
8868 // as we will have mirrored the dword containing the element into the
8869 // same position within that half.
8870 for (int &M : HalfMask)
8871 if (M >= SourceOffset && M < SourceOffset + 4) {
8872 M = M - SourceOffset + DestOffset;
8873 assert(M >= 0 && "This should never wrap below zero!");
8878 // Ensure we have the input in a viable dword of its current half. This
8879 // is particularly tricky because the original position may be clobbered
8880 // by inputs being moved and *staying* in that half.
8881 if (IncomingInputs.size() == 1) {
8882 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8883 int InputFixed = std::find(std::begin(SourceHalfMask),
8884 std::end(SourceHalfMask), -1) -
8885 std::begin(SourceHalfMask) + SourceOffset;
8886 SourceHalfMask[InputFixed - SourceOffset] =
8887 IncomingInputs[0] - SourceOffset;
8888 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8890 IncomingInputs[0] = InputFixed;
8892 } else if (IncomingInputs.size() == 2) {
8893 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8894 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8895 // We have two non-adjacent or clobbered inputs we need to extract from
8896 // the source half. To do this, we need to map them into some adjacent
8897 // dword slot in the source mask.
8898 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8899 IncomingInputs[1] - SourceOffset};
8901 // If there is a free slot in the source half mask adjacent to one of
8902 // the inputs, place the other input in it. We use (Index XOR 1) to
8903 // compute an adjacent index.
8904 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8905 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8906 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8907 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8908 InputsFixed[1] = InputsFixed[0] ^ 1;
8909 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8910 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8911 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8912 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8913 InputsFixed[0] = InputsFixed[1] ^ 1;
8914 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8915 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8916 // The two inputs are in the same DWord but it is clobbered and the
8917 // adjacent DWord isn't used at all. Move both inputs to the free
8919 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8920 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8921 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8922 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8924 // The only way we hit this point is if there is no clobbering
8925 // (because there are no off-half inputs to this half) and there is no
8926 // free slot adjacent to one of the inputs. In this case, we have to
8927 // swap an input with a non-input.
8928 for (int i = 0; i < 4; ++i)
8929 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8930 "We can't handle any clobbers here!");
8931 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8932 "Cannot have adjacent inputs here!");
8934 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8935 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8937 // We also have to update the final source mask in this case because
8938 // it may need to undo the above swap.
8939 for (int &M : FinalSourceHalfMask)
8940 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8941 M = InputsFixed[1] + SourceOffset;
8942 else if (M == InputsFixed[1] + SourceOffset)
8943 M = (InputsFixed[0] ^ 1) + SourceOffset;
8945 InputsFixed[1] = InputsFixed[0] ^ 1;
8948 // Point everything at the fixed inputs.
8949 for (int &M : HalfMask)
8950 if (M == IncomingInputs[0])
8951 M = InputsFixed[0] + SourceOffset;
8952 else if (M == IncomingInputs[1])
8953 M = InputsFixed[1] + SourceOffset;
8955 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8956 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8959 llvm_unreachable("Unhandled input size!");
8962 // Now hoist the DWord down to the right half.
8963 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8964 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8965 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8966 for (int &M : HalfMask)
8967 for (int Input : IncomingInputs)
8969 M = FreeDWord * 2 + Input % 2;
8971 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8972 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8973 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8974 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8976 // Now enact all the shuffles we've computed to move the inputs into their
8978 if (!isNoopShuffleMask(PSHUFLMask))
8979 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8980 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8981 if (!isNoopShuffleMask(PSHUFHMask))
8982 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8983 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8984 if (!isNoopShuffleMask(PSHUFDMask))
8987 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8988 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8990 // At this point, each half should contain all its inputs, and we can then
8991 // just shuffle them into their final position.
8992 assert(std::count_if(LoMask.begin(), LoMask.end(),
8993 [](int M) { return M >= 4; }) == 0 &&
8994 "Failed to lift all the high half inputs to the low mask!");
8995 assert(std::count_if(HiMask.begin(), HiMask.end(),
8996 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8997 "Failed to lift all the low half inputs to the high mask!");
8999 // Do a half shuffle for the low mask.
9000 if (!isNoopShuffleMask(LoMask))
9001 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9002 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9004 // Do a half shuffle with the high mask after shifting its values down.
9005 for (int &M : HiMask)
9008 if (!isNoopShuffleMask(HiMask))
9009 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9010 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9015 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9016 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9017 SDValue V2, ArrayRef<int> Mask,
9018 SelectionDAG &DAG, bool &V1InUse,
9020 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9026 int Size = Mask.size();
9027 int Scale = 16 / Size;
9028 for (int i = 0; i < 16; ++i) {
9029 if (Mask[i / Scale] == -1) {
9030 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9032 const int ZeroMask = 0x80;
9033 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9035 int V2Idx = Mask[i / Scale] < Size
9037 : (Mask[i / Scale] - Size) * Scale + i % Scale;
9038 if (Zeroable[i / Scale])
9039 V1Idx = V2Idx = ZeroMask;
9040 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9041 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9042 V1InUse |= (ZeroMask != V1Idx);
9043 V2InUse |= (ZeroMask != V2Idx);
9048 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9049 DAG.getBitcast(MVT::v16i8, V1),
9050 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9052 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9053 DAG.getBitcast(MVT::v16i8, V2),
9054 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9056 // If we need shuffled inputs from both, blend the two.
9058 if (V1InUse && V2InUse)
9059 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9061 V = V1InUse ? V1 : V2;
9063 // Cast the result back to the correct type.
9064 return DAG.getBitcast(VT, V);
9067 /// \brief Generic lowering of 8-lane i16 shuffles.
9069 /// This handles both single-input shuffles and combined shuffle/blends with
9070 /// two inputs. The single input shuffles are immediately delegated to
9071 /// a dedicated lowering routine.
9073 /// The blends are lowered in one of three fundamental ways. If there are few
9074 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9075 /// of the input is significantly cheaper when lowered as an interleaving of
9076 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9077 /// halves of the inputs separately (making them have relatively few inputs)
9078 /// and then concatenate them.
9079 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9080 const X86Subtarget *Subtarget,
9081 SelectionDAG &DAG) {
9083 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9084 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9085 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9086 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9087 ArrayRef<int> OrigMask = SVOp->getMask();
9088 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9089 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9090 MutableArrayRef<int> Mask(MaskStorage);
9092 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9094 // Whenever we can lower this as a zext, that instruction is strictly faster
9095 // than any alternative.
9096 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9097 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9100 auto isV1 = [](int M) { return M >= 0 && M < 8; };
9102 auto isV2 = [](int M) { return M >= 8; };
9104 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9106 if (NumV2Inputs == 0) {
9107 // Check for being able to broadcast a single element.
9108 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9109 Mask, Subtarget, DAG))
9112 // Try to use shift instructions.
9114 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9117 // Use dedicated unpack instructions for masks that match their pattern.
9118 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
9119 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
9120 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
9121 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
9123 // Try to use byte rotation instructions.
9124 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9125 Mask, Subtarget, DAG))
9128 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9132 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9133 "All single-input shuffles should be canonicalized to be V1-input "
9136 // Try to use shift instructions.
9138 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9141 // See if we can use SSE4A Extraction / Insertion.
9142 if (Subtarget->hasSSE4A())
9143 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9146 // There are special ways we can lower some single-element blends.
9147 if (NumV2Inputs == 1)
9148 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9149 Mask, Subtarget, DAG))
9152 // We have different paths for blend lowering, but they all must use the
9153 // *exact* same predicate.
9154 bool IsBlendSupported = Subtarget->hasSSE41();
9155 if (IsBlendSupported)
9156 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9160 if (SDValue Masked =
9161 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9164 // Use dedicated unpack instructions for masks that match their pattern.
9165 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
9166 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9167 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
9168 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9170 // Try to use byte rotation instructions.
9171 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9172 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9175 if (SDValue BitBlend =
9176 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9179 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9183 // If we can't directly blend but can use PSHUFB, that will be better as it
9184 // can both shuffle and set up the inefficient blend.
9185 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9186 bool V1InUse, V2InUse;
9187 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9191 // We can always bit-blend if we have to so the fallback strategy is to
9192 // decompose into single-input permutes and blends.
9193 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9197 /// \brief Check whether a compaction lowering can be done by dropping even
9198 /// elements and compute how many times even elements must be dropped.
9200 /// This handles shuffles which take every Nth element where N is a power of
9201 /// two. Example shuffle masks:
9203 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
9204 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9205 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
9206 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
9207 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
9208 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
9210 /// Any of these lanes can of course be undef.
9212 /// This routine only supports N <= 3.
9213 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9216 /// \returns N above, or the number of times even elements must be dropped if
9217 /// there is such a number. Otherwise returns zero.
9218 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9219 // Figure out whether we're looping over two inputs or just one.
9220 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9222 // The modulus for the shuffle vector entries is based on whether this is
9223 // a single input or not.
9224 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9225 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9226 "We should only be called with masks with a power-of-2 size!");
9228 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9230 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9231 // and 2^3 simultaneously. This is because we may have ambiguity with
9232 // partially undef inputs.
9233 bool ViableForN[3] = {true, true, true};
9235 for (int i = 0, e = Mask.size(); i < e; ++i) {
9236 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9241 bool IsAnyViable = false;
9242 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9243 if (ViableForN[j]) {
9246 // The shuffle mask must be equal to (i * 2^N) % M.
9247 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9250 ViableForN[j] = false;
9252 // Early exit if we exhaust the possible powers of two.
9257 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9261 // Return 0 as there is no viable power of two.
9265 /// \brief Generic lowering of v16i8 shuffles.
9267 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9268 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9269 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9270 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9272 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9273 const X86Subtarget *Subtarget,
9274 SelectionDAG &DAG) {
9276 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9277 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9278 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9279 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9280 ArrayRef<int> Mask = SVOp->getMask();
9281 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9283 // Try to use shift instructions.
9285 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9288 // Try to use byte rotation instructions.
9289 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9290 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9293 // Try to use a zext lowering.
9294 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9295 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9298 // See if we can use SSE4A Extraction / Insertion.
9299 if (Subtarget->hasSSE4A())
9300 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9304 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9306 // For single-input shuffles, there are some nicer lowering tricks we can use.
9307 if (NumV2Elements == 0) {
9308 // Check for being able to broadcast a single element.
9309 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9310 Mask, Subtarget, DAG))
9313 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9314 // Notably, this handles splat and partial-splat shuffles more efficiently.
9315 // However, it only makes sense if the pre-duplication shuffle simplifies
9316 // things significantly. Currently, this means we need to be able to
9317 // express the pre-duplication shuffle as an i16 shuffle.
9319 // FIXME: We should check for other patterns which can be widened into an
9320 // i16 shuffle as well.
9321 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9322 for (int i = 0; i < 16; i += 2)
9323 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9328 auto tryToWidenViaDuplication = [&]() -> SDValue {
9329 if (!canWidenViaDuplication(Mask))
9331 SmallVector<int, 4> LoInputs;
9332 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9333 [](int M) { return M >= 0 && M < 8; });
9334 std::sort(LoInputs.begin(), LoInputs.end());
9335 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9337 SmallVector<int, 4> HiInputs;
9338 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9339 [](int M) { return M >= 8; });
9340 std::sort(HiInputs.begin(), HiInputs.end());
9341 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9344 bool TargetLo = LoInputs.size() >= HiInputs.size();
9345 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9346 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9348 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9349 SmallDenseMap<int, int, 8> LaneMap;
9350 for (int I : InPlaceInputs) {
9351 PreDupI16Shuffle[I/2] = I/2;
9354 int j = TargetLo ? 0 : 4, je = j + 4;
9355 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9356 // Check if j is already a shuffle of this input. This happens when
9357 // there are two adjacent bytes after we move the low one.
9358 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9359 // If we haven't yet mapped the input, search for a slot into which
9361 while (j < je && PreDupI16Shuffle[j] != -1)
9365 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9368 // Map this input with the i16 shuffle.
9369 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9372 // Update the lane map based on the mapping we ended up with.
9373 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9375 V1 = DAG.getBitcast(
9377 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9378 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9380 // Unpack the bytes to form the i16s that will be shuffled into place.
9381 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9382 MVT::v16i8, V1, V1);
9384 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9385 for (int i = 0; i < 16; ++i)
9386 if (Mask[i] != -1) {
9387 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9388 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9389 if (PostDupI16Shuffle[i / 2] == -1)
9390 PostDupI16Shuffle[i / 2] = MappedMask;
9392 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9393 "Conflicting entrties in the original shuffle!");
9395 return DAG.getBitcast(
9397 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9398 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9400 if (SDValue V = tryToWidenViaDuplication())
9404 if (SDValue Masked =
9405 lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9408 // Use dedicated unpack instructions for masks that match their pattern.
9409 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9410 0, 16, 1, 17, 2, 18, 3, 19,
9412 4, 20, 5, 21, 6, 22, 7, 23}))
9413 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9414 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9415 8, 24, 9, 25, 10, 26, 11, 27,
9417 12, 28, 13, 29, 14, 30, 15, 31}))
9418 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9420 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9421 // with PSHUFB. It is important to do this before we attempt to generate any
9422 // blends but after all of the single-input lowerings. If the single input
9423 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9424 // want to preserve that and we can DAG combine any longer sequences into
9425 // a PSHUFB in the end. But once we start blending from multiple inputs,
9426 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9427 // and there are *very* few patterns that would actually be faster than the
9428 // PSHUFB approach because of its ability to zero lanes.
9430 // FIXME: The only exceptions to the above are blends which are exact
9431 // interleavings with direct instructions supporting them. We currently don't
9432 // handle those well here.
9433 if (Subtarget->hasSSSE3()) {
9434 bool V1InUse = false;
9435 bool V2InUse = false;
9437 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9438 DAG, V1InUse, V2InUse);
9440 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9441 // do so. This avoids using them to handle blends-with-zero which is
9442 // important as a single pshufb is significantly faster for that.
9443 if (V1InUse && V2InUse) {
9444 if (Subtarget->hasSSE41())
9445 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9446 Mask, Subtarget, DAG))
9449 // We can use an unpack to do the blending rather than an or in some
9450 // cases. Even though the or may be (very minorly) more efficient, we
9451 // preference this lowering because there are common cases where part of
9452 // the complexity of the shuffles goes away when we do the final blend as
9454 // FIXME: It might be worth trying to detect if the unpack-feeding
9455 // shuffles will both be pshufb, in which case we shouldn't bother with
9457 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9458 DL, MVT::v16i8, V1, V2, Mask, DAG))
9465 // There are special ways we can lower some single-element blends.
9466 if (NumV2Elements == 1)
9467 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9468 Mask, Subtarget, DAG))
9471 if (SDValue BitBlend =
9472 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9475 // Check whether a compaction lowering can be done. This handles shuffles
9476 // which take every Nth element for some even N. See the helper function for
9479 // We special case these as they can be particularly efficiently handled with
9480 // the PACKUSB instruction on x86 and they show up in common patterns of
9481 // rearranging bytes to truncate wide elements.
9482 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9483 // NumEvenDrops is the power of two stride of the elements. Another way of
9484 // thinking about it is that we need to drop the even elements this many
9485 // times to get the original input.
9486 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9488 // First we need to zero all the dropped bytes.
9489 assert(NumEvenDrops <= 3 &&
9490 "No support for dropping even elements more than 3 times.");
9491 // We use the mask type to pick which bytes are preserved based on how many
9492 // elements are dropped.
9493 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9494 SDValue ByteClearMask = DAG.getBitcast(
9495 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9496 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9498 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9500 // Now pack things back together.
9501 V1 = DAG.getBitcast(MVT::v8i16, V1);
9502 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9503 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9504 for (int i = 1; i < NumEvenDrops; ++i) {
9505 Result = DAG.getBitcast(MVT::v8i16, Result);
9506 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9512 // Handle multi-input cases by blending single-input shuffles.
9513 if (NumV2Elements > 0)
9514 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9517 // The fallback path for single-input shuffles widens this into two v8i16
9518 // vectors with unpacks, shuffles those, and then pulls them back together
9522 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9523 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9524 for (int i = 0; i < 16; ++i)
9526 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9528 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9530 SDValue VLoHalf, VHiHalf;
9531 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9532 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9534 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9535 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9536 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9537 [](int M) { return M >= 0 && M % 2 == 1; })) {
9538 // Use a mask to drop the high bytes.
9539 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9540 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9541 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9543 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9544 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9546 // Squash the masks to point directly into VLoHalf.
9547 for (int &M : LoBlendMask)
9550 for (int &M : HiBlendMask)
9554 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9555 // VHiHalf so that we can blend them as i16s.
9556 VLoHalf = DAG.getBitcast(
9557 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9558 VHiHalf = DAG.getBitcast(
9559 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9562 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9563 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9565 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9568 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9570 /// This routine breaks down the specific type of 128-bit shuffle and
9571 /// dispatches to the lowering routines accordingly.
9572 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9573 MVT VT, const X86Subtarget *Subtarget,
9574 SelectionDAG &DAG) {
9575 switch (VT.SimpleTy) {
9577 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9579 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9581 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9583 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9585 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9587 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9590 llvm_unreachable("Unimplemented!");
9594 /// \brief Helper function to test whether a shuffle mask could be
9595 /// simplified by widening the elements being shuffled.
9597 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9598 /// leaves it in an unspecified state.
9600 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9601 /// shuffle masks. The latter have the special property of a '-2' representing
9602 /// a zero-ed lane of a vector.
9603 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9604 SmallVectorImpl<int> &WidenedMask) {
9605 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9606 // If both elements are undef, its trivial.
9607 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9608 WidenedMask.push_back(SM_SentinelUndef);
9612 // Check for an undef mask and a mask value properly aligned to fit with
9613 // a pair of values. If we find such a case, use the non-undef mask's value.
9614 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9615 WidenedMask.push_back(Mask[i + 1] / 2);
9618 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9619 WidenedMask.push_back(Mask[i] / 2);
9623 // When zeroing, we need to spread the zeroing across both lanes to widen.
9624 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9625 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9626 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9627 WidenedMask.push_back(SM_SentinelZero);
9633 // Finally check if the two mask values are adjacent and aligned with
9635 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9636 WidenedMask.push_back(Mask[i] / 2);
9640 // Otherwise we can't safely widen the elements used in this shuffle.
9643 assert(WidenedMask.size() == Mask.size() / 2 &&
9644 "Incorrect size of mask after widening the elements!");
9649 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9651 /// This routine just extracts two subvectors, shuffles them independently, and
9652 /// then concatenates them back together. This should work effectively with all
9653 /// AVX vector shuffle types.
9654 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9655 SDValue V2, ArrayRef<int> Mask,
9656 SelectionDAG &DAG) {
9657 assert(VT.getSizeInBits() >= 256 &&
9658 "Only for 256-bit or wider vector shuffles!");
9659 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9660 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9662 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9663 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9665 int NumElements = VT.getVectorNumElements();
9666 int SplitNumElements = NumElements / 2;
9667 MVT ScalarVT = VT.getScalarType();
9668 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9670 // Rather than splitting build-vectors, just build two narrower build
9671 // vectors. This helps shuffling with splats and zeros.
9672 auto SplitVector = [&](SDValue V) {
9673 while (V.getOpcode() == ISD::BITCAST)
9674 V = V->getOperand(0);
9676 MVT OrigVT = V.getSimpleValueType();
9677 int OrigNumElements = OrigVT.getVectorNumElements();
9678 int OrigSplitNumElements = OrigNumElements / 2;
9679 MVT OrigScalarVT = OrigVT.getScalarType();
9680 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9684 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9686 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9687 DAG.getIntPtrConstant(0, DL));
9688 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9689 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9692 SmallVector<SDValue, 16> LoOps, HiOps;
9693 for (int i = 0; i < OrigSplitNumElements; ++i) {
9694 LoOps.push_back(BV->getOperand(i));
9695 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9697 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9698 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9700 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9701 DAG.getBitcast(SplitVT, HiV));
9704 SDValue LoV1, HiV1, LoV2, HiV2;
9705 std::tie(LoV1, HiV1) = SplitVector(V1);
9706 std::tie(LoV2, HiV2) = SplitVector(V2);
9708 // Now create two 4-way blends of these half-width vectors.
9709 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9710 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9711 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9712 for (int i = 0; i < SplitNumElements; ++i) {
9713 int M = HalfMask[i];
9714 if (M >= NumElements) {
9715 if (M >= NumElements + SplitNumElements)
9719 V2BlendMask.push_back(M - NumElements);
9720 V1BlendMask.push_back(-1);
9721 BlendMask.push_back(SplitNumElements + i);
9722 } else if (M >= 0) {
9723 if (M >= SplitNumElements)
9727 V2BlendMask.push_back(-1);
9728 V1BlendMask.push_back(M);
9729 BlendMask.push_back(i);
9731 V2BlendMask.push_back(-1);
9732 V1BlendMask.push_back(-1);
9733 BlendMask.push_back(-1);
9737 // Because the lowering happens after all combining takes place, we need to
9738 // manually combine these blend masks as much as possible so that we create
9739 // a minimal number of high-level vector shuffle nodes.
9741 // First try just blending the halves of V1 or V2.
9742 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9743 return DAG.getUNDEF(SplitVT);
9744 if (!UseLoV2 && !UseHiV2)
9745 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9746 if (!UseLoV1 && !UseHiV1)
9747 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9749 SDValue V1Blend, V2Blend;
9750 if (UseLoV1 && UseHiV1) {
9752 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9754 // We only use half of V1 so map the usage down into the final blend mask.
9755 V1Blend = UseLoV1 ? LoV1 : HiV1;
9756 for (int i = 0; i < SplitNumElements; ++i)
9757 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9758 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9760 if (UseLoV2 && UseHiV2) {
9762 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9764 // We only use half of V2 so map the usage down into the final blend mask.
9765 V2Blend = UseLoV2 ? LoV2 : HiV2;
9766 for (int i = 0; i < SplitNumElements; ++i)
9767 if (BlendMask[i] >= SplitNumElements)
9768 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9770 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9772 SDValue Lo = HalfBlend(LoMask);
9773 SDValue Hi = HalfBlend(HiMask);
9774 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9777 /// \brief Either split a vector in halves or decompose the shuffles and the
9780 /// This is provided as a good fallback for many lowerings of non-single-input
9781 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9782 /// between splitting the shuffle into 128-bit components and stitching those
9783 /// back together vs. extracting the single-input shuffles and blending those
9785 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9786 SDValue V2, ArrayRef<int> Mask,
9787 SelectionDAG &DAG) {
9788 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9789 "lower single-input shuffles as it "
9790 "could then recurse on itself.");
9791 int Size = Mask.size();
9793 // If this can be modeled as a broadcast of two elements followed by a blend,
9794 // prefer that lowering. This is especially important because broadcasts can
9795 // often fold with memory operands.
9796 auto DoBothBroadcast = [&] {
9797 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9800 if (V2BroadcastIdx == -1)
9801 V2BroadcastIdx = M - Size;
9802 else if (M - Size != V2BroadcastIdx)
9804 } else if (M >= 0) {
9805 if (V1BroadcastIdx == -1)
9807 else if (M != V1BroadcastIdx)
9812 if (DoBothBroadcast())
9813 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9816 // If the inputs all stem from a single 128-bit lane of each input, then we
9817 // split them rather than blending because the split will decompose to
9818 // unusually few instructions.
9819 int LaneCount = VT.getSizeInBits() / 128;
9820 int LaneSize = Size / LaneCount;
9821 SmallBitVector LaneInputs[2];
9822 LaneInputs[0].resize(LaneCount, false);
9823 LaneInputs[1].resize(LaneCount, false);
9824 for (int i = 0; i < Size; ++i)
9826 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9827 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9828 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9830 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9831 // that the decomposed single-input shuffles don't end up here.
9832 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9835 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9836 /// a permutation and blend of those lanes.
9838 /// This essentially blends the out-of-lane inputs to each lane into the lane
9839 /// from a permuted copy of the vector. This lowering strategy results in four
9840 /// instructions in the worst case for a single-input cross lane shuffle which
9841 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9842 /// of. Special cases for each particular shuffle pattern should be handled
9843 /// prior to trying this lowering.
9844 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9845 SDValue V1, SDValue V2,
9847 SelectionDAG &DAG) {
9848 // FIXME: This should probably be generalized for 512-bit vectors as well.
9849 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9850 int LaneSize = Mask.size() / 2;
9852 // If there are only inputs from one 128-bit lane, splitting will in fact be
9853 // less expensive. The flags track whether the given lane contains an element
9854 // that crosses to another lane.
9855 bool LaneCrossing[2] = {false, false};
9856 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9857 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9858 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9859 if (!LaneCrossing[0] || !LaneCrossing[1])
9860 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9862 if (isSingleInputShuffleMask(Mask)) {
9863 SmallVector<int, 32> FlippedBlendMask;
9864 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9865 FlippedBlendMask.push_back(
9866 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9868 : Mask[i] % LaneSize +
9869 (i / LaneSize) * LaneSize + Size));
9871 // Flip the vector, and blend the results which should now be in-lane. The
9872 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9873 // 5 for the high source. The value 3 selects the high half of source 2 and
9874 // the value 2 selects the low half of source 2. We only use source 2 to
9875 // allow folding it into a memory operand.
9876 unsigned PERMMask = 3 | 2 << 4;
9877 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9878 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9879 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9882 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9883 // will be handled by the above logic and a blend of the results, much like
9884 // other patterns in AVX.
9885 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9888 /// \brief Handle lowering 2-lane 128-bit shuffles.
9889 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9890 SDValue V2, ArrayRef<int> Mask,
9891 const X86Subtarget *Subtarget,
9892 SelectionDAG &DAG) {
9893 // TODO: If minimizing size and one of the inputs is a zero vector and the
9894 // the zero vector has only one use, we could use a VPERM2X128 to save the
9895 // instruction bytes needed to explicitly generate the zero vector.
9897 // Blends are faster and handle all the non-lane-crossing cases.
9898 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9902 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9903 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9905 // If either input operand is a zero vector, use VPERM2X128 because its mask
9906 // allows us to replace the zero input with an implicit zero.
9907 if (!IsV1Zero && !IsV2Zero) {
9908 // Check for patterns which can be matched with a single insert of a 128-bit
9910 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9911 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9912 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9913 VT.getVectorNumElements() / 2);
9914 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9915 DAG.getIntPtrConstant(0, DL));
9916 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9917 OnlyUsesV1 ? V1 : V2,
9918 DAG.getIntPtrConstant(0, DL));
9919 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9923 // Otherwise form a 128-bit permutation. After accounting for undefs,
9924 // convert the 64-bit shuffle mask selection values into 128-bit
9925 // selection bits by dividing the indexes by 2 and shifting into positions
9926 // defined by a vperm2*128 instruction's immediate control byte.
9928 // The immediate permute control byte looks like this:
9929 // [1:0] - select 128 bits from sources for low half of destination
9931 // [3] - zero low half of destination
9932 // [5:4] - select 128 bits from sources for high half of destination
9934 // [7] - zero high half of destination
9936 int MaskLO = Mask[0];
9937 if (MaskLO == SM_SentinelUndef)
9938 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9940 int MaskHI = Mask[2];
9941 if (MaskHI == SM_SentinelUndef)
9942 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9944 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9946 // If either input is a zero vector, replace it with an undef input.
9947 // Shuffle mask values < 4 are selecting elements of V1.
9948 // Shuffle mask values >= 4 are selecting elements of V2.
9949 // Adjust each half of the permute mask by clearing the half that was
9950 // selecting the zero vector and setting the zero mask bit.
9952 V1 = DAG.getUNDEF(VT);
9954 PermMask = (PermMask & 0xf0) | 0x08;
9956 PermMask = (PermMask & 0x0f) | 0x80;
9959 V2 = DAG.getUNDEF(VT);
9961 PermMask = (PermMask & 0xf0) | 0x08;
9963 PermMask = (PermMask & 0x0f) | 0x80;
9966 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9967 DAG.getConstant(PermMask, DL, MVT::i8));
9970 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9971 /// shuffling each lane.
9973 /// This will only succeed when the result of fixing the 128-bit lanes results
9974 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9975 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9976 /// the lane crosses early and then use simpler shuffles within each lane.
9978 /// FIXME: It might be worthwhile at some point to support this without
9979 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9980 /// in x86 only floating point has interesting non-repeating shuffles, and even
9981 /// those are still *marginally* more expensive.
9982 static SDValue lowerVectorShuffleByMerging128BitLanes(
9983 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9984 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9985 assert(!isSingleInputShuffleMask(Mask) &&
9986 "This is only useful with multiple inputs.");
9988 int Size = Mask.size();
9989 int LaneSize = 128 / VT.getScalarSizeInBits();
9990 int NumLanes = Size / LaneSize;
9991 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9993 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9994 // check whether the in-128-bit lane shuffles share a repeating pattern.
9995 SmallVector<int, 4> Lanes;
9996 Lanes.resize(NumLanes, -1);
9997 SmallVector<int, 4> InLaneMask;
9998 InLaneMask.resize(LaneSize, -1);
9999 for (int i = 0; i < Size; ++i) {
10003 int j = i / LaneSize;
10005 if (Lanes[j] < 0) {
10006 // First entry we've seen for this lane.
10007 Lanes[j] = Mask[i] / LaneSize;
10008 } else if (Lanes[j] != Mask[i] / LaneSize) {
10009 // This doesn't match the lane selected previously!
10013 // Check that within each lane we have a consistent shuffle mask.
10014 int k = i % LaneSize;
10015 if (InLaneMask[k] < 0) {
10016 InLaneMask[k] = Mask[i] % LaneSize;
10017 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10018 // This doesn't fit a repeating in-lane mask.
10023 // First shuffle the lanes into place.
10024 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10025 VT.getSizeInBits() / 64);
10026 SmallVector<int, 8> LaneMask;
10027 LaneMask.resize(NumLanes * 2, -1);
10028 for (int i = 0; i < NumLanes; ++i)
10029 if (Lanes[i] >= 0) {
10030 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10031 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10034 V1 = DAG.getBitcast(LaneVT, V1);
10035 V2 = DAG.getBitcast(LaneVT, V2);
10036 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10038 // Cast it back to the type we actually want.
10039 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10041 // Now do a simple shuffle that isn't lane crossing.
10042 SmallVector<int, 8> NewMask;
10043 NewMask.resize(Size, -1);
10044 for (int i = 0; i < Size; ++i)
10046 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10047 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10048 "Must not introduce lane crosses at this point!");
10050 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10053 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10056 /// This returns true if the elements from a particular input are already in the
10057 /// slot required by the given mask and require no permutation.
10058 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10059 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10060 int Size = Mask.size();
10061 for (int i = 0; i < Size; ++i)
10062 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10068 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10069 ArrayRef<int> Mask, SDValue V1,
10070 SDValue V2, SelectionDAG &DAG) {
10072 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
10073 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
10074 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10075 int NumElts = VT.getVectorNumElements();
10076 bool ShufpdMask = true;
10077 bool CommutableMask = true;
10078 unsigned Immediate = 0;
10079 for (int i = 0; i < NumElts; ++i) {
10082 int Val = (i & 6) + NumElts * (i & 1);
10083 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10084 if (Mask[i] < Val || Mask[i] > Val + 1)
10085 ShufpdMask = false;
10086 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
10087 CommutableMask = false;
10088 Immediate |= (Mask[i] % 2) << i;
10091 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10092 DAG.getConstant(Immediate, DL, MVT::i8));
10093 if (CommutableMask)
10094 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10095 DAG.getConstant(Immediate, DL, MVT::i8));
10099 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10101 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10102 /// isn't available.
10103 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10104 const X86Subtarget *Subtarget,
10105 SelectionDAG &DAG) {
10107 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10108 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10109 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10110 ArrayRef<int> Mask = SVOp->getMask();
10111 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10113 SmallVector<int, 4> WidenedMask;
10114 if (canWidenShuffleElements(Mask, WidenedMask))
10115 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10118 if (isSingleInputShuffleMask(Mask)) {
10119 // Check for being able to broadcast a single element.
10120 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10121 Mask, Subtarget, DAG))
10124 // Use low duplicate instructions for masks that match their pattern.
10125 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10126 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10128 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10129 // Non-half-crossing single input shuffles can be lowerid with an
10130 // interleaved permutation.
10131 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10132 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10133 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10134 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10137 // With AVX2 we have direct support for this permutation.
10138 if (Subtarget->hasAVX2())
10139 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10140 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10142 // Otherwise, fall back.
10143 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10147 // X86 has dedicated unpack instructions that can handle specific blend
10148 // operations: UNPCKH and UNPCKL.
10149 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10150 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10151 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10152 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10153 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10154 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
10155 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10156 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
10158 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10162 // Check if the blend happens to exactly fit that of SHUFPD.
10164 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10167 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10168 // shuffle. However, if we have AVX2 and either inputs are already in place,
10169 // we will be able to shuffle even across lanes the other input in a single
10170 // instruction so skip this pattern.
10171 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10172 isShuffleMaskInputInPlace(1, Mask))))
10173 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10174 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10177 // If we have AVX2 then we always want to lower with a blend because an v4 we
10178 // can fully permute the elements.
10179 if (Subtarget->hasAVX2())
10180 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10183 // Otherwise fall back on generic lowering.
10184 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10187 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10189 /// This routine is only called when we have AVX2 and thus a reasonable
10190 /// instruction set for v4i64 shuffling..
10191 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10192 const X86Subtarget *Subtarget,
10193 SelectionDAG &DAG) {
10195 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10196 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10197 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10198 ArrayRef<int> Mask = SVOp->getMask();
10199 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10200 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10202 SmallVector<int, 4> WidenedMask;
10203 if (canWidenShuffleElements(Mask, WidenedMask))
10204 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10207 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10211 // Check for being able to broadcast a single element.
10212 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10213 Mask, Subtarget, DAG))
10216 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10217 // use lower latency instructions that will operate on both 128-bit lanes.
10218 SmallVector<int, 2> RepeatedMask;
10219 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10220 if (isSingleInputShuffleMask(Mask)) {
10221 int PSHUFDMask[] = {-1, -1, -1, -1};
10222 for (int i = 0; i < 2; ++i)
10223 if (RepeatedMask[i] >= 0) {
10224 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10225 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10227 return DAG.getBitcast(
10229 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10230 DAG.getBitcast(MVT::v8i32, V1),
10231 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10235 // AVX2 provides a direct instruction for permuting a single input across
10237 if (isSingleInputShuffleMask(Mask))
10238 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10239 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10241 // Try to use shift instructions.
10242 if (SDValue Shift =
10243 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10246 // Use dedicated unpack instructions for masks that match their pattern.
10247 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10248 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10249 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10250 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10251 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10252 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
10253 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10254 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
10256 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10257 // shuffle. However, if we have AVX2 and either inputs are already in place,
10258 // we will be able to shuffle even across lanes the other input in a single
10259 // instruction so skip this pattern.
10260 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10261 isShuffleMaskInputInPlace(1, Mask))))
10262 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10263 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10266 // Otherwise fall back on generic blend lowering.
10267 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10271 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10273 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10274 /// isn't available.
10275 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10276 const X86Subtarget *Subtarget,
10277 SelectionDAG &DAG) {
10279 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10280 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10281 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10282 ArrayRef<int> Mask = SVOp->getMask();
10283 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10285 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10289 // Check for being able to broadcast a single element.
10290 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10291 Mask, Subtarget, DAG))
10294 // If the shuffle mask is repeated in each 128-bit lane, we have many more
10295 // options to efficiently lower the shuffle.
10296 SmallVector<int, 4> RepeatedMask;
10297 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10298 assert(RepeatedMask.size() == 4 &&
10299 "Repeated masks must be half the mask width!");
10301 // Use even/odd duplicate instructions for masks that match their pattern.
10302 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10303 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10304 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10305 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10307 if (isSingleInputShuffleMask(Mask))
10308 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10309 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10311 // Use dedicated unpack instructions for masks that match their pattern.
10312 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10313 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10314 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10315 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10316 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10317 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10318 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10319 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10321 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10322 // have already handled any direct blends. We also need to squash the
10323 // repeated mask into a simulated v4f32 mask.
10324 for (int i = 0; i < 4; ++i)
10325 if (RepeatedMask[i] >= 8)
10326 RepeatedMask[i] -= 4;
10327 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10330 // If we have a single input shuffle with different shuffle patterns in the
10331 // two 128-bit lanes use the variable mask to VPERMILPS.
10332 if (isSingleInputShuffleMask(Mask)) {
10333 SDValue VPermMask[8];
10334 for (int i = 0; i < 8; ++i)
10335 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10336 : DAG.getConstant(Mask[i], DL, MVT::i32);
10337 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10338 return DAG.getNode(
10339 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10340 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10342 if (Subtarget->hasAVX2())
10343 return DAG.getNode(
10344 X86ISD::VPERMV, DL, MVT::v8f32,
10345 DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10346 MVT::v8i32, VPermMask)),
10349 // Otherwise, fall back.
10350 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10354 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10356 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10357 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10360 // If we have AVX2 then we always want to lower with a blend because at v8 we
10361 // can fully permute the elements.
10362 if (Subtarget->hasAVX2())
10363 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10366 // Otherwise fall back on generic lowering.
10367 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10370 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10372 /// This routine is only called when we have AVX2 and thus a reasonable
10373 /// instruction set for v8i32 shuffling..
10374 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10375 const X86Subtarget *Subtarget,
10376 SelectionDAG &DAG) {
10378 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10379 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10380 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10381 ArrayRef<int> Mask = SVOp->getMask();
10382 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10383 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10385 // Whenever we can lower this as a zext, that instruction is strictly faster
10386 // than any alternative. It also allows us to fold memory operands into the
10387 // shuffle in many cases.
10388 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10389 Mask, Subtarget, DAG))
10392 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10396 // Check for being able to broadcast a single element.
10397 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10398 Mask, Subtarget, DAG))
10401 // If the shuffle mask is repeated in each 128-bit lane we can use more
10402 // efficient instructions that mirror the shuffles across the two 128-bit
10404 SmallVector<int, 4> RepeatedMask;
10405 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10406 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10407 if (isSingleInputShuffleMask(Mask))
10408 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10409 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10411 // Use dedicated unpack instructions for masks that match their pattern.
10412 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10413 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10414 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10415 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10416 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10417 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10418 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10419 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10422 // Try to use shift instructions.
10423 if (SDValue Shift =
10424 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10427 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10428 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10431 // If the shuffle patterns aren't repeated but it is a single input, directly
10432 // generate a cross-lane VPERMD instruction.
10433 if (isSingleInputShuffleMask(Mask)) {
10434 SDValue VPermMask[8];
10435 for (int i = 0; i < 8; ++i)
10436 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10437 : DAG.getConstant(Mask[i], DL, MVT::i32);
10438 return DAG.getNode(
10439 X86ISD::VPERMV, DL, MVT::v8i32,
10440 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10443 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10445 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10446 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10449 // Otherwise fall back on generic blend lowering.
10450 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10454 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10456 /// This routine is only called when we have AVX2 and thus a reasonable
10457 /// instruction set for v16i16 shuffling..
10458 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10459 const X86Subtarget *Subtarget,
10460 SelectionDAG &DAG) {
10462 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10463 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10464 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10465 ArrayRef<int> Mask = SVOp->getMask();
10466 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10467 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10469 // Whenever we can lower this as a zext, that instruction is strictly faster
10470 // than any alternative. It also allows us to fold memory operands into the
10471 // shuffle in many cases.
10472 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10473 Mask, Subtarget, DAG))
10476 // Check for being able to broadcast a single element.
10477 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10478 Mask, Subtarget, DAG))
10481 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10485 // Use dedicated unpack instructions for masks that match their pattern.
10486 if (isShuffleEquivalent(V1, V2, Mask,
10487 {// First 128-bit lane:
10488 0, 16, 1, 17, 2, 18, 3, 19,
10489 // Second 128-bit lane:
10490 8, 24, 9, 25, 10, 26, 11, 27}))
10491 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10492 if (isShuffleEquivalent(V1, V2, Mask,
10493 {// First 128-bit lane:
10494 4, 20, 5, 21, 6, 22, 7, 23,
10495 // Second 128-bit lane:
10496 12, 28, 13, 29, 14, 30, 15, 31}))
10497 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10499 // Try to use shift instructions.
10500 if (SDValue Shift =
10501 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10504 // Try to use byte rotation instructions.
10505 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10506 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10509 if (isSingleInputShuffleMask(Mask)) {
10510 // There are no generalized cross-lane shuffle operations available on i16
10512 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10513 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10516 SmallVector<int, 8> RepeatedMask;
10517 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10518 // As this is a single-input shuffle, the repeated mask should be
10519 // a strictly valid v8i16 mask that we can pass through to the v8i16
10520 // lowering to handle even the v16 case.
10521 return lowerV8I16GeneralSingleInputVectorShuffle(
10522 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10525 SDValue PSHUFBMask[32];
10526 for (int i = 0; i < 16; ++i) {
10527 if (Mask[i] == -1) {
10528 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10532 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10533 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10534 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10535 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10537 return DAG.getBitcast(MVT::v16i16,
10538 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10539 DAG.getBitcast(MVT::v32i8, V1),
10540 DAG.getNode(ISD::BUILD_VECTOR, DL,
10541 MVT::v32i8, PSHUFBMask)));
10544 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10546 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10547 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10550 // Otherwise fall back on generic lowering.
10551 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10554 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10556 /// This routine is only called when we have AVX2 and thus a reasonable
10557 /// instruction set for v32i8 shuffling..
10558 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10559 const X86Subtarget *Subtarget,
10560 SelectionDAG &DAG) {
10562 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10563 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10564 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10565 ArrayRef<int> Mask = SVOp->getMask();
10566 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10567 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10569 // Whenever we can lower this as a zext, that instruction is strictly faster
10570 // than any alternative. It also allows us to fold memory operands into the
10571 // shuffle in many cases.
10572 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10573 Mask, Subtarget, DAG))
10576 // Check for being able to broadcast a single element.
10577 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10578 Mask, Subtarget, DAG))
10581 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10585 // Use dedicated unpack instructions for masks that match their pattern.
10586 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10588 if (isShuffleEquivalent(
10590 {// First 128-bit lane:
10591 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10592 // Second 128-bit lane:
10593 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10594 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10595 if (isShuffleEquivalent(
10597 {// First 128-bit lane:
10598 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10599 // Second 128-bit lane:
10600 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10601 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10603 // Try to use shift instructions.
10604 if (SDValue Shift =
10605 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10608 // Try to use byte rotation instructions.
10609 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10610 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10613 if (isSingleInputShuffleMask(Mask)) {
10614 // There are no generalized cross-lane shuffle operations available on i8
10616 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10617 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10620 SDValue PSHUFBMask[32];
10621 for (int i = 0; i < 32; ++i)
10624 ? DAG.getUNDEF(MVT::i8)
10625 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10628 return DAG.getNode(
10629 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10630 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10633 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10635 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10636 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10639 // Otherwise fall back on generic lowering.
10640 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10643 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10645 /// This routine either breaks down the specific type of a 256-bit x86 vector
10646 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10647 /// together based on the available instructions.
10648 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10649 MVT VT, const X86Subtarget *Subtarget,
10650 SelectionDAG &DAG) {
10652 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10653 ArrayRef<int> Mask = SVOp->getMask();
10655 // If we have a single input to the zero element, insert that into V1 if we
10656 // can do so cheaply.
10657 int NumElts = VT.getVectorNumElements();
10658 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10659 return M >= NumElts;
10662 if (NumV2Elements == 1 && Mask[0] >= NumElts)
10663 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10664 DL, VT, V1, V2, Mask, Subtarget, DAG))
10667 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10668 // check for those subtargets here and avoid much of the subtarget querying in
10669 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10670 // ability to manipulate a 256-bit vector with integer types. Since we'll use
10671 // floating point types there eventually, just immediately cast everything to
10672 // a float and operate entirely in that domain.
10673 if (VT.isInteger() && !Subtarget->hasAVX2()) {
10674 int ElementBits = VT.getScalarSizeInBits();
10675 if (ElementBits < 32)
10676 // No floating point type available, decompose into 128-bit vectors.
10677 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10679 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10680 VT.getVectorNumElements());
10681 V1 = DAG.getBitcast(FpVT, V1);
10682 V2 = DAG.getBitcast(FpVT, V2);
10683 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10686 switch (VT.SimpleTy) {
10688 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10690 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10692 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10694 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10696 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10698 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10701 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10705 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10706 ArrayRef<int> Mask, SDValue V1,
10707 SDValue V2, SelectionDAG &DAG) {
10709 assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10711 MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10712 MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10714 SmallVector<SDValue, 32> VPermMask;
10715 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i)
10716 VPermMask.push_back(Mask[i] < 0 ? DAG.getUNDEF(MaskEltVT) :
10717 DAG.getConstant(Mask[i], DL, MaskEltVT));
10718 SDValue MaskNode = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVecVT,
10720 if (isSingleInputShuffleMask(Mask))
10721 return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10723 return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10726 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10727 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10728 const X86Subtarget *Subtarget,
10729 SelectionDAG &DAG) {
10731 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10732 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10733 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10734 ArrayRef<int> Mask = SVOp->getMask();
10735 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10737 if (SDValue Unpck =
10738 lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10741 return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10744 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10745 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10746 const X86Subtarget *Subtarget,
10747 SelectionDAG &DAG) {
10749 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10750 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10751 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10752 ArrayRef<int> Mask = SVOp->getMask();
10753 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10755 if (SDValue Unpck =
10756 lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10759 return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10762 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10763 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10764 const X86Subtarget *Subtarget,
10765 SelectionDAG &DAG) {
10767 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10768 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10769 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10770 ArrayRef<int> Mask = SVOp->getMask();
10771 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10773 if (SDValue Unpck =
10774 lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10777 return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10780 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10781 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10782 const X86Subtarget *Subtarget,
10783 SelectionDAG &DAG) {
10785 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10786 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10787 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10788 ArrayRef<int> Mask = SVOp->getMask();
10789 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10791 if (SDValue Unpck =
10792 lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
10795 return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10798 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10799 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10800 const X86Subtarget *Subtarget,
10801 SelectionDAG &DAG) {
10803 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10804 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10805 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10806 ArrayRef<int> Mask = SVOp->getMask();
10807 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10808 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10810 return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10813 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10814 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10815 const X86Subtarget *Subtarget,
10816 SelectionDAG &DAG) {
10818 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10819 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10820 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10821 ArrayRef<int> Mask = SVOp->getMask();
10822 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10823 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10825 // FIXME: Implement direct support for this type!
10826 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10829 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10831 /// This routine either breaks down the specific type of a 512-bit x86 vector
10832 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10833 /// together based on the available instructions.
10834 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10835 MVT VT, const X86Subtarget *Subtarget,
10836 SelectionDAG &DAG) {
10838 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10839 ArrayRef<int> Mask = SVOp->getMask();
10840 assert(Subtarget->hasAVX512() &&
10841 "Cannot lower 512-bit vectors w/ basic ISA!");
10843 // Check for being able to broadcast a single element.
10844 if (SDValue Broadcast =
10845 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10848 // Dispatch to each element type for lowering. If we don't have supprot for
10849 // specific element type shuffles at 512 bits, immediately split them and
10850 // lower them. Each lowering routine of a given type is allowed to assume that
10851 // the requisite ISA extensions for that element type are available.
10852 switch (VT.SimpleTy) {
10854 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10856 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10858 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10860 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10862 if (Subtarget->hasBWI())
10863 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10866 if (Subtarget->hasBWI())
10867 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10871 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10874 // Otherwise fall back on splitting.
10875 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10878 // Lower vXi1 vector shuffles.
10879 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
10880 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
10881 // vector, shuffle and then truncate it back.
10882 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10883 MVT VT, const X86Subtarget *Subtarget,
10884 SelectionDAG &DAG) {
10886 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10887 ArrayRef<int> Mask = SVOp->getMask();
10888 assert(Subtarget->hasAVX512() &&
10889 "Cannot lower 512-bit vectors w/o basic ISA!");
10891 switch (VT.SimpleTy) {
10893 assert(false && "Expected a vector of i1 elements");
10896 ExtVT = MVT::v2i64;
10899 ExtVT = MVT::v4i32;
10902 ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
10905 ExtVT = MVT::v16i32;
10908 ExtVT = MVT::v32i16;
10911 ExtVT = MVT::v64i8;
10915 if (ISD::isBuildVectorAllZeros(V1.getNode()))
10916 V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10917 else if (ISD::isBuildVectorAllOnes(V1.getNode()))
10918 V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10920 V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
10923 V2 = DAG.getUNDEF(ExtVT);
10924 else if (ISD::isBuildVectorAllZeros(V2.getNode()))
10925 V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10926 else if (ISD::isBuildVectorAllOnes(V2.getNode()))
10927 V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10929 V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
10930 return DAG.getNode(ISD::TRUNCATE, DL, VT,
10931 DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
10933 /// \brief Top-level lowering for x86 vector shuffles.
10935 /// This handles decomposition, canonicalization, and lowering of all x86
10936 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10937 /// above in helper routines. The canonicalization attempts to widen shuffles
10938 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10939 /// s.t. only one of the two inputs needs to be tested, etc.
10940 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10941 SelectionDAG &DAG) {
10942 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10943 ArrayRef<int> Mask = SVOp->getMask();
10944 SDValue V1 = Op.getOperand(0);
10945 SDValue V2 = Op.getOperand(1);
10946 MVT VT = Op.getSimpleValueType();
10947 int NumElements = VT.getVectorNumElements();
10949 bool Is1BitVector = (VT.getScalarType() == MVT::i1);
10951 assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
10952 "Can't lower MMX shuffles");
10954 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10955 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10956 if (V1IsUndef && V2IsUndef)
10957 return DAG.getUNDEF(VT);
10959 // When we create a shuffle node we put the UNDEF node to second operand,
10960 // but in some cases the first operand may be transformed to UNDEF.
10961 // In this case we should just commute the node.
10963 return DAG.getCommutedVectorShuffle(*SVOp);
10965 // Check for non-undef masks pointing at an undef vector and make the masks
10966 // undef as well. This makes it easier to match the shuffle based solely on
10970 if (M >= NumElements) {
10971 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10972 for (int &M : NewMask)
10973 if (M >= NumElements)
10975 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10978 // We actually see shuffles that are entirely re-arrangements of a set of
10979 // zero inputs. This mostly happens while decomposing complex shuffles into
10980 // simple ones. Directly lower these as a buildvector of zeros.
10981 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10982 if (Zeroable.all())
10983 return getZeroVector(VT, Subtarget, DAG, dl);
10985 // Try to collapse shuffles into using a vector type with fewer elements but
10986 // wider element types. We cap this to not form integers or floating point
10987 // elements wider than 64 bits, but it might be interesting to form i128
10988 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10989 SmallVector<int, 16> WidenedMask;
10990 if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
10991 canWidenShuffleElements(Mask, WidenedMask)) {
10992 MVT NewEltVT = VT.isFloatingPoint()
10993 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10994 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10995 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10996 // Make sure that the new vector type is legal. For example, v2f64 isn't
10998 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10999 V1 = DAG.getBitcast(NewVT, V1);
11000 V2 = DAG.getBitcast(NewVT, V2);
11001 return DAG.getBitcast(
11002 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11006 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11007 for (int M : SVOp->getMask())
11009 ++NumUndefElements;
11010 else if (M < NumElements)
11015 // Commute the shuffle as needed such that more elements come from V1 than
11016 // V2. This allows us to match the shuffle pattern strictly on how many
11017 // elements come from V1 without handling the symmetric cases.
11018 if (NumV2Elements > NumV1Elements)
11019 return DAG.getCommutedVectorShuffle(*SVOp);
11021 // When the number of V1 and V2 elements are the same, try to minimize the
11022 // number of uses of V2 in the low half of the vector. When that is tied,
11023 // ensure that the sum of indices for V1 is equal to or lower than the sum
11024 // indices for V2. When those are equal, try to ensure that the number of odd
11025 // indices for V1 is lower than the number of odd indices for V2.
11026 if (NumV1Elements == NumV2Elements) {
11027 int LowV1Elements = 0, LowV2Elements = 0;
11028 for (int M : SVOp->getMask().slice(0, NumElements / 2))
11029 if (M >= NumElements)
11033 if (LowV2Elements > LowV1Elements) {
11034 return DAG.getCommutedVectorShuffle(*SVOp);
11035 } else if (LowV2Elements == LowV1Elements) {
11036 int SumV1Indices = 0, SumV2Indices = 0;
11037 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11038 if (SVOp->getMask()[i] >= NumElements)
11040 else if (SVOp->getMask()[i] >= 0)
11042 if (SumV2Indices < SumV1Indices) {
11043 return DAG.getCommutedVectorShuffle(*SVOp);
11044 } else if (SumV2Indices == SumV1Indices) {
11045 int NumV1OddIndices = 0, NumV2OddIndices = 0;
11046 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11047 if (SVOp->getMask()[i] >= NumElements)
11048 NumV2OddIndices += i % 2;
11049 else if (SVOp->getMask()[i] >= 0)
11050 NumV1OddIndices += i % 2;
11051 if (NumV2OddIndices < NumV1OddIndices)
11052 return DAG.getCommutedVectorShuffle(*SVOp);
11057 // For each vector width, delegate to a specialized lowering routine.
11058 if (VT.getSizeInBits() == 128)
11059 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11061 if (VT.getSizeInBits() == 256)
11062 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11064 if (VT.getSizeInBits() == 512)
11065 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11068 return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11069 llvm_unreachable("Unimplemented!");
11072 // This function assumes its argument is a BUILD_VECTOR of constants or
11073 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11075 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11076 unsigned &MaskValue) {
11078 unsigned NumElems = BuildVector->getNumOperands();
11079 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11080 unsigned NumLanes = (NumElems - 1) / 8 + 1;
11081 unsigned NumElemsInLane = NumElems / NumLanes;
11083 // Blend for v16i16 should be symmetric for the both lanes.
11084 for (unsigned i = 0; i < NumElemsInLane; ++i) {
11085 SDValue EltCond = BuildVector->getOperand(i);
11086 SDValue SndLaneEltCond =
11087 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11089 int Lane1Cond = -1, Lane2Cond = -1;
11090 if (isa<ConstantSDNode>(EltCond))
11091 Lane1Cond = !isZero(EltCond);
11092 if (isa<ConstantSDNode>(SndLaneEltCond))
11093 Lane2Cond = !isZero(SndLaneEltCond);
11095 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11096 // Lane1Cond != 0, means we want the first argument.
11097 // Lane1Cond == 0, means we want the second argument.
11098 // The encoding of this argument is 0 for the first argument, 1
11099 // for the second. Therefore, invert the condition.
11100 MaskValue |= !Lane1Cond << i;
11101 else if (Lane1Cond < 0)
11102 MaskValue |= !Lane2Cond << i;
11109 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11110 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11111 const X86Subtarget *Subtarget,
11112 SelectionDAG &DAG) {
11113 SDValue Cond = Op.getOperand(0);
11114 SDValue LHS = Op.getOperand(1);
11115 SDValue RHS = Op.getOperand(2);
11117 MVT VT = Op.getSimpleValueType();
11119 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11121 auto *CondBV = cast<BuildVectorSDNode>(Cond);
11123 // Only non-legal VSELECTs reach this lowering, convert those into generic
11124 // shuffles and re-use the shuffle lowering path for blends.
11125 SmallVector<int, 32> Mask;
11126 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11127 SDValue CondElt = CondBV->getOperand(i);
11129 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
11131 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11134 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11135 // A vselect where all conditions and data are constants can be optimized into
11136 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11137 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11138 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11139 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11142 // Try to lower this to a blend-style vector shuffle. This can handle all
11143 // constant condition cases.
11144 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11147 // Variable blends are only legal from SSE4.1 onward.
11148 if (!Subtarget->hasSSE41())
11151 // Only some types will be legal on some subtargets. If we can emit a legal
11152 // VSELECT-matching blend, return Op, and but if we need to expand, return
11154 switch (Op.getSimpleValueType().SimpleTy) {
11156 // Most of the vector types have blends past SSE4.1.
11160 // The byte blends for AVX vectors were introduced only in AVX2.
11161 if (Subtarget->hasAVX2())
11168 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11169 if (Subtarget->hasBWI() && Subtarget->hasVLX())
11172 // FIXME: We should custom lower this by fixing the condition and using i8
11178 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11179 MVT VT = Op.getSimpleValueType();
11182 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11185 if (VT.getSizeInBits() == 8) {
11186 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11187 Op.getOperand(0), Op.getOperand(1));
11188 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11189 DAG.getValueType(VT));
11190 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11193 if (VT.getSizeInBits() == 16) {
11194 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11195 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11197 return DAG.getNode(
11198 ISD::TRUNCATE, dl, MVT::i16,
11199 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11200 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11201 Op.getOperand(1)));
11202 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11203 Op.getOperand(0), Op.getOperand(1));
11204 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11205 DAG.getValueType(VT));
11206 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11209 if (VT == MVT::f32) {
11210 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11211 // the result back to FR32 register. It's only worth matching if the
11212 // result has a single use which is a store or a bitcast to i32. And in
11213 // the case of a store, it's not worth it if the index is a constant 0,
11214 // because a MOVSSmr can be used instead, which is smaller and faster.
11215 if (!Op.hasOneUse())
11217 SDNode *User = *Op.getNode()->use_begin();
11218 if ((User->getOpcode() != ISD::STORE ||
11219 (isa<ConstantSDNode>(Op.getOperand(1)) &&
11220 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11221 (User->getOpcode() != ISD::BITCAST ||
11222 User->getValueType(0) != MVT::i32))
11224 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11225 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11227 return DAG.getBitcast(MVT::f32, Extract);
11230 if (VT == MVT::i32 || VT == MVT::i64) {
11231 // ExtractPS/pextrq works with constant index.
11232 if (isa<ConstantSDNode>(Op.getOperand(1)))
11238 /// Extract one bit from mask vector, like v16i1 or v8i1.
11239 /// AVX-512 feature.
11241 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11242 SDValue Vec = Op.getOperand(0);
11244 MVT VecVT = Vec.getSimpleValueType();
11245 SDValue Idx = Op.getOperand(1);
11246 MVT EltVT = Op.getSimpleValueType();
11248 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11249 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11250 "Unexpected vector type in ExtractBitFromMaskVector");
11252 // variable index can't be handled in mask registers,
11253 // extend vector to VR512
11254 if (!isa<ConstantSDNode>(Idx)) {
11255 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11256 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11257 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11258 ExtVT.getVectorElementType(), Ext, Idx);
11259 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11262 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11263 const TargetRegisterClass* rc = getRegClassFor(VecVT);
11264 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11265 rc = getRegClassFor(MVT::v16i1);
11266 unsigned MaxSift = rc->getSize()*8 - 1;
11267 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11268 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11269 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11270 DAG.getConstant(MaxSift, dl, MVT::i8));
11271 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11272 DAG.getIntPtrConstant(0, dl));
11276 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11277 SelectionDAG &DAG) const {
11279 SDValue Vec = Op.getOperand(0);
11280 MVT VecVT = Vec.getSimpleValueType();
11281 SDValue Idx = Op.getOperand(1);
11283 if (Op.getSimpleValueType() == MVT::i1)
11284 return ExtractBitFromMaskVector(Op, DAG);
11286 if (!isa<ConstantSDNode>(Idx)) {
11287 if (VecVT.is512BitVector() ||
11288 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11289 VecVT.getVectorElementType().getSizeInBits() == 32)) {
11292 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11293 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11294 MaskEltVT.getSizeInBits());
11296 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11297 auto PtrVT = getPointerTy(DAG.getDataLayout());
11298 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11299 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11300 DAG.getConstant(0, dl, PtrVT));
11301 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11302 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11303 DAG.getConstant(0, dl, PtrVT));
11308 // If this is a 256-bit vector result, first extract the 128-bit vector and
11309 // then extract the element from the 128-bit vector.
11310 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11312 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11313 // Get the 128-bit vector.
11314 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11315 MVT EltVT = VecVT.getVectorElementType();
11317 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11319 //if (IdxVal >= NumElems/2)
11320 // IdxVal -= NumElems/2;
11321 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11322 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11323 DAG.getConstant(IdxVal, dl, MVT::i32));
11326 assert(VecVT.is128BitVector() && "Unexpected vector length");
11328 if (Subtarget->hasSSE41())
11329 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11332 MVT VT = Op.getSimpleValueType();
11333 // TODO: handle v16i8.
11334 if (VT.getSizeInBits() == 16) {
11335 SDValue Vec = Op.getOperand(0);
11336 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11338 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11339 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11340 DAG.getBitcast(MVT::v4i32, Vec),
11341 Op.getOperand(1)));
11342 // Transform it so it match pextrw which produces a 32-bit result.
11343 MVT EltVT = MVT::i32;
11344 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11345 Op.getOperand(0), Op.getOperand(1));
11346 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11347 DAG.getValueType(VT));
11348 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11351 if (VT.getSizeInBits() == 32) {
11352 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11356 // SHUFPS the element to the lowest double word, then movss.
11357 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11358 MVT VVT = Op.getOperand(0).getSimpleValueType();
11359 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11360 DAG.getUNDEF(VVT), Mask);
11361 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11362 DAG.getIntPtrConstant(0, dl));
11365 if (VT.getSizeInBits() == 64) {
11366 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11367 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11368 // to match extract_elt for f64.
11369 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11373 // UNPCKHPD the element to the lowest double word, then movsd.
11374 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11375 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11376 int Mask[2] = { 1, -1 };
11377 MVT VVT = Op.getOperand(0).getSimpleValueType();
11378 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11379 DAG.getUNDEF(VVT), Mask);
11380 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11381 DAG.getIntPtrConstant(0, dl));
11387 /// Insert one bit to mask vector, like v16i1 or v8i1.
11388 /// AVX-512 feature.
11390 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11392 SDValue Vec = Op.getOperand(0);
11393 SDValue Elt = Op.getOperand(1);
11394 SDValue Idx = Op.getOperand(2);
11395 MVT VecVT = Vec.getSimpleValueType();
11397 if (!isa<ConstantSDNode>(Idx)) {
11398 // Non constant index. Extend source and destination,
11399 // insert element and then truncate the result.
11400 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11401 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
11402 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11403 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11404 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11405 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11408 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11409 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11411 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11412 DAG.getConstant(IdxVal, dl, MVT::i8));
11413 if (Vec.getOpcode() == ISD::UNDEF)
11415 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11418 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11419 SelectionDAG &DAG) const {
11420 MVT VT = Op.getSimpleValueType();
11421 MVT EltVT = VT.getVectorElementType();
11423 if (EltVT == MVT::i1)
11424 return InsertBitToMaskVector(Op, DAG);
11427 SDValue N0 = Op.getOperand(0);
11428 SDValue N1 = Op.getOperand(1);
11429 SDValue N2 = Op.getOperand(2);
11430 if (!isa<ConstantSDNode>(N2))
11432 auto *N2C = cast<ConstantSDNode>(N2);
11433 unsigned IdxVal = N2C->getZExtValue();
11435 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11436 // into that, and then insert the subvector back into the result.
11437 if (VT.is256BitVector() || VT.is512BitVector()) {
11438 // With a 256-bit vector, we can insert into the zero element efficiently
11439 // using a blend if we have AVX or AVX2 and the right data type.
11440 if (VT.is256BitVector() && IdxVal == 0) {
11441 // TODO: It is worthwhile to cast integer to floating point and back
11442 // and incur a domain crossing penalty if that's what we'll end up
11443 // doing anyway after extracting to a 128-bit vector.
11444 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11445 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11446 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11447 N2 = DAG.getIntPtrConstant(1, dl);
11448 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11452 // Get the desired 128-bit vector chunk.
11453 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11455 // Insert the element into the desired chunk.
11456 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11457 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11459 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11460 DAG.getConstant(IdxIn128, dl, MVT::i32));
11462 // Insert the changed part back into the bigger vector
11463 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11465 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11467 if (Subtarget->hasSSE41()) {
11468 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11470 if (VT == MVT::v8i16) {
11471 Opc = X86ISD::PINSRW;
11473 assert(VT == MVT::v16i8);
11474 Opc = X86ISD::PINSRB;
11477 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11479 if (N1.getValueType() != MVT::i32)
11480 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11481 if (N2.getValueType() != MVT::i32)
11482 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11483 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11486 if (EltVT == MVT::f32) {
11487 // Bits [7:6] of the constant are the source select. This will always be
11488 // zero here. The DAG Combiner may combine an extract_elt index into
11489 // these bits. For example (insert (extract, 3), 2) could be matched by
11490 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11491 // Bits [5:4] of the constant are the destination select. This is the
11492 // value of the incoming immediate.
11493 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11494 // combine either bitwise AND or insert of float 0.0 to set these bits.
11496 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11497 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11498 // If this is an insertion of 32-bits into the low 32-bits of
11499 // a vector, we prefer to generate a blend with immediate rather
11500 // than an insertps. Blends are simpler operations in hardware and so
11501 // will always have equal or better performance than insertps.
11502 // But if optimizing for size and there's a load folding opportunity,
11503 // generate insertps because blendps does not have a 32-bit memory
11505 N2 = DAG.getIntPtrConstant(1, dl);
11506 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11507 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11509 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11510 // Create this as a scalar to vector..
11511 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11512 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11515 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11516 // PINSR* works with constant index.
11521 if (EltVT == MVT::i8)
11524 if (EltVT.getSizeInBits() == 16) {
11525 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11526 // as its second argument.
11527 if (N1.getValueType() != MVT::i32)
11528 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11529 if (N2.getValueType() != MVT::i32)
11530 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11531 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11536 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11538 MVT OpVT = Op.getSimpleValueType();
11540 // If this is a 256-bit vector result, first insert into a 128-bit
11541 // vector and then insert into the 256-bit vector.
11542 if (!OpVT.is128BitVector()) {
11543 // Insert into a 128-bit vector.
11544 unsigned SizeFactor = OpVT.getSizeInBits()/128;
11545 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11546 OpVT.getVectorNumElements() / SizeFactor);
11548 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11550 // Insert the 128-bit vector.
11551 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11554 if (OpVT == MVT::v1i64 &&
11555 Op.getOperand(0).getValueType() == MVT::i64)
11556 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11558 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11559 assert(OpVT.is128BitVector() && "Expected an SSE type!");
11560 return DAG.getBitcast(
11561 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11564 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
11565 // a simple subregister reference or explicit instructions to grab
11566 // upper bits of a vector.
11567 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11568 SelectionDAG &DAG) {
11570 SDValue In = Op.getOperand(0);
11571 SDValue Idx = Op.getOperand(1);
11572 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11573 MVT ResVT = Op.getSimpleValueType();
11574 MVT InVT = In.getSimpleValueType();
11576 if (Subtarget->hasFp256()) {
11577 if (ResVT.is128BitVector() &&
11578 (InVT.is256BitVector() || InVT.is512BitVector()) &&
11579 isa<ConstantSDNode>(Idx)) {
11580 return Extract128BitVector(In, IdxVal, DAG, dl);
11582 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11583 isa<ConstantSDNode>(Idx)) {
11584 return Extract256BitVector(In, IdxVal, DAG, dl);
11590 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
11591 // simple superregister reference or explicit instructions to insert
11592 // the upper bits of a vector.
11593 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11594 SelectionDAG &DAG) {
11595 if (!Subtarget->hasAVX())
11599 SDValue Vec = Op.getOperand(0);
11600 SDValue SubVec = Op.getOperand(1);
11601 SDValue Idx = Op.getOperand(2);
11603 if (!isa<ConstantSDNode>(Idx))
11606 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11607 MVT OpVT = Op.getSimpleValueType();
11608 MVT SubVecVT = SubVec.getSimpleValueType();
11610 // Fold two 16-byte subvector loads into one 32-byte load:
11611 // (insert_subvector (insert_subvector undef, (load addr), 0),
11612 // (load addr + 16), Elts/2)
11614 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11615 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11616 OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11617 auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11618 if (Idx2 && Idx2->getZExtValue() == 0) {
11619 SDValue SubVec2 = Vec.getOperand(1);
11620 // If needed, look through a bitcast to get to the load.
11621 if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11622 SubVec2 = SubVec2.getOperand(0);
11624 if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11626 unsigned Alignment = FirstLd->getAlignment();
11627 unsigned AS = FirstLd->getAddressSpace();
11628 const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11629 if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11630 OpVT, AS, Alignment, &Fast) && Fast) {
11631 SDValue Ops[] = { SubVec2, SubVec };
11632 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11639 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11640 SubVecVT.is128BitVector())
11641 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11643 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11644 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11646 if (OpVT.getVectorElementType() == MVT::i1) {
11647 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11649 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11650 SDValue Undef = DAG.getUNDEF(OpVT);
11651 unsigned NumElems = OpVT.getVectorNumElements();
11652 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11654 if (IdxVal == OpVT.getVectorNumElements() / 2) {
11655 // Zero upper bits of the Vec
11656 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11657 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11659 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11661 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11662 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11665 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11667 // Zero upper bits of the Vec2
11668 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11669 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11670 // Zero lower bits of the Vec
11671 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11672 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11673 // Merge them together
11674 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11680 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11681 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11682 // one of the above mentioned nodes. It has to be wrapped because otherwise
11683 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11684 // be used to form addressing mode. These wrapped nodes will be selected
11687 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11688 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11690 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11691 // global base reg.
11692 unsigned char OpFlag = 0;
11693 unsigned WrapperKind = X86ISD::Wrapper;
11694 CodeModel::Model M = DAG.getTarget().getCodeModel();
11696 if (Subtarget->isPICStyleRIPRel() &&
11697 (M == CodeModel::Small || M == CodeModel::Kernel))
11698 WrapperKind = X86ISD::WrapperRIP;
11699 else if (Subtarget->isPICStyleGOT())
11700 OpFlag = X86II::MO_GOTOFF;
11701 else if (Subtarget->isPICStyleStubPIC())
11702 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11704 auto PtrVT = getPointerTy(DAG.getDataLayout());
11705 SDValue Result = DAG.getTargetConstantPool(
11706 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11708 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11709 // With PIC, the address is actually $g + Offset.
11712 DAG.getNode(ISD::ADD, DL, PtrVT,
11713 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11719 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11720 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11722 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11723 // global base reg.
11724 unsigned char OpFlag = 0;
11725 unsigned WrapperKind = X86ISD::Wrapper;
11726 CodeModel::Model M = DAG.getTarget().getCodeModel();
11728 if (Subtarget->isPICStyleRIPRel() &&
11729 (M == CodeModel::Small || M == CodeModel::Kernel))
11730 WrapperKind = X86ISD::WrapperRIP;
11731 else if (Subtarget->isPICStyleGOT())
11732 OpFlag = X86II::MO_GOTOFF;
11733 else if (Subtarget->isPICStyleStubPIC())
11734 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11736 auto PtrVT = getPointerTy(DAG.getDataLayout());
11737 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11739 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11741 // With PIC, the address is actually $g + Offset.
11744 DAG.getNode(ISD::ADD, DL, PtrVT,
11745 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11751 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11752 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11754 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11755 // global base reg.
11756 unsigned char OpFlag = 0;
11757 unsigned WrapperKind = X86ISD::Wrapper;
11758 CodeModel::Model M = DAG.getTarget().getCodeModel();
11760 if (Subtarget->isPICStyleRIPRel() &&
11761 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11762 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11763 OpFlag = X86II::MO_GOTPCREL;
11764 WrapperKind = X86ISD::WrapperRIP;
11765 } else if (Subtarget->isPICStyleGOT()) {
11766 OpFlag = X86II::MO_GOT;
11767 } else if (Subtarget->isPICStyleStubPIC()) {
11768 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11769 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11770 OpFlag = X86II::MO_DARWIN_NONLAZY;
11773 auto PtrVT = getPointerTy(DAG.getDataLayout());
11774 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11777 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11779 // With PIC, the address is actually $g + Offset.
11780 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11781 !Subtarget->is64Bit()) {
11783 DAG.getNode(ISD::ADD, DL, PtrVT,
11784 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11787 // For symbols that require a load from a stub to get the address, emit the
11789 if (isGlobalStubReference(OpFlag))
11790 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11791 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11792 false, false, false, 0);
11798 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11799 // Create the TargetBlockAddressAddress node.
11800 unsigned char OpFlags =
11801 Subtarget->ClassifyBlockAddressReference();
11802 CodeModel::Model M = DAG.getTarget().getCodeModel();
11803 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11804 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11806 auto PtrVT = getPointerTy(DAG.getDataLayout());
11807 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11809 if (Subtarget->isPICStyleRIPRel() &&
11810 (M == CodeModel::Small || M == CodeModel::Kernel))
11811 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11813 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11815 // With PIC, the address is actually $g + Offset.
11816 if (isGlobalRelativeToPICBase(OpFlags)) {
11817 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11818 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11825 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11826 int64_t Offset, SelectionDAG &DAG) const {
11827 // Create the TargetGlobalAddress node, folding in the constant
11828 // offset if it is legal.
11829 unsigned char OpFlags =
11830 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11831 CodeModel::Model M = DAG.getTarget().getCodeModel();
11832 auto PtrVT = getPointerTy(DAG.getDataLayout());
11834 if (OpFlags == X86II::MO_NO_FLAG &&
11835 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11836 // A direct static reference to a global.
11837 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11840 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11843 if (Subtarget->isPICStyleRIPRel() &&
11844 (M == CodeModel::Small || M == CodeModel::Kernel))
11845 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11847 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11849 // With PIC, the address is actually $g + Offset.
11850 if (isGlobalRelativeToPICBase(OpFlags)) {
11851 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11852 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11855 // For globals that require a load from a stub to get the address, emit the
11857 if (isGlobalStubReference(OpFlags))
11858 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11859 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11860 false, false, false, 0);
11862 // If there was a non-zero offset that we didn't fold, create an explicit
11863 // addition for it.
11865 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11866 DAG.getConstant(Offset, dl, PtrVT));
11872 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11873 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11874 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11875 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11879 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11880 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11881 unsigned char OperandFlags, bool LocalDynamic = false) {
11882 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11883 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11885 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11886 GA->getValueType(0),
11890 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11894 SDValue Ops[] = { Chain, TGA, *InFlag };
11895 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11897 SDValue Ops[] = { Chain, TGA };
11898 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11901 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11902 MFI->setAdjustsStack(true);
11903 MFI->setHasCalls(true);
11905 SDValue Flag = Chain.getValue(1);
11906 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11909 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11911 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11914 SDLoc dl(GA); // ? function entry point might be better
11915 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11916 DAG.getNode(X86ISD::GlobalBaseReg,
11917 SDLoc(), PtrVT), InFlag);
11918 InFlag = Chain.getValue(1);
11920 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11923 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11925 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11927 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11928 X86::RAX, X86II::MO_TLSGD);
11931 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11937 // Get the start address of the TLS block for this module.
11938 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11939 .getInfo<X86MachineFunctionInfo>();
11940 MFI->incNumLocalDynamicTLSAccesses();
11944 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11945 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11948 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11949 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11950 InFlag = Chain.getValue(1);
11951 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11952 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11955 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11959 unsigned char OperandFlags = X86II::MO_DTPOFF;
11960 unsigned WrapperKind = X86ISD::Wrapper;
11961 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11962 GA->getValueType(0),
11963 GA->getOffset(), OperandFlags);
11964 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11966 // Add x@dtpoff with the base.
11967 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11970 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11971 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11972 const EVT PtrVT, TLSModel::Model model,
11973 bool is64Bit, bool isPIC) {
11976 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11977 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11978 is64Bit ? 257 : 256));
11980 SDValue ThreadPointer =
11981 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11982 MachinePointerInfo(Ptr), false, false, false, 0);
11984 unsigned char OperandFlags = 0;
11985 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11987 unsigned WrapperKind = X86ISD::Wrapper;
11988 if (model == TLSModel::LocalExec) {
11989 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11990 } else if (model == TLSModel::InitialExec) {
11992 OperandFlags = X86II::MO_GOTTPOFF;
11993 WrapperKind = X86ISD::WrapperRIP;
11995 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11998 llvm_unreachable("Unexpected model");
12001 // emit "addl x@ntpoff,%eax" (local exec)
12002 // or "addl x@indntpoff,%eax" (initial exec)
12003 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12005 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12006 GA->getOffset(), OperandFlags);
12007 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12009 if (model == TLSModel::InitialExec) {
12010 if (isPIC && !is64Bit) {
12011 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12012 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12016 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12017 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12018 false, false, false, 0);
12021 // The address of the thread local variable is the add of the thread
12022 // pointer with the offset of the variable.
12023 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12027 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12029 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12030 const GlobalValue *GV = GA->getGlobal();
12031 auto PtrVT = getPointerTy(DAG.getDataLayout());
12033 if (Subtarget->isTargetELF()) {
12034 if (DAG.getTarget().Options.EmulatedTLS)
12035 return LowerToTLSEmulatedModel(GA, DAG);
12036 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12038 case TLSModel::GeneralDynamic:
12039 if (Subtarget->is64Bit())
12040 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12041 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12042 case TLSModel::LocalDynamic:
12043 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12044 Subtarget->is64Bit());
12045 case TLSModel::InitialExec:
12046 case TLSModel::LocalExec:
12047 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12048 DAG.getTarget().getRelocationModel() ==
12051 llvm_unreachable("Unknown TLS model.");
12054 if (Subtarget->isTargetDarwin()) {
12055 // Darwin only has one model of TLS. Lower to that.
12056 unsigned char OpFlag = 0;
12057 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12058 X86ISD::WrapperRIP : X86ISD::Wrapper;
12060 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12061 // global base reg.
12062 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12063 !Subtarget->is64Bit();
12065 OpFlag = X86II::MO_TLVP_PIC_BASE;
12067 OpFlag = X86II::MO_TLVP;
12069 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12070 GA->getValueType(0),
12071 GA->getOffset(), OpFlag);
12072 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12074 // With PIC32, the address is actually $g + Offset.
12076 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12077 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12080 // Lowering the machine isd will make sure everything is in the right
12082 SDValue Chain = DAG.getEntryNode();
12083 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12084 SDValue Args[] = { Chain, Offset };
12085 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12087 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12088 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12089 MFI->setAdjustsStack(true);
12091 // And our return value (tls address) is in the standard call return value
12093 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12094 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12097 if (Subtarget->isTargetKnownWindowsMSVC() ||
12098 Subtarget->isTargetWindowsGNU()) {
12099 // Just use the implicit TLS architecture
12100 // Need to generate someting similar to:
12101 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12103 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
12104 // mov rcx, qword [rdx+rcx*8]
12105 // mov eax, .tls$:tlsvar
12106 // [rax+rcx] contains the address
12107 // Windows 64bit: gs:0x58
12108 // Windows 32bit: fs:__tls_array
12111 SDValue Chain = DAG.getEntryNode();
12113 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12114 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12115 // use its literal value of 0x2C.
12116 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12117 ? Type::getInt8PtrTy(*DAG.getContext(),
12119 : Type::getInt32PtrTy(*DAG.getContext(),
12122 SDValue TlsArray = Subtarget->is64Bit()
12123 ? DAG.getIntPtrConstant(0x58, dl)
12124 : (Subtarget->isTargetWindowsGNU()
12125 ? DAG.getIntPtrConstant(0x2C, dl)
12126 : DAG.getExternalSymbol("_tls_array", PtrVT));
12128 SDValue ThreadPointer =
12129 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12133 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12134 res = ThreadPointer;
12136 // Load the _tls_index variable
12137 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12138 if (Subtarget->is64Bit())
12139 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12140 MachinePointerInfo(), MVT::i32, false, false,
12143 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12146 auto &DL = DAG.getDataLayout();
12148 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12149 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12151 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12154 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12157 // Get the offset of start of .tls section
12158 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12159 GA->getValueType(0),
12160 GA->getOffset(), X86II::MO_SECREL);
12161 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12163 // The address of the thread local variable is the add of the thread
12164 // pointer with the offset of the variable.
12165 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12168 llvm_unreachable("TLS not implemented for this target.");
12171 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12172 /// and take a 2 x i32 value to shift plus a shift amount.
12173 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12174 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12175 MVT VT = Op.getSimpleValueType();
12176 unsigned VTBits = VT.getSizeInBits();
12178 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12179 SDValue ShOpLo = Op.getOperand(0);
12180 SDValue ShOpHi = Op.getOperand(1);
12181 SDValue ShAmt = Op.getOperand(2);
12182 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12183 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12185 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12186 DAG.getConstant(VTBits - 1, dl, MVT::i8));
12187 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12188 DAG.getConstant(VTBits - 1, dl, MVT::i8))
12189 : DAG.getConstant(0, dl, VT);
12191 SDValue Tmp2, Tmp3;
12192 if (Op.getOpcode() == ISD::SHL_PARTS) {
12193 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12194 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12196 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12197 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12200 // If the shift amount is larger or equal than the width of a part we can't
12201 // rely on the results of shld/shrd. Insert a test and select the appropriate
12202 // values for large shift amounts.
12203 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12204 DAG.getConstant(VTBits, dl, MVT::i8));
12205 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12206 AndNode, DAG.getConstant(0, dl, MVT::i8));
12209 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12210 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12211 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12213 if (Op.getOpcode() == ISD::SHL_PARTS) {
12214 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12215 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12217 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12218 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12221 SDValue Ops[2] = { Lo, Hi };
12222 return DAG.getMergeValues(Ops, dl);
12225 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12226 SelectionDAG &DAG) const {
12227 SDValue Src = Op.getOperand(0);
12228 MVT SrcVT = Src.getSimpleValueType();
12229 MVT VT = Op.getSimpleValueType();
12232 if (SrcVT.isVector()) {
12233 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12234 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12235 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12236 DAG.getUNDEF(SrcVT)));
12238 if (SrcVT.getVectorElementType() == MVT::i1) {
12239 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12240 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12241 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12246 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12247 "Unknown SINT_TO_FP to lower!");
12249 // These are really Legal; return the operand so the caller accepts it as
12251 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12253 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12254 Subtarget->is64Bit()) {
12258 unsigned Size = SrcVT.getSizeInBits()/8;
12259 MachineFunction &MF = DAG.getMachineFunction();
12260 auto PtrVT = getPointerTy(MF.getDataLayout());
12261 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12262 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12263 SDValue Chain = DAG.getStore(
12264 DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12265 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12267 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12270 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12272 SelectionDAG &DAG) const {
12276 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12278 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12280 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12282 unsigned ByteSize = SrcVT.getSizeInBits()/8;
12284 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12285 MachineMemOperand *MMO;
12287 int SSFI = FI->getIndex();
12288 MMO = DAG.getMachineFunction().getMachineMemOperand(
12289 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12290 MachineMemOperand::MOLoad, ByteSize, ByteSize);
12292 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12293 StackSlot = StackSlot.getOperand(1);
12295 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12296 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12298 Tys, Ops, SrcVT, MMO);
12301 Chain = Result.getValue(1);
12302 SDValue InFlag = Result.getValue(2);
12304 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12305 // shouldn't be necessary except that RFP cannot be live across
12306 // multiple blocks. When stackifier is fixed, they can be uncoupled.
12307 MachineFunction &MF = DAG.getMachineFunction();
12308 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12309 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12310 auto PtrVT = getPointerTy(MF.getDataLayout());
12311 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12312 Tys = DAG.getVTList(MVT::Other);
12314 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12316 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12317 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12318 MachineMemOperand::MOStore, SSFISize, SSFISize);
12320 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12321 Ops, Op.getValueType(), MMO);
12322 Result = DAG.getLoad(
12323 Op.getValueType(), DL, Chain, StackSlot,
12324 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12325 false, false, false, 0);
12331 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12332 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12333 SelectionDAG &DAG) const {
12334 // This algorithm is not obvious. Here it is what we're trying to output:
12337 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12338 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12340 haddpd %xmm0, %xmm0
12342 pshufd $0x4e, %xmm0, %xmm1
12348 LLVMContext *Context = DAG.getContext();
12350 // Build some magic constants.
12351 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12352 Constant *C0 = ConstantDataVector::get(*Context, CV0);
12353 auto PtrVT = getPointerTy(DAG.getDataLayout());
12354 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12356 SmallVector<Constant*,2> CV1;
12358 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12359 APInt(64, 0x4330000000000000ULL))));
12361 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12362 APInt(64, 0x4530000000000000ULL))));
12363 Constant *C1 = ConstantVector::get(CV1);
12364 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12366 // Load the 64-bit value into an XMM register.
12367 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12370 DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12371 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12372 false, false, false, 16);
12374 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12377 DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12378 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12379 false, false, false, 16);
12380 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12381 // TODO: Are there any fast-math-flags to propagate here?
12382 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12385 if (Subtarget->hasSSE3()) {
12386 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12387 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12389 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12390 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12392 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12393 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12396 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12397 DAG.getIntPtrConstant(0, dl));
12400 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12401 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12402 SelectionDAG &DAG) const {
12404 // FP constant to bias correct the final result.
12405 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12408 // Load the 32-bit value into an XMM register.
12409 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12412 // Zero out the upper parts of the register.
12413 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12415 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12416 DAG.getBitcast(MVT::v2f64, Load),
12417 DAG.getIntPtrConstant(0, dl));
12419 // Or the load with the bias.
12420 SDValue Or = DAG.getNode(
12421 ISD::OR, dl, MVT::v2i64,
12422 DAG.getBitcast(MVT::v2i64,
12423 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12424 DAG.getBitcast(MVT::v2i64,
12425 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12427 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12428 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12430 // Subtract the bias.
12431 // TODO: Are there any fast-math-flags to propagate here?
12432 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12434 // Handle final rounding.
12435 EVT DestVT = Op.getValueType();
12437 if (DestVT.bitsLT(MVT::f64))
12438 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12439 DAG.getIntPtrConstant(0, dl));
12440 if (DestVT.bitsGT(MVT::f64))
12441 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12443 // Handle final rounding.
12447 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12448 const X86Subtarget &Subtarget) {
12449 // The algorithm is the following:
12450 // #ifdef __SSE4_1__
12451 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12452 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12453 // (uint4) 0x53000000, 0xaa);
12455 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12456 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12458 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12459 // return (float4) lo + fhi;
12462 SDValue V = Op->getOperand(0);
12463 EVT VecIntVT = V.getValueType();
12464 bool Is128 = VecIntVT == MVT::v4i32;
12465 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12466 // If we convert to something else than the supported type, e.g., to v4f64,
12468 if (VecFloatVT != Op->getValueType(0))
12471 unsigned NumElts = VecIntVT.getVectorNumElements();
12472 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12473 "Unsupported custom type");
12474 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12476 // In the #idef/#else code, we have in common:
12477 // - The vector of constants:
12483 // Create the splat vector for 0x4b000000.
12484 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12485 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12486 CstLow, CstLow, CstLow, CstLow};
12487 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12488 makeArrayRef(&CstLowArray[0], NumElts));
12489 // Create the splat vector for 0x53000000.
12490 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12491 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12492 CstHigh, CstHigh, CstHigh, CstHigh};
12493 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12494 makeArrayRef(&CstHighArray[0], NumElts));
12496 // Create the right shift.
12497 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12498 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12499 CstShift, CstShift, CstShift, CstShift};
12500 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12501 makeArrayRef(&CstShiftArray[0], NumElts));
12502 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12505 if (Subtarget.hasSSE41()) {
12506 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12507 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12508 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12509 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12510 // Low will be bitcasted right away, so do not bother bitcasting back to its
12512 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12513 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12514 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12515 // (uint4) 0x53000000, 0xaa);
12516 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12517 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12518 // High will be bitcasted right away, so do not bother bitcasting back to
12519 // its original type.
12520 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12521 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12523 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12524 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12525 CstMask, CstMask, CstMask);
12526 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12527 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12528 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12530 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12531 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12534 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12535 SDValue CstFAdd = DAG.getConstantFP(
12536 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12537 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12538 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12539 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12540 makeArrayRef(&CstFAddArray[0], NumElts));
12542 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12543 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12544 // TODO: Are there any fast-math-flags to propagate here?
12546 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12547 // return (float4) lo + fhi;
12548 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12549 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12552 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12553 SelectionDAG &DAG) const {
12554 SDValue N0 = Op.getOperand(0);
12555 MVT SVT = N0.getSimpleValueType();
12558 switch (SVT.SimpleTy) {
12560 llvm_unreachable("Custom UINT_TO_FP is not supported!");
12565 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12566 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12567 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12571 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12574 if (Subtarget->hasAVX512())
12575 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12576 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12578 llvm_unreachable(nullptr);
12581 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12582 SelectionDAG &DAG) const {
12583 SDValue N0 = Op.getOperand(0);
12585 auto PtrVT = getPointerTy(DAG.getDataLayout());
12587 if (Op.getValueType().isVector())
12588 return lowerUINT_TO_FP_vec(Op, DAG);
12590 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12591 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12592 // the optimization here.
12593 if (DAG.SignBitIsZero(N0))
12594 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12596 MVT SrcVT = N0.getSimpleValueType();
12597 MVT DstVT = Op.getSimpleValueType();
12599 if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
12600 (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
12601 // Conversions from unsigned i32 to f32/f64 are legal,
12602 // using VCVTUSI2SS/SD. Same for i64 in 64-bit mode.
12606 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12607 return LowerUINT_TO_FP_i64(Op, DAG);
12608 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12609 return LowerUINT_TO_FP_i32(Op, DAG);
12610 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12613 // Make a 64-bit buffer, and use it to build an FILD.
12614 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12615 if (SrcVT == MVT::i32) {
12616 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12617 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12618 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12619 StackSlot, MachinePointerInfo(),
12621 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12622 OffsetSlot, MachinePointerInfo(),
12624 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12628 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12629 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12630 StackSlot, MachinePointerInfo(),
12632 // For i64 source, we need to add the appropriate power of 2 if the input
12633 // was negative. This is the same as the optimization in
12634 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12635 // we must be careful to do the computation in x87 extended precision, not
12636 // in SSE. (The generic code can't know it's OK to do this, or how to.)
12637 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12638 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12639 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12640 MachineMemOperand::MOLoad, 8, 8);
12642 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12643 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12644 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12647 APInt FF(32, 0x5F800000ULL);
12649 // Check whether the sign bit is set.
12650 SDValue SignSet = DAG.getSetCC(
12651 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12652 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12654 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12655 SDValue FudgePtr = DAG.getConstantPool(
12656 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12658 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12659 SDValue Zero = DAG.getIntPtrConstant(0, dl);
12660 SDValue Four = DAG.getIntPtrConstant(4, dl);
12661 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12663 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12665 // Load the value out, extending it from f32 to f80.
12666 // FIXME: Avoid the extend by constructing the right constant pool?
12667 SDValue Fudge = DAG.getExtLoad(
12668 ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12669 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12670 false, false, false, 4);
12671 // Extend everything to 80 bits to force it to be done on x87.
12672 // TODO: Are there any fast-math-flags to propagate here?
12673 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12674 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12675 DAG.getIntPtrConstant(0, dl));
12678 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12679 // is legal, or has an f16 source (which needs to be promoted to f32),
12680 // just return an <SDValue(), SDValue()> pair.
12681 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12682 // to i16, i32 or i64, and we lower it to a legal sequence.
12683 // If lowered to the final integer result we return a <result, SDValue()> pair.
12684 // Otherwise we lower it to a sequence ending with a FIST, return a
12685 // <FIST, StackSlot> pair, and the caller is responsible for loading
12686 // the final integer result from StackSlot.
12687 std::pair<SDValue,SDValue>
12688 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12689 bool IsSigned, bool IsReplace) const {
12692 EVT DstTy = Op.getValueType();
12693 EVT TheVT = Op.getOperand(0).getValueType();
12694 auto PtrVT = getPointerTy(DAG.getDataLayout());
12696 if (TheVT == MVT::f16)
12697 // We need to promote the f16 to f32 before using the lowering
12698 // in this routine.
12699 return std::make_pair(SDValue(), SDValue());
12701 assert((TheVT == MVT::f32 ||
12702 TheVT == MVT::f64 ||
12703 TheVT == MVT::f80) &&
12704 "Unexpected FP operand type in FP_TO_INTHelper");
12706 // If using FIST to compute an unsigned i64, we'll need some fixup
12707 // to handle values above the maximum signed i64. A FIST is always
12708 // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12709 bool UnsignedFixup = !IsSigned &&
12710 DstTy == MVT::i64 &&
12711 (!Subtarget->is64Bit() ||
12712 !isScalarFPTypeInSSEReg(TheVT));
12714 if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12715 // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12716 // The low 32 bits of the fist result will have the correct uint32 result.
12717 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12721 assert(DstTy.getSimpleVT() <= MVT::i64 &&
12722 DstTy.getSimpleVT() >= MVT::i16 &&
12723 "Unknown FP_TO_INT to lower!");
12725 // These are really Legal.
12726 if (DstTy == MVT::i32 &&
12727 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12728 return std::make_pair(SDValue(), SDValue());
12729 if (Subtarget->is64Bit() &&
12730 DstTy == MVT::i64 &&
12731 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12732 return std::make_pair(SDValue(), SDValue());
12734 // We lower FP->int64 into FISTP64 followed by a load from a temporary
12736 MachineFunction &MF = DAG.getMachineFunction();
12737 unsigned MemSize = DstTy.getSizeInBits()/8;
12738 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12739 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12742 switch (DstTy.getSimpleVT().SimpleTy) {
12743 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12744 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12745 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12746 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12749 SDValue Chain = DAG.getEntryNode();
12750 SDValue Value = Op.getOperand(0);
12751 SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12753 if (UnsignedFixup) {
12755 // Conversion to unsigned i64 is implemented with a select,
12756 // depending on whether the source value fits in the range
12757 // of a signed i64. Let Thresh be the FP equivalent of
12758 // 0x8000000000000000ULL.
12760 // Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12761 // FistSrc = (Value < Thresh) ? Value : (Value - Thresh);
12762 // Fist-to-mem64 FistSrc
12763 // Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12764 // to XOR'ing the high 32 bits with Adjust.
12766 // Being a power of 2, Thresh is exactly representable in all FP formats.
12767 // For X87 we'd like to use the smallest FP type for this constant, but
12768 // for DAG type consistency we have to match the FP operand type.
12770 APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12771 APFloat::opStatus Status = APFloat::opOK;
12772 bool LosesInfo = false;
12773 if (TheVT == MVT::f64)
12774 // The rounding mode is irrelevant as the conversion should be exact.
12775 Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12777 else if (TheVT == MVT::f80)
12778 Status = Thresh.convert(APFloat::x87DoubleExtended,
12779 APFloat::rmNearestTiesToEven, &LosesInfo);
12781 assert(Status == APFloat::opOK && !LosesInfo &&
12782 "FP conversion should have been exact");
12784 SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12786 SDValue Cmp = DAG.getSetCC(DL,
12787 getSetCCResultType(DAG.getDataLayout(),
12788 *DAG.getContext(), TheVT),
12789 Value, ThreshVal, ISD::SETLT);
12790 Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12791 DAG.getConstant(0, DL, MVT::i32),
12792 DAG.getConstant(0x80000000, DL, MVT::i32));
12793 SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12794 Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12795 *DAG.getContext(), TheVT),
12796 Value, ThreshVal, ISD::SETLT);
12797 Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12800 // FIXME This causes a redundant load/store if the SSE-class value is already
12801 // in memory, such as if it is on the callstack.
12802 if (isScalarFPTypeInSSEReg(TheVT)) {
12803 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12804 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12805 MachinePointerInfo::getFixedStack(MF, SSFI), false,
12807 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12809 Chain, StackSlot, DAG.getValueType(TheVT)
12812 MachineMemOperand *MMO =
12813 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12814 MachineMemOperand::MOLoad, MemSize, MemSize);
12815 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12816 Chain = Value.getValue(1);
12817 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12818 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12821 MachineMemOperand *MMO =
12822 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12823 MachineMemOperand::MOStore, MemSize, MemSize);
12825 if (UnsignedFixup) {
12827 // Insert the FIST, load its result as two i32's,
12828 // and XOR the high i32 with Adjust.
12830 SDValue FistOps[] = { Chain, Value, StackSlot };
12831 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12832 FistOps, DstTy, MMO);
12834 SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12835 MachinePointerInfo(),
12836 false, false, false, 0);
12837 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12838 DAG.getConstant(4, DL, PtrVT));
12840 SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12841 MachinePointerInfo(),
12842 false, false, false, 0);
12843 High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12845 if (Subtarget->is64Bit()) {
12846 // Join High32 and Low32 into a 64-bit result.
12847 // (High32 << 32) | Low32
12848 Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12849 High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12850 High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12851 DAG.getConstant(32, DL, MVT::i8));
12852 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12853 return std::make_pair(Result, SDValue());
12856 SDValue ResultOps[] = { Low32, High32 };
12858 SDValue pair = IsReplace
12859 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12860 : DAG.getMergeValues(ResultOps, DL);
12861 return std::make_pair(pair, SDValue());
12863 // Build the FP_TO_INT*_IN_MEM
12864 SDValue Ops[] = { Chain, Value, StackSlot };
12865 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12867 return std::make_pair(FIST, StackSlot);
12871 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12872 const X86Subtarget *Subtarget) {
12873 MVT VT = Op->getSimpleValueType(0);
12874 SDValue In = Op->getOperand(0);
12875 MVT InVT = In.getSimpleValueType();
12878 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12879 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12881 // Optimize vectors in AVX mode:
12884 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12885 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12886 // Concat upper and lower parts.
12889 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12890 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12891 // Concat upper and lower parts.
12894 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12895 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12896 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12899 if (Subtarget->hasInt256())
12900 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12902 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12903 SDValue Undef = DAG.getUNDEF(InVT);
12904 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12905 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12906 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12908 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12909 VT.getVectorNumElements()/2);
12911 OpLo = DAG.getBitcast(HVT, OpLo);
12912 OpHi = DAG.getBitcast(HVT, OpHi);
12914 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12917 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12918 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12919 MVT VT = Op->getSimpleValueType(0);
12920 SDValue In = Op->getOperand(0);
12921 MVT InVT = In.getSimpleValueType();
12923 unsigned int NumElts = VT.getVectorNumElements();
12924 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12927 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12928 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12930 assert(InVT.getVectorElementType() == MVT::i1);
12931 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12933 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12935 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12937 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12938 if (VT.is512BitVector())
12940 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12943 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12944 SelectionDAG &DAG) {
12945 if (Subtarget->hasFp256())
12946 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12952 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12953 SelectionDAG &DAG) {
12955 MVT VT = Op.getSimpleValueType();
12956 SDValue In = Op.getOperand(0);
12957 MVT SVT = In.getSimpleValueType();
12959 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12960 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12962 if (Subtarget->hasFp256())
12963 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12966 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12967 VT.getVectorNumElements() != SVT.getVectorNumElements());
12971 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12973 MVT VT = Op.getSimpleValueType();
12974 SDValue In = Op.getOperand(0);
12975 MVT InVT = In.getSimpleValueType();
12977 if (VT == MVT::i1) {
12978 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12979 "Invalid scalar TRUNCATE operation");
12980 if (InVT.getSizeInBits() >= 32)
12982 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12983 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12985 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12986 "Invalid TRUNCATE operation");
12988 // move vector to mask - truncate solution for SKX
12989 if (VT.getVectorElementType() == MVT::i1) {
12990 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12991 Subtarget->hasBWI())
12992 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12993 if ((InVT.is256BitVector() || InVT.is128BitVector())
12994 && InVT.getScalarSizeInBits() <= 16 &&
12995 Subtarget->hasBWI() && Subtarget->hasVLX())
12996 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12997 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12998 Subtarget->hasDQI())
12999 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
13000 if ((InVT.is256BitVector() || InVT.is128BitVector())
13001 && InVT.getScalarSizeInBits() >= 32 &&
13002 Subtarget->hasDQI() && Subtarget->hasVLX())
13003 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
13006 if (VT.getVectorElementType() == MVT::i1) {
13007 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13008 unsigned NumElts = InVT.getVectorNumElements();
13009 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
13010 if (InVT.getSizeInBits() < 512) {
13011 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
13012 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13017 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
13018 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13019 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13022 // vpmovqb/w/d, vpmovdb/w, vpmovwb
13023 if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
13024 (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
13025 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13027 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13028 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13029 if (Subtarget->hasInt256()) {
13030 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13031 In = DAG.getBitcast(MVT::v8i32, In);
13032 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13034 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13035 DAG.getIntPtrConstant(0, DL));
13038 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13039 DAG.getIntPtrConstant(0, DL));
13040 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13041 DAG.getIntPtrConstant(2, DL));
13042 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13043 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13044 static const int ShufMask[] = {0, 2, 4, 6};
13045 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13048 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13049 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13050 if (Subtarget->hasInt256()) {
13051 In = DAG.getBitcast(MVT::v32i8, In);
13053 SmallVector<SDValue,32> pshufbMask;
13054 for (unsigned i = 0; i < 2; ++i) {
13055 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13056 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13057 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13058 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13059 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13060 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13061 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13062 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13063 for (unsigned j = 0; j < 8; ++j)
13064 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13066 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13067 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13068 In = DAG.getBitcast(MVT::v4i64, In);
13070 static const int ShufMask[] = {0, 2, -1, -1};
13071 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
13073 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13074 DAG.getIntPtrConstant(0, DL));
13075 return DAG.getBitcast(VT, In);
13078 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13079 DAG.getIntPtrConstant(0, DL));
13081 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13082 DAG.getIntPtrConstant(4, DL));
13084 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13085 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13087 // The PSHUFB mask:
13088 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13089 -1, -1, -1, -1, -1, -1, -1, -1};
13091 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13092 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13093 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13095 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13096 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13098 // The MOVLHPS Mask:
13099 static const int ShufMask2[] = {0, 1, 4, 5};
13100 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13101 return DAG.getBitcast(MVT::v8i16, res);
13104 // Handle truncation of V256 to V128 using shuffles.
13105 if (!VT.is128BitVector() || !InVT.is256BitVector())
13108 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13110 unsigned NumElems = VT.getVectorNumElements();
13111 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13113 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13114 // Prepare truncation shuffle mask
13115 for (unsigned i = 0; i != NumElems; ++i)
13116 MaskVec[i] = i * 2;
13117 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13118 DAG.getUNDEF(NVT), &MaskVec[0]);
13119 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13120 DAG.getIntPtrConstant(0, DL));
13123 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13124 SelectionDAG &DAG) const {
13125 assert(!Op.getSimpleValueType().isVector());
13127 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13128 /*IsSigned=*/ true, /*IsReplace=*/ false);
13129 SDValue FIST = Vals.first, StackSlot = Vals.second;
13130 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13131 if (!FIST.getNode())
13134 if (StackSlot.getNode())
13135 // Load the result.
13136 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13137 FIST, StackSlot, MachinePointerInfo(),
13138 false, false, false, 0);
13140 // The node is the result.
13144 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13145 SelectionDAG &DAG) const {
13146 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13147 /*IsSigned=*/ false, /*IsReplace=*/ false);
13148 SDValue FIST = Vals.first, StackSlot = Vals.second;
13149 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13150 if (!FIST.getNode())
13153 if (StackSlot.getNode())
13154 // Load the result.
13155 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13156 FIST, StackSlot, MachinePointerInfo(),
13157 false, false, false, 0);
13159 // The node is the result.
13163 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13165 MVT VT = Op.getSimpleValueType();
13166 SDValue In = Op.getOperand(0);
13167 MVT SVT = In.getSimpleValueType();
13169 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13171 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13172 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13173 In, DAG.getUNDEF(SVT)));
13176 /// The only differences between FABS and FNEG are the mask and the logic op.
13177 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13178 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13179 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13180 "Wrong opcode for lowering FABS or FNEG.");
13182 bool IsFABS = (Op.getOpcode() == ISD::FABS);
13184 // If this is a FABS and it has an FNEG user, bail out to fold the combination
13185 // into an FNABS. We'll lower the FABS after that if it is still in use.
13187 for (SDNode *User : Op->uses())
13188 if (User->getOpcode() == ISD::FNEG)
13192 MVT VT = Op.getSimpleValueType();
13194 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13195 // decide if we should generate a 16-byte constant mask when we only need 4 or
13196 // 8 bytes for the scalar case.
13202 if (VT.isVector()) {
13204 EltVT = VT.getVectorElementType();
13205 NumElts = VT.getVectorNumElements();
13207 // There are no scalar bitwise logical SSE/AVX instructions, so we
13208 // generate a 16-byte vector constant and logic op even for the scalar case.
13209 // Using a 16-byte mask allows folding the load of the mask with
13210 // the logic op, so it can save (~4 bytes) on code size.
13211 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13213 NumElts = (VT == MVT::f64) ? 2 : 4;
13216 unsigned EltBits = EltVT.getSizeInBits();
13217 LLVMContext *Context = DAG.getContext();
13218 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13220 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13221 Constant *C = ConstantInt::get(*Context, MaskElt);
13222 C = ConstantVector::getSplat(NumElts, C);
13223 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13224 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13225 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13227 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13228 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13229 false, false, false, Alignment);
13231 SDValue Op0 = Op.getOperand(0);
13232 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13234 IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13235 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13238 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13240 // For the scalar case extend to a 128-bit vector, perform the logic op,
13241 // and extract the scalar result back out.
13242 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13243 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13244 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13245 DAG.getIntPtrConstant(0, dl));
13248 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13249 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13250 LLVMContext *Context = DAG.getContext();
13251 SDValue Op0 = Op.getOperand(0);
13252 SDValue Op1 = Op.getOperand(1);
13254 MVT VT = Op.getSimpleValueType();
13255 MVT SrcVT = Op1.getSimpleValueType();
13257 // If second operand is smaller, extend it first.
13258 if (SrcVT.bitsLT(VT)) {
13259 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13262 // And if it is bigger, shrink it first.
13263 if (SrcVT.bitsGT(VT)) {
13264 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13268 // At this point the operands and the result should have the same
13269 // type, and that won't be f80 since that is not custom lowered.
13271 const fltSemantics &Sem =
13272 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13273 const unsigned SizeInBits = VT.getSizeInBits();
13275 SmallVector<Constant *, 4> CV(
13276 VT == MVT::f64 ? 2 : 4,
13277 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13279 // First, clear all bits but the sign bit from the second operand (sign).
13280 CV[0] = ConstantFP::get(*Context,
13281 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13282 Constant *C = ConstantVector::get(CV);
13283 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13284 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13286 // Perform all logic operations as 16-byte vectors because there are no
13287 // scalar FP logic instructions in SSE. This allows load folding of the
13288 // constants into the logic instructions.
13289 MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13291 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13292 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13293 false, false, false, 16);
13294 Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13295 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13297 // Next, clear the sign bit from the first operand (magnitude).
13298 // If it's a constant, we can clear it here.
13299 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13300 APFloat APF = Op0CN->getValueAPF();
13301 // If the magnitude is a positive zero, the sign bit alone is enough.
13302 if (APF.isPosZero())
13303 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13304 DAG.getIntPtrConstant(0, dl));
13306 CV[0] = ConstantFP::get(*Context, APF);
13308 CV[0] = ConstantFP::get(
13310 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13312 C = ConstantVector::get(CV);
13313 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13315 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13316 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13317 false, false, false, 16);
13318 // If the magnitude operand wasn't a constant, we need to AND out the sign.
13319 if (!isa<ConstantFPSDNode>(Op0)) {
13320 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13321 Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13323 // OR the magnitude value with the sign bit.
13324 Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13325 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13326 DAG.getIntPtrConstant(0, dl));
13329 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13330 SDValue N0 = Op.getOperand(0);
13332 MVT VT = Op.getSimpleValueType();
13334 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13335 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13336 DAG.getConstant(1, dl, VT));
13337 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13340 // Check whether an OR'd tree is PTEST-able.
13341 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13342 SelectionDAG &DAG) {
13343 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13345 if (!Subtarget->hasSSE41())
13348 if (!Op->hasOneUse())
13351 SDNode *N = Op.getNode();
13354 SmallVector<SDValue, 8> Opnds;
13355 DenseMap<SDValue, unsigned> VecInMap;
13356 SmallVector<SDValue, 8> VecIns;
13357 EVT VT = MVT::Other;
13359 // Recognize a special case where a vector is casted into wide integer to
13361 Opnds.push_back(N->getOperand(0));
13362 Opnds.push_back(N->getOperand(1));
13364 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13365 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13366 // BFS traverse all OR'd operands.
13367 if (I->getOpcode() == ISD::OR) {
13368 Opnds.push_back(I->getOperand(0));
13369 Opnds.push_back(I->getOperand(1));
13370 // Re-evaluate the number of nodes to be traversed.
13371 e += 2; // 2 more nodes (LHS and RHS) are pushed.
13375 // Quit if a non-EXTRACT_VECTOR_ELT
13376 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13379 // Quit if without a constant index.
13380 SDValue Idx = I->getOperand(1);
13381 if (!isa<ConstantSDNode>(Idx))
13384 SDValue ExtractedFromVec = I->getOperand(0);
13385 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13386 if (M == VecInMap.end()) {
13387 VT = ExtractedFromVec.getValueType();
13388 // Quit if not 128/256-bit vector.
13389 if (!VT.is128BitVector() && !VT.is256BitVector())
13391 // Quit if not the same type.
13392 if (VecInMap.begin() != VecInMap.end() &&
13393 VT != VecInMap.begin()->first.getValueType())
13395 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13396 VecIns.push_back(ExtractedFromVec);
13398 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13401 assert((VT.is128BitVector() || VT.is256BitVector()) &&
13402 "Not extracted from 128-/256-bit vector.");
13404 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13406 for (DenseMap<SDValue, unsigned>::const_iterator
13407 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13408 // Quit if not all elements are used.
13409 if (I->second != FullMask)
13413 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13415 // Cast all vectors into TestVT for PTEST.
13416 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13417 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13419 // If more than one full vectors are evaluated, OR them first before PTEST.
13420 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13421 // Each iteration will OR 2 nodes and append the result until there is only
13422 // 1 node left, i.e. the final OR'd value of all vectors.
13423 SDValue LHS = VecIns[Slot];
13424 SDValue RHS = VecIns[Slot + 1];
13425 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13428 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13429 VecIns.back(), VecIns.back());
13432 /// \brief return true if \c Op has a use that doesn't just read flags.
13433 static bool hasNonFlagsUse(SDValue Op) {
13434 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13436 SDNode *User = *UI;
13437 unsigned UOpNo = UI.getOperandNo();
13438 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13439 // Look pass truncate.
13440 UOpNo = User->use_begin().getOperandNo();
13441 User = *User->use_begin();
13444 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13445 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13451 /// Emit nodes that will be selected as "test Op0,Op0", or something
13453 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13454 SelectionDAG &DAG) const {
13455 if (Op.getValueType() == MVT::i1) {
13456 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13457 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13458 DAG.getConstant(0, dl, MVT::i8));
13460 // CF and OF aren't always set the way we want. Determine which
13461 // of these we need.
13462 bool NeedCF = false;
13463 bool NeedOF = false;
13466 case X86::COND_A: case X86::COND_AE:
13467 case X86::COND_B: case X86::COND_BE:
13470 case X86::COND_G: case X86::COND_GE:
13471 case X86::COND_L: case X86::COND_LE:
13472 case X86::COND_O: case X86::COND_NO: {
13473 // Check if we really need to set the
13474 // Overflow flag. If NoSignedWrap is present
13475 // that is not actually needed.
13476 switch (Op->getOpcode()) {
13481 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13482 if (BinNode->Flags.hasNoSignedWrap())
13492 // See if we can use the EFLAGS value from the operand instead of
13493 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13494 // we prove that the arithmetic won't overflow, we can't use OF or CF.
13495 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13496 // Emit a CMP with 0, which is the TEST pattern.
13497 //if (Op.getValueType() == MVT::i1)
13498 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13499 // DAG.getConstant(0, MVT::i1));
13500 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13501 DAG.getConstant(0, dl, Op.getValueType()));
13503 unsigned Opcode = 0;
13504 unsigned NumOperands = 0;
13506 // Truncate operations may prevent the merge of the SETCC instruction
13507 // and the arithmetic instruction before it. Attempt to truncate the operands
13508 // of the arithmetic instruction and use a reduced bit-width instruction.
13509 bool NeedTruncation = false;
13510 SDValue ArithOp = Op;
13511 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13512 SDValue Arith = Op->getOperand(0);
13513 // Both the trunc and the arithmetic op need to have one user each.
13514 if (Arith->hasOneUse())
13515 switch (Arith.getOpcode()) {
13522 NeedTruncation = true;
13528 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13529 // which may be the result of a CAST. We use the variable 'Op', which is the
13530 // non-casted variable when we check for possible users.
13531 switch (ArithOp.getOpcode()) {
13533 // Due to an isel shortcoming, be conservative if this add is likely to be
13534 // selected as part of a load-modify-store instruction. When the root node
13535 // in a match is a store, isel doesn't know how to remap non-chain non-flag
13536 // uses of other nodes in the match, such as the ADD in this case. This
13537 // leads to the ADD being left around and reselected, with the result being
13538 // two adds in the output. Alas, even if none our users are stores, that
13539 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
13540 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
13541 // climbing the DAG back to the root, and it doesn't seem to be worth the
13543 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13544 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13545 if (UI->getOpcode() != ISD::CopyToReg &&
13546 UI->getOpcode() != ISD::SETCC &&
13547 UI->getOpcode() != ISD::STORE)
13550 if (ConstantSDNode *C =
13551 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13552 // An add of one will be selected as an INC.
13553 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13554 Opcode = X86ISD::INC;
13559 // An add of negative one (subtract of one) will be selected as a DEC.
13560 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13561 Opcode = X86ISD::DEC;
13567 // Otherwise use a regular EFLAGS-setting add.
13568 Opcode = X86ISD::ADD;
13573 // If we have a constant logical shift that's only used in a comparison
13574 // against zero turn it into an equivalent AND. This allows turning it into
13575 // a TEST instruction later.
13576 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13577 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13578 EVT VT = Op.getValueType();
13579 unsigned BitWidth = VT.getSizeInBits();
13580 unsigned ShAmt = Op->getConstantOperandVal(1);
13581 if (ShAmt >= BitWidth) // Avoid undefined shifts.
13583 APInt Mask = ArithOp.getOpcode() == ISD::SRL
13584 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13585 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13586 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13588 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13589 DAG.getConstant(Mask, dl, VT));
13590 DAG.ReplaceAllUsesWith(Op, New);
13596 // If the primary and result isn't used, don't bother using X86ISD::AND,
13597 // because a TEST instruction will be better.
13598 if (!hasNonFlagsUse(Op))
13604 // Due to the ISEL shortcoming noted above, be conservative if this op is
13605 // likely to be selected as part of a load-modify-store instruction.
13606 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13607 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13608 if (UI->getOpcode() == ISD::STORE)
13611 // Otherwise use a regular EFLAGS-setting instruction.
13612 switch (ArithOp.getOpcode()) {
13613 default: llvm_unreachable("unexpected operator!");
13614 case ISD::SUB: Opcode = X86ISD::SUB; break;
13615 case ISD::XOR: Opcode = X86ISD::XOR; break;
13616 case ISD::AND: Opcode = X86ISD::AND; break;
13618 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13619 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13620 if (EFLAGS.getNode())
13623 Opcode = X86ISD::OR;
13637 return SDValue(Op.getNode(), 1);
13643 // If we found that truncation is beneficial, perform the truncation and
13645 if (NeedTruncation) {
13646 EVT VT = Op.getValueType();
13647 SDValue WideVal = Op->getOperand(0);
13648 EVT WideVT = WideVal.getValueType();
13649 unsigned ConvertedOp = 0;
13650 // Use a target machine opcode to prevent further DAGCombine
13651 // optimizations that may separate the arithmetic operations
13652 // from the setcc node.
13653 switch (WideVal.getOpcode()) {
13655 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13656 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13657 case ISD::AND: ConvertedOp = X86ISD::AND; break;
13658 case ISD::OR: ConvertedOp = X86ISD::OR; break;
13659 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13663 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13664 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13665 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13666 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13667 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13673 // Emit a CMP with 0, which is the TEST pattern.
13674 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13675 DAG.getConstant(0, dl, Op.getValueType()));
13677 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13678 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13680 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13681 DAG.ReplaceAllUsesWith(Op, New);
13682 return SDValue(New.getNode(), 1);
13685 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13687 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13688 SDLoc dl, SelectionDAG &DAG) const {
13689 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13690 if (C->getAPIntValue() == 0)
13691 return EmitTest(Op0, X86CC, dl, DAG);
13693 if (Op0.getValueType() == MVT::i1)
13694 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13697 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13698 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13699 // Do the comparison at i32 if it's smaller, besides the Atom case.
13700 // This avoids subregister aliasing issues. Keep the smaller reference
13701 // if we're optimizing for size, however, as that'll allow better folding
13702 // of memory operations.
13703 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13704 !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13705 !Subtarget->isAtom()) {
13706 unsigned ExtendOp =
13707 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13708 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13709 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13711 // Use SUB instead of CMP to enable CSE between SUB and CMP.
13712 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13713 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13715 return SDValue(Sub.getNode(), 1);
13717 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13720 /// Convert a comparison if required by the subtarget.
13721 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13722 SelectionDAG &DAG) const {
13723 // If the subtarget does not support the FUCOMI instruction, floating-point
13724 // comparisons have to be converted.
13725 if (Subtarget->hasCMov() ||
13726 Cmp.getOpcode() != X86ISD::CMP ||
13727 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13728 !Cmp.getOperand(1).getValueType().isFloatingPoint())
13731 // The instruction selector will select an FUCOM instruction instead of
13732 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13733 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13734 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13736 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13737 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13738 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13739 DAG.getConstant(8, dl, MVT::i8));
13740 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13741 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13744 /// The minimum architected relative accuracy is 2^-12. We need one
13745 /// Newton-Raphson step to have a good float result (24 bits of precision).
13746 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13747 DAGCombinerInfo &DCI,
13748 unsigned &RefinementSteps,
13749 bool &UseOneConstNR) const {
13750 EVT VT = Op.getValueType();
13751 const char *RecipOp;
13753 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13754 // TODO: Add support for AVX512 (v16f32).
13755 // It is likely not profitable to do this for f64 because a double-precision
13756 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13757 // instructions: convert to single, rsqrtss, convert back to double, refine
13758 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13759 // along with FMA, this could be a throughput win.
13760 if (VT == MVT::f32 && Subtarget->hasSSE1())
13762 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13763 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13764 RecipOp = "vec-sqrtf";
13768 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13769 if (!Recips.isEnabled(RecipOp))
13772 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13773 UseOneConstNR = false;
13774 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13777 /// The minimum architected relative accuracy is 2^-12. We need one
13778 /// Newton-Raphson step to have a good float result (24 bits of precision).
13779 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13780 DAGCombinerInfo &DCI,
13781 unsigned &RefinementSteps) const {
13782 EVT VT = Op.getValueType();
13783 const char *RecipOp;
13785 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13786 // TODO: Add support for AVX512 (v16f32).
13787 // It is likely not profitable to do this for f64 because a double-precision
13788 // reciprocal estimate with refinement on x86 prior to FMA requires
13789 // 15 instructions: convert to single, rcpss, convert back to double, refine
13790 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13791 // along with FMA, this could be a throughput win.
13792 if (VT == MVT::f32 && Subtarget->hasSSE1())
13794 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13795 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13796 RecipOp = "vec-divf";
13800 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13801 if (!Recips.isEnabled(RecipOp))
13804 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13805 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13808 /// If we have at least two divisions that use the same divisor, convert to
13809 /// multplication by a reciprocal. This may need to be adjusted for a given
13810 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13811 /// This is because we still need one division to calculate the reciprocal and
13812 /// then we need two multiplies by that reciprocal as replacements for the
13813 /// original divisions.
13814 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13818 static bool isAllOnes(SDValue V) {
13819 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13820 return C && C->isAllOnesValue();
13823 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13824 /// if it's possible.
13825 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13826 SDLoc dl, SelectionDAG &DAG) const {
13827 SDValue Op0 = And.getOperand(0);
13828 SDValue Op1 = And.getOperand(1);
13829 if (Op0.getOpcode() == ISD::TRUNCATE)
13830 Op0 = Op0.getOperand(0);
13831 if (Op1.getOpcode() == ISD::TRUNCATE)
13832 Op1 = Op1.getOperand(0);
13835 if (Op1.getOpcode() == ISD::SHL)
13836 std::swap(Op0, Op1);
13837 if (Op0.getOpcode() == ISD::SHL) {
13838 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13839 if (And00C->getZExtValue() == 1) {
13840 // If we looked past a truncate, check that it's only truncating away
13842 unsigned BitWidth = Op0.getValueSizeInBits();
13843 unsigned AndBitWidth = And.getValueSizeInBits();
13844 if (BitWidth > AndBitWidth) {
13846 DAG.computeKnownBits(Op0, Zeros, Ones);
13847 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13851 RHS = Op0.getOperand(1);
13853 } else if (Op1.getOpcode() == ISD::Constant) {
13854 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13855 uint64_t AndRHSVal = AndRHS->getZExtValue();
13856 SDValue AndLHS = Op0;
13858 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13859 LHS = AndLHS.getOperand(0);
13860 RHS = AndLHS.getOperand(1);
13863 // Use BT if the immediate can't be encoded in a TEST instruction.
13864 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13866 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13870 if (LHS.getNode()) {
13871 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
13872 // instruction. Since the shift amount is in-range-or-undefined, we know
13873 // that doing a bittest on the i32 value is ok. We extend to i32 because
13874 // the encoding for the i16 version is larger than the i32 version.
13875 // Also promote i16 to i32 for performance / code size reason.
13876 if (LHS.getValueType() == MVT::i8 ||
13877 LHS.getValueType() == MVT::i16)
13878 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13880 // If the operand types disagree, extend the shift amount to match. Since
13881 // BT ignores high bits (like shifts) we can use anyextend.
13882 if (LHS.getValueType() != RHS.getValueType())
13883 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13885 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13886 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13887 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13888 DAG.getConstant(Cond, dl, MVT::i8), BT);
13894 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13896 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13901 // SSE Condition code mapping:
13910 switch (SetCCOpcode) {
13911 default: llvm_unreachable("Unexpected SETCC condition");
13913 case ISD::SETEQ: SSECC = 0; break;
13915 case ISD::SETGT: Swap = true; // Fallthrough
13917 case ISD::SETOLT: SSECC = 1; break;
13919 case ISD::SETGE: Swap = true; // Fallthrough
13921 case ISD::SETOLE: SSECC = 2; break;
13922 case ISD::SETUO: SSECC = 3; break;
13924 case ISD::SETNE: SSECC = 4; break;
13925 case ISD::SETULE: Swap = true; // Fallthrough
13926 case ISD::SETUGE: SSECC = 5; break;
13927 case ISD::SETULT: Swap = true; // Fallthrough
13928 case ISD::SETUGT: SSECC = 6; break;
13929 case ISD::SETO: SSECC = 7; break;
13931 case ISD::SETONE: SSECC = 8; break;
13934 std::swap(Op0, Op1);
13939 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13940 // ones, and then concatenate the result back.
13941 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13942 MVT VT = Op.getSimpleValueType();
13944 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13945 "Unsupported value type for operation");
13947 unsigned NumElems = VT.getVectorNumElements();
13949 SDValue CC = Op.getOperand(2);
13951 // Extract the LHS vectors
13952 SDValue LHS = Op.getOperand(0);
13953 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13954 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13956 // Extract the RHS vectors
13957 SDValue RHS = Op.getOperand(1);
13958 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13959 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13961 // Issue the operation on the smaller types and concatenate the result back
13962 MVT EltVT = VT.getVectorElementType();
13963 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13964 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13965 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13966 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13969 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13970 SDValue Op0 = Op.getOperand(0);
13971 SDValue Op1 = Op.getOperand(1);
13972 SDValue CC = Op.getOperand(2);
13973 MVT VT = Op.getSimpleValueType();
13976 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13977 "Unexpected type for boolean compare operation");
13978 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13979 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13980 DAG.getConstant(-1, dl, VT));
13981 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13982 DAG.getConstant(-1, dl, VT));
13983 switch (SetCCOpcode) {
13984 default: llvm_unreachable("Unexpected SETCC condition");
13986 // (x == y) -> ~(x ^ y)
13987 return DAG.getNode(ISD::XOR, dl, VT,
13988 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13989 DAG.getConstant(-1, dl, VT));
13991 // (x != y) -> (x ^ y)
13992 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13995 // (x > y) -> (x & ~y)
13996 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13999 // (x < y) -> (~x & y)
14000 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14003 // (x <= y) -> (~x | y)
14004 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14007 // (x >=y) -> (x | ~y)
14008 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14012 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14013 const X86Subtarget *Subtarget) {
14014 SDValue Op0 = Op.getOperand(0);
14015 SDValue Op1 = Op.getOperand(1);
14016 SDValue CC = Op.getOperand(2);
14017 MVT VT = Op.getSimpleValueType();
14020 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
14021 Op.getValueType().getScalarType() == MVT::i1 &&
14022 "Cannot set masked compare for this operation");
14024 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14026 bool Unsigned = false;
14029 switch (SetCCOpcode) {
14030 default: llvm_unreachable("Unexpected SETCC condition");
14031 case ISD::SETNE: SSECC = 4; break;
14032 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
14033 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14034 case ISD::SETLT: Swap = true; //fall-through
14035 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
14036 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14037 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14038 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
14039 case ISD::SETULE: Unsigned = true; //fall-through
14040 case ISD::SETLE: SSECC = 2; break;
14044 std::swap(Op0, Op1);
14046 return DAG.getNode(Opc, dl, VT, Op0, Op1);
14047 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14048 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14049 DAG.getConstant(SSECC, dl, MVT::i8));
14052 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14053 /// operand \p Op1. If non-trivial (for example because it's not constant)
14054 /// return an empty value.
14055 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14057 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14061 MVT VT = Op1.getSimpleValueType();
14062 MVT EVT = VT.getVectorElementType();
14063 unsigned n = VT.getVectorNumElements();
14064 SmallVector<SDValue, 8> ULTOp1;
14066 for (unsigned i = 0; i < n; ++i) {
14067 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14068 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
14071 // Avoid underflow.
14072 APInt Val = Elt->getAPIntValue();
14076 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14079 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14082 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14083 SelectionDAG &DAG) {
14084 SDValue Op0 = Op.getOperand(0);
14085 SDValue Op1 = Op.getOperand(1);
14086 SDValue CC = Op.getOperand(2);
14087 MVT VT = Op.getSimpleValueType();
14088 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14089 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14094 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14095 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14098 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14099 unsigned Opc = X86ISD::CMPP;
14100 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14101 assert(VT.getVectorNumElements() <= 16);
14102 Opc = X86ISD::CMPM;
14104 // In the two special cases we can't handle, emit two comparisons.
14107 unsigned CombineOpc;
14108 if (SetCCOpcode == ISD::SETUEQ) {
14109 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14111 assert(SetCCOpcode == ISD::SETONE);
14112 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14115 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14116 DAG.getConstant(CC0, dl, MVT::i8));
14117 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14118 DAG.getConstant(CC1, dl, MVT::i8));
14119 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14121 // Handle all other FP comparisons here.
14122 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14123 DAG.getConstant(SSECC, dl, MVT::i8));
14126 // Break 256-bit integer vector compare into smaller ones.
14127 if (VT.is256BitVector() && !Subtarget->hasInt256())
14128 return Lower256IntVSETCC(Op, DAG);
14130 EVT OpVT = Op1.getValueType();
14131 if (OpVT.getVectorElementType() == MVT::i1)
14132 return LowerBoolVSETCC_AVX512(Op, DAG);
14134 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14135 if (Subtarget->hasAVX512()) {
14136 if (Op1.getValueType().is512BitVector() ||
14137 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14138 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14139 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14141 // In AVX-512 architecture setcc returns mask with i1 elements,
14142 // But there is no compare instruction for i8 and i16 elements in KNL.
14143 // We are not talking about 512-bit operands in this case, these
14144 // types are illegal.
14146 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14147 OpVT.getVectorElementType().getSizeInBits() >= 8))
14148 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14149 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14152 // We are handling one of the integer comparisons here. Since SSE only has
14153 // GT and EQ comparisons for integer, swapping operands and multiple
14154 // operations may be required for some comparisons.
14156 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14157 bool Subus = false;
14159 switch (SetCCOpcode) {
14160 default: llvm_unreachable("Unexpected SETCC condition");
14161 case ISD::SETNE: Invert = true;
14162 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
14163 case ISD::SETLT: Swap = true;
14164 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
14165 case ISD::SETGE: Swap = true;
14166 case ISD::SETLE: Opc = X86ISD::PCMPGT;
14167 Invert = true; break;
14168 case ISD::SETULT: Swap = true;
14169 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14170 FlipSigns = true; break;
14171 case ISD::SETUGE: Swap = true;
14172 case ISD::SETULE: Opc = X86ISD::PCMPGT;
14173 FlipSigns = true; Invert = true; break;
14176 // Special case: Use min/max operations for SETULE/SETUGE
14177 MVT VET = VT.getVectorElementType();
14179 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14180 || (Subtarget->hasSSE2() && (VET == MVT::i8));
14183 switch (SetCCOpcode) {
14185 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14186 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14189 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14192 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14193 if (!MinMax && hasSubus) {
14194 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14196 // t = psubus Op0, Op1
14197 // pcmpeq t, <0..0>
14198 switch (SetCCOpcode) {
14200 case ISD::SETULT: {
14201 // If the comparison is against a constant we can turn this into a
14202 // setule. With psubus, setule does not require a swap. This is
14203 // beneficial because the constant in the register is no longer
14204 // destructed as the destination so it can be hoisted out of a loop.
14205 // Only do this pre-AVX since vpcmp* is no longer destructive.
14206 if (Subtarget->hasAVX())
14208 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14209 if (ULEOp1.getNode()) {
14211 Subus = true; Invert = false; Swap = false;
14215 // Psubus is better than flip-sign because it requires no inversion.
14216 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
14217 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14221 Opc = X86ISD::SUBUS;
14227 std::swap(Op0, Op1);
14229 // Check that the operation in question is available (most are plain SSE2,
14230 // but PCMPGTQ and PCMPEQQ have different requirements).
14231 if (VT == MVT::v2i64) {
14232 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14233 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14235 // First cast everything to the right type.
14236 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14237 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14239 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14240 // bits of the inputs before performing those operations. The lower
14241 // compare is always unsigned.
14244 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14246 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14247 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14248 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14249 Sign, Zero, Sign, Zero);
14251 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14252 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14254 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14255 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14256 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14258 // Create masks for only the low parts/high parts of the 64 bit integers.
14259 static const int MaskHi[] = { 1, 1, 3, 3 };
14260 static const int MaskLo[] = { 0, 0, 2, 2 };
14261 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14262 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14263 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14265 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14266 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14269 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14271 return DAG.getBitcast(VT, Result);
14274 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14275 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14276 // pcmpeqd + pshufd + pand.
14277 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14279 // First cast everything to the right type.
14280 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14281 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14284 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14286 // Make sure the lower and upper halves are both all-ones.
14287 static const int Mask[] = { 1, 0, 3, 2 };
14288 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14289 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14292 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14294 return DAG.getBitcast(VT, Result);
14298 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14299 // bits of the inputs before performing those operations.
14301 EVT EltVT = VT.getVectorElementType();
14302 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14304 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14305 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14308 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14310 // If the logical-not of the result is required, perform that now.
14312 Result = DAG.getNOT(dl, Result, VT);
14315 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14318 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14319 getZeroVector(VT, Subtarget, DAG, dl));
14324 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14326 MVT VT = Op.getSimpleValueType();
14328 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14330 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14331 && "SetCC type must be 8-bit or 1-bit integer");
14332 SDValue Op0 = Op.getOperand(0);
14333 SDValue Op1 = Op.getOperand(1);
14335 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14337 // Optimize to BT if possible.
14338 // Lower (X & (1 << N)) == 0 to BT(X, N).
14339 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14340 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14341 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14342 Op1.getOpcode() == ISD::Constant &&
14343 cast<ConstantSDNode>(Op1)->isNullValue() &&
14344 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14345 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14346 if (NewSetCC.getNode()) {
14348 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14353 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
14355 if (Op1.getOpcode() == ISD::Constant &&
14356 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14357 cast<ConstantSDNode>(Op1)->isNullValue()) &&
14358 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14360 // If the input is a setcc, then reuse the input setcc or use a new one with
14361 // the inverted condition.
14362 if (Op0.getOpcode() == X86ISD::SETCC) {
14363 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14364 bool Invert = (CC == ISD::SETNE) ^
14365 cast<ConstantSDNode>(Op1)->isNullValue();
14369 CCode = X86::GetOppositeBranchCondition(CCode);
14370 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14371 DAG.getConstant(CCode, dl, MVT::i8),
14372 Op0.getOperand(1));
14374 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14378 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14379 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14380 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14382 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14383 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14386 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14387 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14388 if (X86CC == X86::COND_INVALID)
14391 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14392 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14393 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14394 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14396 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14400 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14401 static bool isX86LogicalCmp(SDValue Op) {
14402 unsigned Opc = Op.getNode()->getOpcode();
14403 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14404 Opc == X86ISD::SAHF)
14406 if (Op.getResNo() == 1 &&
14407 (Opc == X86ISD::ADD ||
14408 Opc == X86ISD::SUB ||
14409 Opc == X86ISD::ADC ||
14410 Opc == X86ISD::SBB ||
14411 Opc == X86ISD::SMUL ||
14412 Opc == X86ISD::UMUL ||
14413 Opc == X86ISD::INC ||
14414 Opc == X86ISD::DEC ||
14415 Opc == X86ISD::OR ||
14416 Opc == X86ISD::XOR ||
14417 Opc == X86ISD::AND))
14420 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14426 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14427 if (V.getOpcode() != ISD::TRUNCATE)
14430 SDValue VOp0 = V.getOperand(0);
14431 unsigned InBits = VOp0.getValueSizeInBits();
14432 unsigned Bits = V.getValueSizeInBits();
14433 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14436 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14437 bool addTest = true;
14438 SDValue Cond = Op.getOperand(0);
14439 SDValue Op1 = Op.getOperand(1);
14440 SDValue Op2 = Op.getOperand(2);
14442 EVT VT = Op1.getValueType();
14445 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14446 // are available or VBLENDV if AVX is available.
14447 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14448 if (Cond.getOpcode() == ISD::SETCC &&
14449 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14450 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14451 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14452 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14453 int SSECC = translateX86FSETCC(
14454 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14457 if (Subtarget->hasAVX512()) {
14458 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14459 DAG.getConstant(SSECC, DL, MVT::i8));
14460 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14463 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14464 DAG.getConstant(SSECC, DL, MVT::i8));
14466 // If we have AVX, we can use a variable vector select (VBLENDV) instead
14467 // of 3 logic instructions for size savings and potentially speed.
14468 // Unfortunately, there is no scalar form of VBLENDV.
14470 // If either operand is a constant, don't try this. We can expect to
14471 // optimize away at least one of the logic instructions later in that
14472 // case, so that sequence would be faster than a variable blend.
14474 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14475 // uses XMM0 as the selection register. That may need just as many
14476 // instructions as the AND/ANDN/OR sequence due to register moves, so
14479 if (Subtarget->hasAVX() &&
14480 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14482 // Convert to vectors, do a VSELECT, and convert back to scalar.
14483 // All of the conversions should be optimized away.
14485 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14486 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14487 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14488 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14490 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14491 VCmp = DAG.getBitcast(VCmpVT, VCmp);
14493 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14495 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14496 VSel, DAG.getIntPtrConstant(0, DL));
14498 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14499 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14500 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14504 if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14506 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14507 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14508 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14509 Op1Scalar = Op1.getOperand(0);
14511 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14512 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14513 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14514 Op2Scalar = Op2.getOperand(0);
14515 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14516 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14517 Op1Scalar.getValueType(),
14518 Cond, Op1Scalar, Op2Scalar);
14519 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14520 return DAG.getBitcast(VT, newSelect);
14521 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14522 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14523 DAG.getIntPtrConstant(0, DL));
14527 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14528 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14529 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14530 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14531 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14532 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14533 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14535 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14538 if (Cond.getOpcode() == ISD::SETCC) {
14539 SDValue NewCond = LowerSETCC(Cond, DAG);
14540 if (NewCond.getNode())
14544 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14545 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14546 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14547 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14548 if (Cond.getOpcode() == X86ISD::SETCC &&
14549 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14550 isZero(Cond.getOperand(1).getOperand(1))) {
14551 SDValue Cmp = Cond.getOperand(1);
14553 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14555 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14556 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14557 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14559 SDValue CmpOp0 = Cmp.getOperand(0);
14560 // Apply further optimizations for special cases
14561 // (select (x != 0), -1, 0) -> neg & sbb
14562 // (select (x == 0), 0, -1) -> neg & sbb
14563 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14564 if (YC->isNullValue() &&
14565 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14566 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14567 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14568 DAG.getConstant(0, DL,
14569 CmpOp0.getValueType()),
14571 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14572 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14573 SDValue(Neg.getNode(), 1));
14577 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14578 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14579 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14581 SDValue Res = // Res = 0 or -1.
14582 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14583 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14585 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14586 Res = DAG.getNOT(DL, Res, Res.getValueType());
14588 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14589 if (!N2C || !N2C->isNullValue())
14590 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14595 // Look past (and (setcc_carry (cmp ...)), 1).
14596 if (Cond.getOpcode() == ISD::AND &&
14597 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14598 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14599 if (C && C->getAPIntValue() == 1)
14600 Cond = Cond.getOperand(0);
14603 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14604 // setting operand in place of the X86ISD::SETCC.
14605 unsigned CondOpcode = Cond.getOpcode();
14606 if (CondOpcode == X86ISD::SETCC ||
14607 CondOpcode == X86ISD::SETCC_CARRY) {
14608 CC = Cond.getOperand(0);
14610 SDValue Cmp = Cond.getOperand(1);
14611 unsigned Opc = Cmp.getOpcode();
14612 MVT VT = Op.getSimpleValueType();
14614 bool IllegalFPCMov = false;
14615 if (VT.isFloatingPoint() && !VT.isVector() &&
14616 !isScalarFPTypeInSSEReg(VT)) // FPStack?
14617 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14619 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14620 Opc == X86ISD::BT) { // FIXME
14624 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14625 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14626 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14627 Cond.getOperand(0).getValueType() != MVT::i8)) {
14628 SDValue LHS = Cond.getOperand(0);
14629 SDValue RHS = Cond.getOperand(1);
14630 unsigned X86Opcode;
14633 switch (CondOpcode) {
14634 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14635 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14636 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14637 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14638 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14639 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14640 default: llvm_unreachable("unexpected overflowing operator");
14642 if (CondOpcode == ISD::UMULO)
14643 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14646 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14648 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14650 if (CondOpcode == ISD::UMULO)
14651 Cond = X86Op.getValue(2);
14653 Cond = X86Op.getValue(1);
14655 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14660 // Look past the truncate if the high bits are known zero.
14661 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14662 Cond = Cond.getOperand(0);
14664 // We know the result of AND is compared against zero. Try to match
14666 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14667 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14668 if (NewSetCC.getNode()) {
14669 CC = NewSetCC.getOperand(0);
14670 Cond = NewSetCC.getOperand(1);
14677 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14678 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14681 // a < b ? -1 : 0 -> RES = ~setcc_carry
14682 // a < b ? 0 : -1 -> RES = setcc_carry
14683 // a >= b ? -1 : 0 -> RES = setcc_carry
14684 // a >= b ? 0 : -1 -> RES = ~setcc_carry
14685 if (Cond.getOpcode() == X86ISD::SUB) {
14686 Cond = ConvertCmpIfNecessary(Cond, DAG);
14687 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14689 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14690 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14691 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14692 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14694 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14695 return DAG.getNOT(DL, Res, Res.getValueType());
14700 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14701 // widen the cmov and push the truncate through. This avoids introducing a new
14702 // branch during isel and doesn't add any extensions.
14703 if (Op.getValueType() == MVT::i8 &&
14704 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14705 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14706 if (T1.getValueType() == T2.getValueType() &&
14707 // Blacklist CopyFromReg to avoid partial register stalls.
14708 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14709 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14710 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14711 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14715 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14716 // condition is true.
14717 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14718 SDValue Ops[] = { Op2, Op1, CC, Cond };
14719 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14722 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14723 const X86Subtarget *Subtarget,
14724 SelectionDAG &DAG) {
14725 MVT VT = Op->getSimpleValueType(0);
14726 SDValue In = Op->getOperand(0);
14727 MVT InVT = In.getSimpleValueType();
14728 MVT VTElt = VT.getVectorElementType();
14729 MVT InVTElt = InVT.getVectorElementType();
14733 if ((InVTElt == MVT::i1) &&
14734 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14735 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14737 ((Subtarget->hasBWI() && VT.is512BitVector() &&
14738 VTElt.getSizeInBits() <= 16)) ||
14740 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14741 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14743 ((Subtarget->hasDQI() && VT.is512BitVector() &&
14744 VTElt.getSizeInBits() >= 32))))
14745 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14747 unsigned int NumElts = VT.getVectorNumElements();
14749 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14752 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14753 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14754 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14755 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14758 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14759 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14761 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14764 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14766 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14767 if (VT.is512BitVector())
14769 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14772 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14773 const X86Subtarget *Subtarget,
14774 SelectionDAG &DAG) {
14775 SDValue In = Op->getOperand(0);
14776 MVT VT = Op->getSimpleValueType(0);
14777 MVT InVT = In.getSimpleValueType();
14778 assert(VT.getSizeInBits() == InVT.getSizeInBits());
14780 MVT InSVT = InVT.getScalarType();
14781 assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14783 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14785 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14790 // SSE41 targets can use the pmovsx* instructions directly.
14791 if (Subtarget->hasSSE41())
14792 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14794 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14798 // As SRAI is only available on i16/i32 types, we expand only up to i32
14799 // and handle i64 separately.
14800 while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14801 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14802 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14803 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14804 Curr = DAG.getBitcast(CurrVT, Curr);
14807 SDValue SignExt = Curr;
14808 if (CurrVT != InVT) {
14809 unsigned SignExtShift =
14810 CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14811 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14812 DAG.getConstant(SignExtShift, dl, MVT::i8));
14818 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14819 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14820 DAG.getConstant(31, dl, MVT::i8));
14821 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14822 return DAG.getBitcast(VT, Ext);
14828 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14829 SelectionDAG &DAG) {
14830 MVT VT = Op->getSimpleValueType(0);
14831 SDValue In = Op->getOperand(0);
14832 MVT InVT = In.getSimpleValueType();
14835 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14836 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14838 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14839 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14840 (VT != MVT::v16i16 || InVT != MVT::v16i8))
14843 if (Subtarget->hasInt256())
14844 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14846 // Optimize vectors in AVX mode
14847 // Sign extend v8i16 to v8i32 and
14850 // Divide input vector into two parts
14851 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14852 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14853 // concat the vectors to original VT
14855 unsigned NumElems = InVT.getVectorNumElements();
14856 SDValue Undef = DAG.getUNDEF(InVT);
14858 SmallVector<int,8> ShufMask1(NumElems, -1);
14859 for (unsigned i = 0; i != NumElems/2; ++i)
14862 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14864 SmallVector<int,8> ShufMask2(NumElems, -1);
14865 for (unsigned i = 0; i != NumElems/2; ++i)
14866 ShufMask2[i] = i + NumElems/2;
14868 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14870 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14871 VT.getVectorNumElements()/2);
14873 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14874 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14876 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14879 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14880 // may emit an illegal shuffle but the expansion is still better than scalar
14881 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14882 // we'll emit a shuffle and a arithmetic shift.
14883 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14884 // TODO: It is possible to support ZExt by zeroing the undef values during
14885 // the shuffle phase or after the shuffle.
14886 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14887 SelectionDAG &DAG) {
14888 MVT RegVT = Op.getSimpleValueType();
14889 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14890 assert(RegVT.isInteger() &&
14891 "We only custom lower integer vector sext loads.");
14893 // Nothing useful we can do without SSE2 shuffles.
14894 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14896 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14898 EVT MemVT = Ld->getMemoryVT();
14899 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14900 unsigned RegSz = RegVT.getSizeInBits();
14902 ISD::LoadExtType Ext = Ld->getExtensionType();
14904 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14905 && "Only anyext and sext are currently implemented.");
14906 assert(MemVT != RegVT && "Cannot extend to the same type");
14907 assert(MemVT.isVector() && "Must load a vector from memory");
14909 unsigned NumElems = RegVT.getVectorNumElements();
14910 unsigned MemSz = MemVT.getSizeInBits();
14911 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14913 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14914 // The only way in which we have a legal 256-bit vector result but not the
14915 // integer 256-bit operations needed to directly lower a sextload is if we
14916 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14917 // a 128-bit vector and a normal sign_extend to 256-bits that should get
14918 // correctly legalized. We do this late to allow the canonical form of
14919 // sextload to persist throughout the rest of the DAG combiner -- it wants
14920 // to fold together any extensions it can, and so will fuse a sign_extend
14921 // of an sextload into a sextload targeting a wider value.
14923 if (MemSz == 128) {
14924 // Just switch this to a normal load.
14925 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14926 "it must be a legal 128-bit vector "
14928 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14929 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14930 Ld->isInvariant(), Ld->getAlignment());
14932 assert(MemSz < 128 &&
14933 "Can't extend a type wider than 128 bits to a 256 bit vector!");
14934 // Do an sext load to a 128-bit vector type. We want to use the same
14935 // number of elements, but elements half as wide. This will end up being
14936 // recursively lowered by this routine, but will succeed as we definitely
14937 // have all the necessary features if we're using AVX1.
14939 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14940 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14942 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14943 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14944 Ld->isNonTemporal(), Ld->isInvariant(),
14945 Ld->getAlignment());
14948 // Replace chain users with the new chain.
14949 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14950 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14952 // Finally, do a normal sign-extend to the desired register.
14953 return DAG.getSExtOrTrunc(Load, dl, RegVT);
14956 // All sizes must be a power of two.
14957 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14958 "Non-power-of-two elements are not custom lowered!");
14960 // Attempt to load the original value using scalar loads.
14961 // Find the largest scalar type that divides the total loaded size.
14962 MVT SclrLoadTy = MVT::i8;
14963 for (MVT Tp : MVT::integer_valuetypes()) {
14964 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14969 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14970 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14972 SclrLoadTy = MVT::f64;
14974 // Calculate the number of scalar loads that we need to perform
14975 // in order to load our vector from memory.
14976 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14978 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14979 "Can only lower sext loads with a single scalar load!");
14981 unsigned loadRegZize = RegSz;
14982 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14985 // Represent our vector as a sequence of elements which are the
14986 // largest scalar that we can load.
14987 EVT LoadUnitVecVT = EVT::getVectorVT(
14988 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14990 // Represent the data using the same element type that is stored in
14991 // memory. In practice, we ''widen'' MemVT.
14993 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14994 loadRegZize / MemVT.getScalarType().getSizeInBits());
14996 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14997 "Invalid vector type");
14999 // We can't shuffle using an illegal type.
15000 assert(TLI.isTypeLegal(WideVecVT) &&
15001 "We only lower types that form legal widened vector types");
15003 SmallVector<SDValue, 8> Chains;
15004 SDValue Ptr = Ld->getBasePtr();
15005 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15006 TLI.getPointerTy(DAG.getDataLayout()));
15007 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15009 for (unsigned i = 0; i < NumLoads; ++i) {
15010 // Perform a single load.
15011 SDValue ScalarLoad =
15012 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15013 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15014 Ld->getAlignment());
15015 Chains.push_back(ScalarLoad.getValue(1));
15016 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15017 // another round of DAGCombining.
15019 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15021 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15022 ScalarLoad, DAG.getIntPtrConstant(i, dl));
15024 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15027 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15029 // Bitcast the loaded value to a vector of the original element type, in
15030 // the size of the target vector type.
15031 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15032 unsigned SizeRatio = RegSz / MemSz;
15034 if (Ext == ISD::SEXTLOAD) {
15035 // If we have SSE4.1, we can directly emit a VSEXT node.
15036 if (Subtarget->hasSSE41()) {
15037 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15038 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15042 // Otherwise we'll shuffle the small elements in the high bits of the
15043 // larger type and perform an arithmetic shift. If the shift is not legal
15044 // it's better to scalarize.
15045 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
15046 "We can't implement a sext load without an arithmetic right shift!");
15048 // Redistribute the loaded elements into the different locations.
15049 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15050 for (unsigned i = 0; i != NumElems; ++i)
15051 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
15053 SDValue Shuff = DAG.getVectorShuffle(
15054 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15056 Shuff = DAG.getBitcast(RegVT, Shuff);
15058 // Build the arithmetic shift.
15059 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
15060 MemVT.getVectorElementType().getSizeInBits();
15062 DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
15063 DAG.getConstant(Amt, dl, RegVT));
15065 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15069 // Redistribute the loaded elements into the different locations.
15070 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15071 for (unsigned i = 0; i != NumElems; ++i)
15072 ShuffleVec[i * SizeRatio] = i;
15074 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15075 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15077 // Bitcast to the requested type.
15078 Shuff = DAG.getBitcast(RegVT, Shuff);
15079 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15083 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15084 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15085 // from the AND / OR.
15086 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15087 Opc = Op.getOpcode();
15088 if (Opc != ISD::OR && Opc != ISD::AND)
15090 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15091 Op.getOperand(0).hasOneUse() &&
15092 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15093 Op.getOperand(1).hasOneUse());
15096 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15097 // 1 and that the SETCC node has a single use.
15098 static bool isXor1OfSetCC(SDValue Op) {
15099 if (Op.getOpcode() != ISD::XOR)
15101 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15102 if (N1C && N1C->getAPIntValue() == 1) {
15103 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15104 Op.getOperand(0).hasOneUse();
15109 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15110 bool addTest = true;
15111 SDValue Chain = Op.getOperand(0);
15112 SDValue Cond = Op.getOperand(1);
15113 SDValue Dest = Op.getOperand(2);
15116 bool Inverted = false;
15118 if (Cond.getOpcode() == ISD::SETCC) {
15119 // Check for setcc([su]{add,sub,mul}o == 0).
15120 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15121 isa<ConstantSDNode>(Cond.getOperand(1)) &&
15122 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15123 Cond.getOperand(0).getResNo() == 1 &&
15124 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15125 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15126 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15127 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15128 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15129 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15131 Cond = Cond.getOperand(0);
15133 SDValue NewCond = LowerSETCC(Cond, DAG);
15134 if (NewCond.getNode())
15139 // FIXME: LowerXALUO doesn't handle these!!
15140 else if (Cond.getOpcode() == X86ISD::ADD ||
15141 Cond.getOpcode() == X86ISD::SUB ||
15142 Cond.getOpcode() == X86ISD::SMUL ||
15143 Cond.getOpcode() == X86ISD::UMUL)
15144 Cond = LowerXALUO(Cond, DAG);
15147 // Look pass (and (setcc_carry (cmp ...)), 1).
15148 if (Cond.getOpcode() == ISD::AND &&
15149 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15150 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15151 if (C && C->getAPIntValue() == 1)
15152 Cond = Cond.getOperand(0);
15155 // If condition flag is set by a X86ISD::CMP, then use it as the condition
15156 // setting operand in place of the X86ISD::SETCC.
15157 unsigned CondOpcode = Cond.getOpcode();
15158 if (CondOpcode == X86ISD::SETCC ||
15159 CondOpcode == X86ISD::SETCC_CARRY) {
15160 CC = Cond.getOperand(0);
15162 SDValue Cmp = Cond.getOperand(1);
15163 unsigned Opc = Cmp.getOpcode();
15164 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15165 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15169 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15173 // These can only come from an arithmetic instruction with overflow,
15174 // e.g. SADDO, UADDO.
15175 Cond = Cond.getNode()->getOperand(1);
15181 CondOpcode = Cond.getOpcode();
15182 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15183 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15184 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15185 Cond.getOperand(0).getValueType() != MVT::i8)) {
15186 SDValue LHS = Cond.getOperand(0);
15187 SDValue RHS = Cond.getOperand(1);
15188 unsigned X86Opcode;
15191 // Keep this in sync with LowerXALUO, otherwise we might create redundant
15192 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15194 switch (CondOpcode) {
15195 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15197 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15199 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15202 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15203 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15205 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15207 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15210 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15211 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15212 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15213 default: llvm_unreachable("unexpected overflowing operator");
15216 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15217 if (CondOpcode == ISD::UMULO)
15218 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15221 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15223 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15225 if (CondOpcode == ISD::UMULO)
15226 Cond = X86Op.getValue(2);
15228 Cond = X86Op.getValue(1);
15230 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15234 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15235 SDValue Cmp = Cond.getOperand(0).getOperand(1);
15236 if (CondOpc == ISD::OR) {
15237 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15238 // two branches instead of an explicit OR instruction with a
15240 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15241 isX86LogicalCmp(Cmp)) {
15242 CC = Cond.getOperand(0).getOperand(0);
15243 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15244 Chain, Dest, CC, Cmp);
15245 CC = Cond.getOperand(1).getOperand(0);
15249 } else { // ISD::AND
15250 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15251 // two branches instead of an explicit AND instruction with a
15252 // separate test. However, we only do this if this block doesn't
15253 // have a fall-through edge, because this requires an explicit
15254 // jmp when the condition is false.
15255 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15256 isX86LogicalCmp(Cmp) &&
15257 Op.getNode()->hasOneUse()) {
15258 X86::CondCode CCode =
15259 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15260 CCode = X86::GetOppositeBranchCondition(CCode);
15261 CC = DAG.getConstant(CCode, dl, MVT::i8);
15262 SDNode *User = *Op.getNode()->use_begin();
15263 // Look for an unconditional branch following this conditional branch.
15264 // We need this because we need to reverse the successors in order
15265 // to implement FCMP_OEQ.
15266 if (User->getOpcode() == ISD::BR) {
15267 SDValue FalseBB = User->getOperand(1);
15269 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15270 assert(NewBR == User);
15274 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15275 Chain, Dest, CC, Cmp);
15276 X86::CondCode CCode =
15277 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15278 CCode = X86::GetOppositeBranchCondition(CCode);
15279 CC = DAG.getConstant(CCode, dl, MVT::i8);
15285 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15286 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15287 // It should be transformed during dag combiner except when the condition
15288 // is set by a arithmetics with overflow node.
15289 X86::CondCode CCode =
15290 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15291 CCode = X86::GetOppositeBranchCondition(CCode);
15292 CC = DAG.getConstant(CCode, dl, MVT::i8);
15293 Cond = Cond.getOperand(0).getOperand(1);
15295 } else if (Cond.getOpcode() == ISD::SETCC &&
15296 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15297 // For FCMP_OEQ, we can emit
15298 // two branches instead of an explicit AND instruction with a
15299 // separate test. However, we only do this if this block doesn't
15300 // have a fall-through edge, because this requires an explicit
15301 // jmp when the condition is false.
15302 if (Op.getNode()->hasOneUse()) {
15303 SDNode *User = *Op.getNode()->use_begin();
15304 // Look for an unconditional branch following this conditional branch.
15305 // We need this because we need to reverse the successors in order
15306 // to implement FCMP_OEQ.
15307 if (User->getOpcode() == ISD::BR) {
15308 SDValue FalseBB = User->getOperand(1);
15310 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15311 assert(NewBR == User);
15315 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15316 Cond.getOperand(0), Cond.getOperand(1));
15317 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15318 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15319 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15320 Chain, Dest, CC, Cmp);
15321 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15326 } else if (Cond.getOpcode() == ISD::SETCC &&
15327 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15328 // For FCMP_UNE, we can emit
15329 // two branches instead of an explicit AND instruction with a
15330 // separate test. However, we only do this if this block doesn't
15331 // have a fall-through edge, because this requires an explicit
15332 // jmp when the condition is false.
15333 if (Op.getNode()->hasOneUse()) {
15334 SDNode *User = *Op.getNode()->use_begin();
15335 // Look for an unconditional branch following this conditional branch.
15336 // We need this because we need to reverse the successors in order
15337 // to implement FCMP_UNE.
15338 if (User->getOpcode() == ISD::BR) {
15339 SDValue FalseBB = User->getOperand(1);
15341 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15342 assert(NewBR == User);
15345 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15346 Cond.getOperand(0), Cond.getOperand(1));
15347 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15348 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15349 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15350 Chain, Dest, CC, Cmp);
15351 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15361 // Look pass the truncate if the high bits are known zero.
15362 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15363 Cond = Cond.getOperand(0);
15365 // We know the result of AND is compared against zero. Try to match
15367 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15368 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15369 if (NewSetCC.getNode()) {
15370 CC = NewSetCC.getOperand(0);
15371 Cond = NewSetCC.getOperand(1);
15378 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15379 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15380 Cond = EmitTest(Cond, X86Cond, dl, DAG);
15382 Cond = ConvertCmpIfNecessary(Cond, DAG);
15383 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15384 Chain, Dest, CC, Cond);
15387 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15388 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15389 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15390 // that the guard pages used by the OS virtual memory manager are allocated in
15391 // correct sequence.
15393 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15394 SelectionDAG &DAG) const {
15395 MachineFunction &MF = DAG.getMachineFunction();
15396 bool SplitStack = MF.shouldSplitStack();
15397 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15402 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15403 SDNode* Node = Op.getNode();
15405 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15406 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15407 " not tell us which reg is the stack pointer!");
15408 EVT VT = Node->getValueType(0);
15409 SDValue Tmp1 = SDValue(Node, 0);
15410 SDValue Tmp2 = SDValue(Node, 1);
15411 SDValue Tmp3 = Node->getOperand(2);
15412 SDValue Chain = Tmp1.getOperand(0);
15414 // Chain the dynamic stack allocation so that it doesn't modify the stack
15415 // pointer when other instructions are using the stack.
15416 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15419 SDValue Size = Tmp2.getOperand(1);
15420 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15421 Chain = SP.getValue(1);
15422 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15423 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15424 unsigned StackAlign = TFI.getStackAlignment();
15425 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15426 if (Align > StackAlign)
15427 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15428 DAG.getConstant(-(uint64_t)Align, dl, VT));
15429 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15431 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15432 DAG.getIntPtrConstant(0, dl, true), SDValue(),
15435 SDValue Ops[2] = { Tmp1, Tmp2 };
15436 return DAG.getMergeValues(Ops, dl);
15440 SDValue Chain = Op.getOperand(0);
15441 SDValue Size = Op.getOperand(1);
15442 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15443 EVT VT = Op.getNode()->getValueType(0);
15445 bool Is64Bit = Subtarget->is64Bit();
15446 MVT SPTy = getPointerTy(DAG.getDataLayout());
15449 MachineRegisterInfo &MRI = MF.getRegInfo();
15452 // The 64 bit implementation of segmented stacks needs to clobber both r10
15453 // r11. This makes it impossible to use it along with nested parameters.
15454 const Function *F = MF.getFunction();
15456 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15458 if (I->hasNestAttr())
15459 report_fatal_error("Cannot use segmented stacks with functions that "
15460 "have nested arguments.");
15463 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15464 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15465 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15466 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15467 DAG.getRegister(Vreg, SPTy));
15468 SDValue Ops1[2] = { Value, Chain };
15469 return DAG.getMergeValues(Ops1, dl);
15472 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15474 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15475 Flag = Chain.getValue(1);
15476 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15478 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15480 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15481 unsigned SPReg = RegInfo->getStackRegister();
15482 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15483 Chain = SP.getValue(1);
15486 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15487 DAG.getConstant(-(uint64_t)Align, dl, VT));
15488 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15491 SDValue Ops1[2] = { SP, Chain };
15492 return DAG.getMergeValues(Ops1, dl);
15496 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15497 MachineFunction &MF = DAG.getMachineFunction();
15498 auto PtrVT = getPointerTy(MF.getDataLayout());
15499 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15501 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15504 if (!Subtarget->is64Bit() ||
15505 Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15506 // vastart just stores the address of the VarArgsFrameIndex slot into the
15507 // memory location argument.
15508 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15509 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15510 MachinePointerInfo(SV), false, false, 0);
15514 // gp_offset (0 - 6 * 8)
15515 // fp_offset (48 - 48 + 8 * 16)
15516 // overflow_arg_area (point to parameters coming in memory).
15518 SmallVector<SDValue, 8> MemOps;
15519 SDValue FIN = Op.getOperand(1);
15521 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15522 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15524 FIN, MachinePointerInfo(SV), false, false, 0);
15525 MemOps.push_back(Store);
15528 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15529 Store = DAG.getStore(Op.getOperand(0), DL,
15530 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15532 FIN, MachinePointerInfo(SV, 4), false, false, 0);
15533 MemOps.push_back(Store);
15535 // Store ptr to overflow_arg_area
15536 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15537 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15538 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15539 MachinePointerInfo(SV, 8),
15541 MemOps.push_back(Store);
15543 // Store ptr to reg_save_area.
15544 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15545 Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15546 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15547 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15548 SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15549 MemOps.push_back(Store);
15550 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15553 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15554 assert(Subtarget->is64Bit() &&
15555 "LowerVAARG only handles 64-bit va_arg!");
15556 assert(Op.getNode()->getNumOperands() == 4);
15558 MachineFunction &MF = DAG.getMachineFunction();
15559 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15560 // The Win64 ABI uses char* instead of a structure.
15561 return DAG.expandVAArg(Op.getNode());
15563 SDValue Chain = Op.getOperand(0);
15564 SDValue SrcPtr = Op.getOperand(1);
15565 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15566 unsigned Align = Op.getConstantOperandVal(3);
15569 EVT ArgVT = Op.getNode()->getValueType(0);
15570 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15571 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15574 // Decide which area this value should be read from.
15575 // TODO: Implement the AMD64 ABI in its entirety. This simple
15576 // selection mechanism works only for the basic types.
15577 if (ArgVT == MVT::f80) {
15578 llvm_unreachable("va_arg for f80 not yet implemented");
15579 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15580 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
15581 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15582 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
15584 llvm_unreachable("Unhandled argument type in LowerVAARG");
15587 if (ArgMode == 2) {
15588 // Sanity Check: Make sure using fp_offset makes sense.
15589 assert(!Subtarget->useSoftFloat() &&
15590 !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15591 Subtarget->hasSSE1());
15594 // Insert VAARG_64 node into the DAG
15595 // VAARG_64 returns two values: Variable Argument Address, Chain
15596 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15597 DAG.getConstant(ArgMode, dl, MVT::i8),
15598 DAG.getConstant(Align, dl, MVT::i32)};
15599 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15600 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15601 VTs, InstOps, MVT::i64,
15602 MachinePointerInfo(SV),
15604 /*Volatile=*/false,
15606 /*WriteMem=*/true);
15607 Chain = VAARG.getValue(1);
15609 // Load the next argument and return it
15610 return DAG.getLoad(ArgVT, dl,
15613 MachinePointerInfo(),
15614 false, false, false, 0);
15617 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15618 SelectionDAG &DAG) {
15619 // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15620 // where a va_list is still an i8*.
15621 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15622 if (Subtarget->isCallingConvWin64(
15623 DAG.getMachineFunction().getFunction()->getCallingConv()))
15624 // Probably a Win64 va_copy.
15625 return DAG.expandVACopy(Op.getNode());
15627 SDValue Chain = Op.getOperand(0);
15628 SDValue DstPtr = Op.getOperand(1);
15629 SDValue SrcPtr = Op.getOperand(2);
15630 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15631 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15634 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15635 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15637 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15640 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15641 // amount is a constant. Takes immediate version of shift as input.
15642 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15643 SDValue SrcOp, uint64_t ShiftAmt,
15644 SelectionDAG &DAG) {
15645 MVT ElementType = VT.getVectorElementType();
15647 // Fold this packed shift into its first operand if ShiftAmt is 0.
15651 // Check for ShiftAmt >= element width
15652 if (ShiftAmt >= ElementType.getSizeInBits()) {
15653 if (Opc == X86ISD::VSRAI)
15654 ShiftAmt = ElementType.getSizeInBits() - 1;
15656 return DAG.getConstant(0, dl, VT);
15659 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15660 && "Unknown target vector shift-by-constant node");
15662 // Fold this packed vector shift into a build vector if SrcOp is a
15663 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15664 if (VT == SrcOp.getSimpleValueType() &&
15665 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15666 SmallVector<SDValue, 8> Elts;
15667 unsigned NumElts = SrcOp->getNumOperands();
15668 ConstantSDNode *ND;
15671 default: llvm_unreachable(nullptr);
15672 case X86ISD::VSHLI:
15673 for (unsigned i=0; i!=NumElts; ++i) {
15674 SDValue CurrentOp = SrcOp->getOperand(i);
15675 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15676 Elts.push_back(CurrentOp);
15679 ND = cast<ConstantSDNode>(CurrentOp);
15680 const APInt &C = ND->getAPIntValue();
15681 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15684 case X86ISD::VSRLI:
15685 for (unsigned i=0; i!=NumElts; ++i) {
15686 SDValue CurrentOp = SrcOp->getOperand(i);
15687 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15688 Elts.push_back(CurrentOp);
15691 ND = cast<ConstantSDNode>(CurrentOp);
15692 const APInt &C = ND->getAPIntValue();
15693 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15696 case X86ISD::VSRAI:
15697 for (unsigned i=0; i!=NumElts; ++i) {
15698 SDValue CurrentOp = SrcOp->getOperand(i);
15699 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15700 Elts.push_back(CurrentOp);
15703 ND = cast<ConstantSDNode>(CurrentOp);
15704 const APInt &C = ND->getAPIntValue();
15705 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15710 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15713 return DAG.getNode(Opc, dl, VT, SrcOp,
15714 DAG.getConstant(ShiftAmt, dl, MVT::i8));
15717 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15718 // may or may not be a constant. Takes immediate version of shift as input.
15719 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15720 SDValue SrcOp, SDValue ShAmt,
15721 SelectionDAG &DAG) {
15722 MVT SVT = ShAmt.getSimpleValueType();
15723 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15725 // Catch shift-by-constant.
15726 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15727 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15728 CShAmt->getZExtValue(), DAG);
15730 // Change opcode to non-immediate version
15732 default: llvm_unreachable("Unknown target vector shift node");
15733 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15734 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15735 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15738 const X86Subtarget &Subtarget =
15739 static_cast<const X86Subtarget &>(DAG.getSubtarget());
15740 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15741 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15742 // Let the shuffle legalizer expand this shift amount node.
15743 SDValue Op0 = ShAmt.getOperand(0);
15744 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15745 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15747 // Need to build a vector containing shift amount.
15748 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15749 SmallVector<SDValue, 4> ShOps;
15750 ShOps.push_back(ShAmt);
15751 if (SVT == MVT::i32) {
15752 ShOps.push_back(DAG.getConstant(0, dl, SVT));
15753 ShOps.push_back(DAG.getUNDEF(SVT));
15755 ShOps.push_back(DAG.getUNDEF(SVT));
15757 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15758 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15761 // The return type has to be a 128-bit type with the same element
15762 // type as the input type.
15763 MVT EltVT = VT.getVectorElementType();
15764 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15766 ShAmt = DAG.getBitcast(ShVT, ShAmt);
15767 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15770 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15771 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15772 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15773 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15774 SDValue PreservedSrc,
15775 const X86Subtarget *Subtarget,
15776 SelectionDAG &DAG) {
15777 EVT VT = Op.getValueType();
15778 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15779 MVT::i1, VT.getVectorNumElements());
15780 SDValue VMask = SDValue();
15781 unsigned OpcodeSelect = ISD::VSELECT;
15784 assert(MaskVT.isSimple() && "invalid mask type");
15786 if (isAllOnes(Mask))
15789 if (MaskVT.bitsGT(Mask.getValueType())) {
15790 EVT newMaskVT = EVT::getIntegerVT(*DAG.getContext(),
15791 MaskVT.getSizeInBits());
15792 VMask = DAG.getBitcast(MaskVT,
15793 DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15795 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15796 Mask.getValueType().getSizeInBits());
15797 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15798 // are extracted by EXTRACT_SUBVECTOR.
15799 VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15800 DAG.getBitcast(BitcastVT, Mask),
15801 DAG.getIntPtrConstant(0, dl));
15804 switch (Op.getOpcode()) {
15806 case X86ISD::PCMPEQM:
15807 case X86ISD::PCMPGTM:
15809 case X86ISD::CMPMU:
15810 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15811 case X86ISD::VFPCLASS:
15812 return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
15813 case X86ISD::VTRUNC:
15814 case X86ISD::VTRUNCS:
15815 case X86ISD::VTRUNCUS:
15816 // We can't use ISD::VSELECT here because it is not always "Legal"
15817 // for the destination type. For example vpmovqb require only AVX512
15818 // and vselect that can operate on byte element type require BWI
15819 OpcodeSelect = X86ISD::SELECT;
15822 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15823 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15824 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15827 /// \brief Creates an SDNode for a predicated scalar operation.
15828 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15829 /// The mask is coming as MVT::i8 and it should be truncated
15830 /// to MVT::i1 while lowering masking intrinsics.
15831 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15832 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15833 /// for a scalar instruction.
15834 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15835 SDValue PreservedSrc,
15836 const X86Subtarget *Subtarget,
15837 SelectionDAG &DAG) {
15838 if (isAllOnes(Mask))
15841 EVT VT = Op.getValueType();
15843 // The mask should be of type MVT::i1
15844 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15846 if (Op.getOpcode() == X86ISD::FSETCC)
15847 return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
15849 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15850 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15851 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15854 static int getSEHRegistrationNodeSize(const Function *Fn) {
15855 if (!Fn->hasPersonalityFn())
15856 report_fatal_error(
15857 "querying registration node size for function without personality");
15858 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15859 // WinEHStatePass for the full struct definition.
15860 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15861 case EHPersonality::MSVC_X86SEH: return 24;
15862 case EHPersonality::MSVC_CXX: return 16;
15865 report_fatal_error("can only recover FP for MSVC EH personality functions");
15868 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15869 /// function or when returning to a parent frame after catching an exception, we
15870 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15871 /// Here's the math:
15872 /// RegNodeBase = EntryEBP - RegNodeSize
15873 /// ParentFP = RegNodeBase - RegNodeFrameOffset
15874 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15875 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15876 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15877 SDValue EntryEBP) {
15878 MachineFunction &MF = DAG.getMachineFunction();
15881 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15882 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15884 // It's possible that the parent function no longer has a personality function
15885 // if the exceptional code was optimized away, in which case we just return
15886 // the incoming EBP.
15887 if (!Fn->hasPersonalityFn())
15890 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15892 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15894 MCSymbol *OffsetSym =
15895 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15896 GlobalValue::getRealLinkageName(Fn->getName()));
15897 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15898 SDValue RegNodeFrameOffset =
15899 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15901 // RegNodeBase = EntryEBP - RegNodeSize
15902 // ParentFP = RegNodeBase - RegNodeFrameOffset
15903 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15904 DAG.getConstant(RegNodeSize, dl, PtrVT));
15905 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15908 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15909 SelectionDAG &DAG) {
15911 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15912 EVT VT = Op.getValueType();
15913 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15915 switch(IntrData->Type) {
15916 case INTR_TYPE_1OP:
15917 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15918 case INTR_TYPE_2OP:
15919 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15921 case INTR_TYPE_2OP_IMM8:
15922 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15923 DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
15924 case INTR_TYPE_3OP:
15925 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15926 Op.getOperand(2), Op.getOperand(3));
15927 case INTR_TYPE_4OP:
15928 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15929 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15930 case INTR_TYPE_1OP_MASK_RM: {
15931 SDValue Src = Op.getOperand(1);
15932 SDValue PassThru = Op.getOperand(2);
15933 SDValue Mask = Op.getOperand(3);
15934 SDValue RoundingMode;
15935 // We allways add rounding mode to the Node.
15936 // If the rounding mode is not specified, we add the
15937 // "current direction" mode.
15938 if (Op.getNumOperands() == 4)
15940 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15942 RoundingMode = Op.getOperand(4);
15943 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15944 if (IntrWithRoundingModeOpcode != 0)
15945 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15946 X86::STATIC_ROUNDING::CUR_DIRECTION)
15947 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15948 dl, Op.getValueType(), Src, RoundingMode),
15949 Mask, PassThru, Subtarget, DAG);
15950 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15952 Mask, PassThru, Subtarget, DAG);
15954 case INTR_TYPE_1OP_MASK: {
15955 SDValue Src = Op.getOperand(1);
15956 SDValue PassThru = Op.getOperand(2);
15957 SDValue Mask = Op.getOperand(3);
15958 // We add rounding mode to the Node when
15959 // - RM Opcode is specified and
15960 // - RM is not "current direction".
15961 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15962 if (IntrWithRoundingModeOpcode != 0) {
15963 SDValue Rnd = Op.getOperand(4);
15964 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15965 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15966 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15967 dl, Op.getValueType(),
15969 Mask, PassThru, Subtarget, DAG);
15972 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15973 Mask, PassThru, Subtarget, DAG);
15975 case INTR_TYPE_SCALAR_MASK: {
15976 SDValue Src1 = Op.getOperand(1);
15977 SDValue Src2 = Op.getOperand(2);
15978 SDValue passThru = Op.getOperand(3);
15979 SDValue Mask = Op.getOperand(4);
15980 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
15981 Mask, passThru, Subtarget, DAG);
15983 case INTR_TYPE_SCALAR_MASK_RM: {
15984 SDValue Src1 = Op.getOperand(1);
15985 SDValue Src2 = Op.getOperand(2);
15986 SDValue Src0 = Op.getOperand(3);
15987 SDValue Mask = Op.getOperand(4);
15988 // There are 2 kinds of intrinsics in this group:
15989 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15990 // (2) With rounding mode and sae - 7 operands.
15991 if (Op.getNumOperands() == 6) {
15992 SDValue Sae = Op.getOperand(5);
15993 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15994 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15996 Mask, Src0, Subtarget, DAG);
15998 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15999 SDValue RoundingMode = Op.getOperand(5);
16000 SDValue Sae = Op.getOperand(6);
16001 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16002 RoundingMode, Sae),
16003 Mask, Src0, Subtarget, DAG);
16005 case INTR_TYPE_2OP_MASK: {
16006 SDValue Src1 = Op.getOperand(1);
16007 SDValue Src2 = Op.getOperand(2);
16008 SDValue PassThru = Op.getOperand(3);
16009 SDValue Mask = Op.getOperand(4);
16010 // We specify 2 possible opcodes for intrinsics with rounding modes.
16011 // First, we check if the intrinsic may have non-default rounding mode,
16012 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16013 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16014 if (IntrWithRoundingModeOpcode != 0) {
16015 SDValue Rnd = Op.getOperand(5);
16016 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16017 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16018 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16019 dl, Op.getValueType(),
16021 Mask, PassThru, Subtarget, DAG);
16024 // TODO: Intrinsics should have fast-math-flags to propagate.
16025 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16026 Mask, PassThru, Subtarget, DAG);
16028 case INTR_TYPE_2OP_MASK_RM: {
16029 SDValue Src1 = Op.getOperand(1);
16030 SDValue Src2 = Op.getOperand(2);
16031 SDValue PassThru = Op.getOperand(3);
16032 SDValue Mask = Op.getOperand(4);
16033 // We specify 2 possible modes for intrinsics, with/without rounding modes.
16034 // First, we check if the intrinsic have rounding mode (6 operands),
16035 // if not, we set rounding mode to "current".
16037 if (Op.getNumOperands() == 6)
16038 Rnd = Op.getOperand(5);
16040 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16041 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16043 Mask, PassThru, Subtarget, DAG);
16045 case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16046 SDValue Src1 = Op.getOperand(1);
16047 SDValue Src2 = Op.getOperand(2);
16048 SDValue Src3 = Op.getOperand(3);
16049 SDValue PassThru = Op.getOperand(4);
16050 SDValue Mask = Op.getOperand(5);
16051 SDValue Sae = Op.getOperand(6);
16053 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16055 Mask, PassThru, Subtarget, DAG);
16057 case INTR_TYPE_3OP_MASK_RM: {
16058 SDValue Src1 = Op.getOperand(1);
16059 SDValue Src2 = Op.getOperand(2);
16060 SDValue Imm = Op.getOperand(3);
16061 SDValue PassThru = Op.getOperand(4);
16062 SDValue Mask = Op.getOperand(5);
16063 // We specify 2 possible modes for intrinsics, with/without rounding modes.
16064 // First, we check if the intrinsic have rounding mode (7 operands),
16065 // if not, we set rounding mode to "current".
16067 if (Op.getNumOperands() == 7)
16068 Rnd = Op.getOperand(6);
16070 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16071 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16072 Src1, Src2, Imm, Rnd),
16073 Mask, PassThru, Subtarget, DAG);
16075 case INTR_TYPE_3OP_IMM8_MASK:
16076 case INTR_TYPE_3OP_MASK:
16077 case INSERT_SUBVEC: {
16078 SDValue Src1 = Op.getOperand(1);
16079 SDValue Src2 = Op.getOperand(2);
16080 SDValue Src3 = Op.getOperand(3);
16081 SDValue PassThru = Op.getOperand(4);
16082 SDValue Mask = Op.getOperand(5);
16084 if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16085 Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16086 else if (IntrData->Type == INSERT_SUBVEC) {
16087 // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16088 assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16089 unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16090 Imm *= Src2.getValueType().getVectorNumElements();
16091 Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16094 // We specify 2 possible opcodes for intrinsics with rounding modes.
16095 // First, we check if the intrinsic may have non-default rounding mode,
16096 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16097 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16098 if (IntrWithRoundingModeOpcode != 0) {
16099 SDValue Rnd = Op.getOperand(6);
16100 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16101 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16102 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16103 dl, Op.getValueType(),
16104 Src1, Src2, Src3, Rnd),
16105 Mask, PassThru, Subtarget, DAG);
16108 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16110 Mask, PassThru, Subtarget, DAG);
16112 case VPERM_3OP_MASKZ:
16113 case VPERM_3OP_MASK:
16116 case FMA_OP_MASK: {
16117 SDValue Src1 = Op.getOperand(1);
16118 SDValue Src2 = Op.getOperand(2);
16119 SDValue Src3 = Op.getOperand(3);
16120 SDValue Mask = Op.getOperand(4);
16121 EVT VT = Op.getValueType();
16122 SDValue PassThru = SDValue();
16124 // set PassThru element
16125 if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
16126 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16127 else if (IntrData->Type == FMA_OP_MASK3)
16132 // We specify 2 possible opcodes for intrinsics with rounding modes.
16133 // First, we check if the intrinsic may have non-default rounding mode,
16134 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16135 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16136 if (IntrWithRoundingModeOpcode != 0) {
16137 SDValue Rnd = Op.getOperand(5);
16138 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16139 X86::STATIC_ROUNDING::CUR_DIRECTION)
16140 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16141 dl, Op.getValueType(),
16142 Src1, Src2, Src3, Rnd),
16143 Mask, PassThru, Subtarget, DAG);
16145 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16146 dl, Op.getValueType(),
16148 Mask, PassThru, Subtarget, DAG);
16151 // FPclass intrinsics with mask
16152 SDValue Src1 = Op.getOperand(1);
16153 EVT VT = Src1.getValueType();
16154 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16155 VT.getVectorNumElements());
16156 SDValue Imm = Op.getOperand(2);
16157 SDValue Mask = Op.getOperand(3);
16158 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16159 Mask.getValueType().getSizeInBits());
16160 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16161 SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16162 DAG.getTargetConstant(0, dl, MaskVT),
16164 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16165 DAG.getUNDEF(BitcastVT), FPclassMask,
16166 DAG.getIntPtrConstant(0, dl));
16167 return DAG.getBitcast(Op.getValueType(), Res);
16170 case CMP_MASK_CC: {
16171 // Comparison intrinsics with masks.
16172 // Example of transformation:
16173 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16174 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16176 // (v8i1 (insert_subvector undef,
16177 // (v2i1 (and (PCMPEQM %a, %b),
16178 // (extract_subvector
16179 // (v8i1 (bitcast %mask)), 0))), 0))))
16180 EVT VT = Op.getOperand(1).getValueType();
16181 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16182 VT.getVectorNumElements());
16183 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16184 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16185 Mask.getValueType().getSizeInBits());
16187 if (IntrData->Type == CMP_MASK_CC) {
16188 SDValue CC = Op.getOperand(3);
16189 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16190 // We specify 2 possible opcodes for intrinsics with rounding modes.
16191 // First, we check if the intrinsic may have non-default rounding mode,
16192 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16193 if (IntrData->Opc1 != 0) {
16194 SDValue Rnd = Op.getOperand(5);
16195 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16196 X86::STATIC_ROUNDING::CUR_DIRECTION)
16197 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16198 Op.getOperand(2), CC, Rnd);
16200 //default rounding mode
16202 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16203 Op.getOperand(2), CC);
16206 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16207 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16210 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16211 DAG.getTargetConstant(0, dl,
16214 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16215 DAG.getUNDEF(BitcastVT), CmpMask,
16216 DAG.getIntPtrConstant(0, dl));
16217 return DAG.getBitcast(Op.getValueType(), Res);
16219 case CMP_MASK_SCALAR_CC: {
16220 SDValue Src1 = Op.getOperand(1);
16221 SDValue Src2 = Op.getOperand(2);
16222 SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16223 SDValue Mask = Op.getOperand(4);
16226 if (IntrData->Opc1 != 0) {
16227 SDValue Rnd = Op.getOperand(5);
16228 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16229 X86::STATIC_ROUNDING::CUR_DIRECTION)
16230 Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16232 //default rounding mode
16234 Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16236 SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16237 DAG.getTargetConstant(0, dl,
16241 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16242 DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16243 DAG.getValueType(MVT::i1));
16245 case COMI: { // Comparison intrinsics
16246 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16247 SDValue LHS = Op.getOperand(1);
16248 SDValue RHS = Op.getOperand(2);
16249 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16250 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16251 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16252 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16253 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16254 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16257 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16258 Op.getOperand(1), Op.getOperand(2), DAG);
16260 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16261 Op.getSimpleValueType(),
16263 Op.getOperand(2), DAG),
16264 Op.getOperand(4), Op.getOperand(3), Subtarget,
16266 case COMPRESS_EXPAND_IN_REG: {
16267 SDValue Mask = Op.getOperand(3);
16268 SDValue DataToCompress = Op.getOperand(1);
16269 SDValue PassThru = Op.getOperand(2);
16270 if (isAllOnes(Mask)) // return data as is
16271 return Op.getOperand(1);
16273 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16275 Mask, PassThru, Subtarget, DAG);
16278 SDValue Mask = Op.getOperand(3);
16279 EVT VT = Op.getValueType();
16280 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16281 VT.getVectorNumElements());
16282 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16283 Mask.getValueType().getSizeInBits());
16285 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16286 DAG.getBitcast(BitcastVT, Mask),
16287 DAG.getIntPtrConstant(0, dl));
16288 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16297 default: return SDValue(); // Don't custom lower most intrinsics.
16299 case Intrinsic::x86_avx2_permd:
16300 case Intrinsic::x86_avx2_permps:
16301 // Operands intentionally swapped. Mask is last operand to intrinsic,
16302 // but second operand for node/instruction.
16303 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16304 Op.getOperand(2), Op.getOperand(1));
16306 // ptest and testp intrinsics. The intrinsic these come from are designed to
16307 // return an integer value, not just an instruction so lower it to the ptest
16308 // or testp pattern and a setcc for the result.
16309 case Intrinsic::x86_sse41_ptestz:
16310 case Intrinsic::x86_sse41_ptestc:
16311 case Intrinsic::x86_sse41_ptestnzc:
16312 case Intrinsic::x86_avx_ptestz_256:
16313 case Intrinsic::x86_avx_ptestc_256:
16314 case Intrinsic::x86_avx_ptestnzc_256:
16315 case Intrinsic::x86_avx_vtestz_ps:
16316 case Intrinsic::x86_avx_vtestc_ps:
16317 case Intrinsic::x86_avx_vtestnzc_ps:
16318 case Intrinsic::x86_avx_vtestz_pd:
16319 case Intrinsic::x86_avx_vtestc_pd:
16320 case Intrinsic::x86_avx_vtestnzc_pd:
16321 case Intrinsic::x86_avx_vtestz_ps_256:
16322 case Intrinsic::x86_avx_vtestc_ps_256:
16323 case Intrinsic::x86_avx_vtestnzc_ps_256:
16324 case Intrinsic::x86_avx_vtestz_pd_256:
16325 case Intrinsic::x86_avx_vtestc_pd_256:
16326 case Intrinsic::x86_avx_vtestnzc_pd_256: {
16327 bool IsTestPacked = false;
16330 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16331 case Intrinsic::x86_avx_vtestz_ps:
16332 case Intrinsic::x86_avx_vtestz_pd:
16333 case Intrinsic::x86_avx_vtestz_ps_256:
16334 case Intrinsic::x86_avx_vtestz_pd_256:
16335 IsTestPacked = true; // Fallthrough
16336 case Intrinsic::x86_sse41_ptestz:
16337 case Intrinsic::x86_avx_ptestz_256:
16339 X86CC = X86::COND_E;
16341 case Intrinsic::x86_avx_vtestc_ps:
16342 case Intrinsic::x86_avx_vtestc_pd:
16343 case Intrinsic::x86_avx_vtestc_ps_256:
16344 case Intrinsic::x86_avx_vtestc_pd_256:
16345 IsTestPacked = true; // Fallthrough
16346 case Intrinsic::x86_sse41_ptestc:
16347 case Intrinsic::x86_avx_ptestc_256:
16349 X86CC = X86::COND_B;
16351 case Intrinsic::x86_avx_vtestnzc_ps:
16352 case Intrinsic::x86_avx_vtestnzc_pd:
16353 case Intrinsic::x86_avx_vtestnzc_ps_256:
16354 case Intrinsic::x86_avx_vtestnzc_pd_256:
16355 IsTestPacked = true; // Fallthrough
16356 case Intrinsic::x86_sse41_ptestnzc:
16357 case Intrinsic::x86_avx_ptestnzc_256:
16359 X86CC = X86::COND_A;
16363 SDValue LHS = Op.getOperand(1);
16364 SDValue RHS = Op.getOperand(2);
16365 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16366 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16367 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16368 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16369 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16371 case Intrinsic::x86_avx512_kortestz_w:
16372 case Intrinsic::x86_avx512_kortestc_w: {
16373 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16374 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16375 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16376 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16377 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16378 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16379 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16382 case Intrinsic::x86_sse42_pcmpistria128:
16383 case Intrinsic::x86_sse42_pcmpestria128:
16384 case Intrinsic::x86_sse42_pcmpistric128:
16385 case Intrinsic::x86_sse42_pcmpestric128:
16386 case Intrinsic::x86_sse42_pcmpistrio128:
16387 case Intrinsic::x86_sse42_pcmpestrio128:
16388 case Intrinsic::x86_sse42_pcmpistris128:
16389 case Intrinsic::x86_sse42_pcmpestris128:
16390 case Intrinsic::x86_sse42_pcmpistriz128:
16391 case Intrinsic::x86_sse42_pcmpestriz128: {
16395 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16396 case Intrinsic::x86_sse42_pcmpistria128:
16397 Opcode = X86ISD::PCMPISTRI;
16398 X86CC = X86::COND_A;
16400 case Intrinsic::x86_sse42_pcmpestria128:
16401 Opcode = X86ISD::PCMPESTRI;
16402 X86CC = X86::COND_A;
16404 case Intrinsic::x86_sse42_pcmpistric128:
16405 Opcode = X86ISD::PCMPISTRI;
16406 X86CC = X86::COND_B;
16408 case Intrinsic::x86_sse42_pcmpestric128:
16409 Opcode = X86ISD::PCMPESTRI;
16410 X86CC = X86::COND_B;
16412 case Intrinsic::x86_sse42_pcmpistrio128:
16413 Opcode = X86ISD::PCMPISTRI;
16414 X86CC = X86::COND_O;
16416 case Intrinsic::x86_sse42_pcmpestrio128:
16417 Opcode = X86ISD::PCMPESTRI;
16418 X86CC = X86::COND_O;
16420 case Intrinsic::x86_sse42_pcmpistris128:
16421 Opcode = X86ISD::PCMPISTRI;
16422 X86CC = X86::COND_S;
16424 case Intrinsic::x86_sse42_pcmpestris128:
16425 Opcode = X86ISD::PCMPESTRI;
16426 X86CC = X86::COND_S;
16428 case Intrinsic::x86_sse42_pcmpistriz128:
16429 Opcode = X86ISD::PCMPISTRI;
16430 X86CC = X86::COND_E;
16432 case Intrinsic::x86_sse42_pcmpestriz128:
16433 Opcode = X86ISD::PCMPESTRI;
16434 X86CC = X86::COND_E;
16437 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16438 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16439 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16440 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16441 DAG.getConstant(X86CC, dl, MVT::i8),
16442 SDValue(PCMP.getNode(), 1));
16443 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16446 case Intrinsic::x86_sse42_pcmpistri128:
16447 case Intrinsic::x86_sse42_pcmpestri128: {
16449 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16450 Opcode = X86ISD::PCMPISTRI;
16452 Opcode = X86ISD::PCMPESTRI;
16454 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16455 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16456 return DAG.getNode(Opcode, dl, VTs, NewOps);
16459 case Intrinsic::x86_seh_lsda: {
16460 // Compute the symbol for the LSDA. We know it'll get emitted later.
16461 MachineFunction &MF = DAG.getMachineFunction();
16462 SDValue Op1 = Op.getOperand(1);
16463 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16464 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16465 GlobalValue::getRealLinkageName(Fn->getName()));
16467 // Generate a simple absolute symbol reference. This intrinsic is only
16468 // supported on 32-bit Windows, which isn't PIC.
16469 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16470 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16473 case Intrinsic::x86_seh_recoverfp: {
16474 SDValue FnOp = Op.getOperand(1);
16475 SDValue IncomingFPOp = Op.getOperand(2);
16476 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16477 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16479 report_fatal_error(
16480 "llvm.x86.seh.recoverfp must take a function as the first argument");
16481 return recoverFramePointer(DAG, Fn, IncomingFPOp);
16484 case Intrinsic::localaddress: {
16485 // Returns one of the stack, base, or frame pointer registers, depending on
16486 // which is used to reference local variables.
16487 MachineFunction &MF = DAG.getMachineFunction();
16488 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16490 if (RegInfo->hasBasePointer(MF))
16491 Reg = RegInfo->getBaseRegister();
16492 else // This function handles the SP or FP case.
16493 Reg = RegInfo->getPtrSizedFrameRegister(MF);
16494 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16499 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16500 SDValue Src, SDValue Mask, SDValue Base,
16501 SDValue Index, SDValue ScaleOp, SDValue Chain,
16502 const X86Subtarget * Subtarget) {
16504 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16506 llvm_unreachable("Invalid scale type");
16507 unsigned ScaleVal = C->getZExtValue();
16508 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16509 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16511 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16512 EVT MaskVT = MVT::getVectorVT(MVT::i1,
16513 Index.getSimpleValueType().getVectorNumElements());
16515 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16517 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16519 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16520 Mask.getValueType().getSizeInBits());
16522 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16523 // are extracted by EXTRACT_SUBVECTOR.
16524 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16525 DAG.getBitcast(BitcastVT, Mask),
16526 DAG.getIntPtrConstant(0, dl));
16528 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16529 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16530 SDValue Segment = DAG.getRegister(0, MVT::i32);
16531 if (Src.getOpcode() == ISD::UNDEF)
16532 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16533 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16534 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16535 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16536 return DAG.getMergeValues(RetOps, dl);
16539 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16540 SDValue Src, SDValue Mask, SDValue Base,
16541 SDValue Index, SDValue ScaleOp, SDValue Chain) {
16543 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16545 llvm_unreachable("Invalid scale type");
16546 unsigned ScaleVal = C->getZExtValue();
16547 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16548 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16550 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16551 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16552 SDValue Segment = DAG.getRegister(0, MVT::i32);
16553 EVT MaskVT = MVT::getVectorVT(MVT::i1,
16554 Index.getSimpleValueType().getVectorNumElements());
16556 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16558 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16560 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16561 Mask.getValueType().getSizeInBits());
16563 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16564 // are extracted by EXTRACT_SUBVECTOR.
16565 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16566 DAG.getBitcast(BitcastVT, Mask),
16567 DAG.getIntPtrConstant(0, dl));
16569 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16570 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16571 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16572 return SDValue(Res, 1);
16575 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16576 SDValue Mask, SDValue Base, SDValue Index,
16577 SDValue ScaleOp, SDValue Chain) {
16579 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16580 assert(C && "Invalid scale type");
16581 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16582 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16583 SDValue Segment = DAG.getRegister(0, MVT::i32);
16585 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16587 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16589 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16591 MaskInReg = DAG.getBitcast(MaskVT, Mask);
16592 //SDVTList VTs = DAG.getVTList(MVT::Other);
16593 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16594 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16595 return SDValue(Res, 0);
16598 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16599 // read performance monitor counters (x86_rdpmc).
16600 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16601 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16602 SmallVectorImpl<SDValue> &Results) {
16603 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16604 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16607 // The ECX register is used to select the index of the performance counter
16609 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16611 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16613 // Reads the content of a 64-bit performance counter and returns it in the
16614 // registers EDX:EAX.
16615 if (Subtarget->is64Bit()) {
16616 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16617 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16620 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16621 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16624 Chain = HI.getValue(1);
16626 if (Subtarget->is64Bit()) {
16627 // The EAX register is loaded with the low-order 32 bits. The EDX register
16628 // is loaded with the supported high-order bits of the counter.
16629 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16630 DAG.getConstant(32, DL, MVT::i8));
16631 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16632 Results.push_back(Chain);
16636 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16637 SDValue Ops[] = { LO, HI };
16638 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16639 Results.push_back(Pair);
16640 Results.push_back(Chain);
16643 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16644 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16645 // also used to custom lower READCYCLECOUNTER nodes.
16646 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16647 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16648 SmallVectorImpl<SDValue> &Results) {
16649 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16650 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16653 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16654 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16655 // and the EAX register is loaded with the low-order 32 bits.
16656 if (Subtarget->is64Bit()) {
16657 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16658 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16661 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16662 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16665 SDValue Chain = HI.getValue(1);
16667 if (Opcode == X86ISD::RDTSCP_DAG) {
16668 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16670 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16671 // the ECX register. Add 'ecx' explicitly to the chain.
16672 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16674 // Explicitly store the content of ECX at the location passed in input
16675 // to the 'rdtscp' intrinsic.
16676 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16677 MachinePointerInfo(), false, false, 0);
16680 if (Subtarget->is64Bit()) {
16681 // The EDX register is loaded with the high-order 32 bits of the MSR, and
16682 // the EAX register is loaded with the low-order 32 bits.
16683 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16684 DAG.getConstant(32, DL, MVT::i8));
16685 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16686 Results.push_back(Chain);
16690 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16691 SDValue Ops[] = { LO, HI };
16692 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16693 Results.push_back(Pair);
16694 Results.push_back(Chain);
16697 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16698 SelectionDAG &DAG) {
16699 SmallVector<SDValue, 2> Results;
16701 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16703 return DAG.getMergeValues(Results, DL);
16706 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16707 SelectionDAG &DAG) {
16708 MachineFunction &MF = DAG.getMachineFunction();
16709 const Function *Fn = MF.getFunction();
16711 SDValue Chain = Op.getOperand(0);
16713 assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16714 "using llvm.x86.seh.restoreframe requires a frame pointer");
16716 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16717 MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16719 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16720 unsigned FrameReg =
16721 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16722 unsigned SPReg = RegInfo->getStackRegister();
16723 unsigned SlotSize = RegInfo->getSlotSize();
16725 // Get incoming EBP.
16726 SDValue IncomingEBP =
16727 DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16729 // SP is saved in the first field of every registration node, so load
16730 // [EBP-RegNodeSize] into SP.
16731 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16732 SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16733 DAG.getConstant(-RegNodeSize, dl, VT));
16735 DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16736 false, VT.getScalarSizeInBits() / 8);
16737 Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16739 if (!RegInfo->needsStackRealignment(MF)) {
16740 // Adjust EBP to point back to the original frame position.
16741 SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16742 Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16744 assert(RegInfo->hasBasePointer(MF) &&
16745 "functions with Win32 EH must use frame or base pointer register");
16747 // Reload the base pointer (ESI) with the adjusted incoming EBP.
16748 SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16749 Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16751 // Reload the spilled EBP value, now that the stack and base pointers are
16753 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16754 X86FI->setHasSEHFramePtrSave(true);
16755 int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16756 X86FI->setSEHFramePtrSaveIndex(FI);
16757 SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16758 MachinePointerInfo(), false, false, false,
16759 VT.getScalarSizeInBits() / 8);
16760 Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16766 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16767 /// return truncate Store/MaskedStore Node
16768 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16772 SDValue Mask = Op.getOperand(4);
16773 SDValue DataToTruncate = Op.getOperand(3);
16774 SDValue Addr = Op.getOperand(2);
16775 SDValue Chain = Op.getOperand(0);
16777 EVT VT = DataToTruncate.getValueType();
16778 EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16779 ElementType, VT.getVectorNumElements());
16781 if (isAllOnes(Mask)) // return just a truncate store
16782 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16783 MachinePointerInfo(), SVT, false, false,
16784 SVT.getScalarSizeInBits()/8);
16786 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16787 MVT::i1, VT.getVectorNumElements());
16788 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16789 Mask.getValueType().getSizeInBits());
16790 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16791 // are extracted by EXTRACT_SUBVECTOR.
16792 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16793 DAG.getBitcast(BitcastVT, Mask),
16794 DAG.getIntPtrConstant(0, dl));
16796 MachineMemOperand *MMO = DAG.getMachineFunction().
16797 getMachineMemOperand(MachinePointerInfo(),
16798 MachineMemOperand::MOStore, SVT.getStoreSize(),
16799 SVT.getScalarSizeInBits()/8);
16801 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16802 VMask, SVT, MMO, true);
16805 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16806 SelectionDAG &DAG) {
16807 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16809 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16811 if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16812 return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16817 switch(IntrData->Type) {
16819 llvm_unreachable("Unknown Intrinsic Type");
16823 // Emit the node with the right value type.
16824 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16825 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16827 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16828 // Otherwise return the value from Rand, which is always 0, casted to i32.
16829 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16830 DAG.getConstant(1, dl, Op->getValueType(1)),
16831 DAG.getConstant(X86::COND_B, dl, MVT::i32),
16832 SDValue(Result.getNode(), 1) };
16833 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16834 DAG.getVTList(Op->getValueType(1), MVT::Glue),
16837 // Return { result, isValid, chain }.
16838 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16839 SDValue(Result.getNode(), 2));
16842 //gather(v1, mask, index, base, scale);
16843 SDValue Chain = Op.getOperand(0);
16844 SDValue Src = Op.getOperand(2);
16845 SDValue Base = Op.getOperand(3);
16846 SDValue Index = Op.getOperand(4);
16847 SDValue Mask = Op.getOperand(5);
16848 SDValue Scale = Op.getOperand(6);
16849 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16853 //scatter(base, mask, index, v1, scale);
16854 SDValue Chain = Op.getOperand(0);
16855 SDValue Base = Op.getOperand(2);
16856 SDValue Mask = Op.getOperand(3);
16857 SDValue Index = Op.getOperand(4);
16858 SDValue Src = Op.getOperand(5);
16859 SDValue Scale = Op.getOperand(6);
16860 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16864 SDValue Hint = Op.getOperand(6);
16865 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16866 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16867 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16868 SDValue Chain = Op.getOperand(0);
16869 SDValue Mask = Op.getOperand(2);
16870 SDValue Index = Op.getOperand(3);
16871 SDValue Base = Op.getOperand(4);
16872 SDValue Scale = Op.getOperand(5);
16873 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16875 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16877 SmallVector<SDValue, 2> Results;
16878 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16880 return DAG.getMergeValues(Results, dl);
16882 // Read Performance Monitoring Counters.
16884 SmallVector<SDValue, 2> Results;
16885 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16886 return DAG.getMergeValues(Results, dl);
16888 // XTEST intrinsics.
16890 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16891 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16892 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16893 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16895 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16896 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16897 Ret, SDValue(InTrans.getNode(), 1));
16901 SmallVector<SDValue, 2> Results;
16902 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16903 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16904 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16905 DAG.getConstant(-1, dl, MVT::i8));
16906 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16907 Op.getOperand(4), GenCF.getValue(1));
16908 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16909 Op.getOperand(5), MachinePointerInfo(),
16911 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16912 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16914 Results.push_back(SetCC);
16915 Results.push_back(Store);
16916 return DAG.getMergeValues(Results, dl);
16918 case COMPRESS_TO_MEM: {
16920 SDValue Mask = Op.getOperand(4);
16921 SDValue DataToCompress = Op.getOperand(3);
16922 SDValue Addr = Op.getOperand(2);
16923 SDValue Chain = Op.getOperand(0);
16925 EVT VT = DataToCompress.getValueType();
16926 if (isAllOnes(Mask)) // return just a store
16927 return DAG.getStore(Chain, dl, DataToCompress, Addr,
16928 MachinePointerInfo(), false, false,
16929 VT.getScalarSizeInBits()/8);
16931 SDValue Compressed =
16932 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16933 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16934 return DAG.getStore(Chain, dl, Compressed, Addr,
16935 MachinePointerInfo(), false, false,
16936 VT.getScalarSizeInBits()/8);
16938 case TRUNCATE_TO_MEM_VI8:
16939 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16940 case TRUNCATE_TO_MEM_VI16:
16941 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16942 case TRUNCATE_TO_MEM_VI32:
16943 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16944 case EXPAND_FROM_MEM: {
16946 SDValue Mask = Op.getOperand(4);
16947 SDValue PassThru = Op.getOperand(3);
16948 SDValue Addr = Op.getOperand(2);
16949 SDValue Chain = Op.getOperand(0);
16950 EVT VT = Op.getValueType();
16952 if (isAllOnes(Mask)) // return just a load
16953 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16954 false, VT.getScalarSizeInBits()/8);
16956 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16957 false, false, false,
16958 VT.getScalarSizeInBits()/8);
16960 SDValue Results[] = {
16961 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16962 Mask, PassThru, Subtarget, DAG), Chain};
16963 return DAG.getMergeValues(Results, dl);
16968 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16969 SelectionDAG &DAG) const {
16970 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16971 MFI->setReturnAddressIsTaken(true);
16973 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16976 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16978 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16981 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16982 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16983 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16984 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16985 DAG.getNode(ISD::ADD, dl, PtrVT,
16986 FrameAddr, Offset),
16987 MachinePointerInfo(), false, false, false, 0);
16990 // Just load the return address.
16991 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16992 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16993 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16996 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16997 MachineFunction &MF = DAG.getMachineFunction();
16998 MachineFrameInfo *MFI = MF.getFrameInfo();
16999 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17000 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17001 EVT VT = Op.getValueType();
17003 MFI->setFrameAddressIsTaken(true);
17005 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17006 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
17007 // is not possible to crawl up the stack without looking at the unwind codes
17009 int FrameAddrIndex = FuncInfo->getFAIndex();
17010 if (!FrameAddrIndex) {
17011 // Set up a frame object for the return address.
17012 unsigned SlotSize = RegInfo->getSlotSize();
17013 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17014 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17015 FuncInfo->setFAIndex(FrameAddrIndex);
17017 return DAG.getFrameIndex(FrameAddrIndex, VT);
17020 unsigned FrameReg =
17021 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17022 SDLoc dl(Op); // FIXME probably not meaningful
17023 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17024 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17025 (FrameReg == X86::EBP && VT == MVT::i32)) &&
17026 "Invalid Frame Register!");
17027 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17029 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17030 MachinePointerInfo(),
17031 false, false, false, 0);
17035 // FIXME? Maybe this could be a TableGen attribute on some registers and
17036 // this table could be generated automatically from RegInfo.
17037 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17038 SelectionDAG &DAG) const {
17039 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17040 const MachineFunction &MF = DAG.getMachineFunction();
17042 unsigned Reg = StringSwitch<unsigned>(RegName)
17043 .Case("esp", X86::ESP)
17044 .Case("rsp", X86::RSP)
17045 .Case("ebp", X86::EBP)
17046 .Case("rbp", X86::RBP)
17049 if (Reg == X86::EBP || Reg == X86::RBP) {
17050 if (!TFI.hasFP(MF))
17051 report_fatal_error("register " + StringRef(RegName) +
17052 " is allocatable: function has no frame pointer");
17055 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17056 unsigned FrameReg =
17057 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17058 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17059 "Invalid Frame Register!");
17067 report_fatal_error("Invalid register name global variable");
17070 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17071 SelectionDAG &DAG) const {
17072 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17073 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17076 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17077 SDValue Chain = Op.getOperand(0);
17078 SDValue Offset = Op.getOperand(1);
17079 SDValue Handler = Op.getOperand(2);
17082 EVT PtrVT = getPointerTy(DAG.getDataLayout());
17083 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17084 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17085 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17086 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17087 "Invalid Frame Register!");
17088 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17089 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17091 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17092 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17094 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17095 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17097 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17099 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17100 DAG.getRegister(StoreAddrReg, PtrVT));
17103 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17104 SelectionDAG &DAG) const {
17106 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17107 DAG.getVTList(MVT::i32, MVT::Other),
17108 Op.getOperand(0), Op.getOperand(1));
17111 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17112 SelectionDAG &DAG) const {
17114 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17115 Op.getOperand(0), Op.getOperand(1));
17118 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17119 return Op.getOperand(0);
17122 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17123 SelectionDAG &DAG) const {
17124 SDValue Root = Op.getOperand(0);
17125 SDValue Trmp = Op.getOperand(1); // trampoline
17126 SDValue FPtr = Op.getOperand(2); // nested function
17127 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17130 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17131 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17133 if (Subtarget->is64Bit()) {
17134 SDValue OutChains[6];
17136 // Large code-model.
17137 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
17138 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17140 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17141 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17143 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17145 // Load the pointer to the nested function into R11.
17146 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17147 SDValue Addr = Trmp;
17148 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17149 Addr, MachinePointerInfo(TrmpAddr),
17152 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17153 DAG.getConstant(2, dl, MVT::i64));
17154 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17155 MachinePointerInfo(TrmpAddr, 2),
17158 // Load the 'nest' parameter value into R10.
17159 // R10 is specified in X86CallingConv.td
17160 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17161 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17162 DAG.getConstant(10, dl, MVT::i64));
17163 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17164 Addr, MachinePointerInfo(TrmpAddr, 10),
17167 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17168 DAG.getConstant(12, dl, MVT::i64));
17169 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17170 MachinePointerInfo(TrmpAddr, 12),
17173 // Jump to the nested function.
17174 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17175 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17176 DAG.getConstant(20, dl, MVT::i64));
17177 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17178 Addr, MachinePointerInfo(TrmpAddr, 20),
17181 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17182 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17183 DAG.getConstant(22, dl, MVT::i64));
17184 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17185 Addr, MachinePointerInfo(TrmpAddr, 22),
17188 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17190 const Function *Func =
17191 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17192 CallingConv::ID CC = Func->getCallingConv();
17197 llvm_unreachable("Unsupported calling convention");
17198 case CallingConv::C:
17199 case CallingConv::X86_StdCall: {
17200 // Pass 'nest' parameter in ECX.
17201 // Must be kept in sync with X86CallingConv.td
17202 NestReg = X86::ECX;
17204 // Check that ECX wasn't needed by an 'inreg' parameter.
17205 FunctionType *FTy = Func->getFunctionType();
17206 const AttributeSet &Attrs = Func->getAttributes();
17208 if (!Attrs.isEmpty() && !Func->isVarArg()) {
17209 unsigned InRegCount = 0;
17212 for (FunctionType::param_iterator I = FTy->param_begin(),
17213 E = FTy->param_end(); I != E; ++I, ++Idx)
17214 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17215 auto &DL = DAG.getDataLayout();
17216 // FIXME: should only count parameters that are lowered to integers.
17217 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17220 if (InRegCount > 2) {
17221 report_fatal_error("Nest register in use - reduce number of inreg"
17227 case CallingConv::X86_FastCall:
17228 case CallingConv::X86_ThisCall:
17229 case CallingConv::Fast:
17230 // Pass 'nest' parameter in EAX.
17231 // Must be kept in sync with X86CallingConv.td
17232 NestReg = X86::EAX;
17236 SDValue OutChains[4];
17237 SDValue Addr, Disp;
17239 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17240 DAG.getConstant(10, dl, MVT::i32));
17241 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17243 // This is storing the opcode for MOV32ri.
17244 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17245 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17246 OutChains[0] = DAG.getStore(Root, dl,
17247 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17248 Trmp, MachinePointerInfo(TrmpAddr),
17251 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17252 DAG.getConstant(1, dl, MVT::i32));
17253 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17254 MachinePointerInfo(TrmpAddr, 1),
17257 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17258 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17259 DAG.getConstant(5, dl, MVT::i32));
17260 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17261 Addr, MachinePointerInfo(TrmpAddr, 5),
17264 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17265 DAG.getConstant(6, dl, MVT::i32));
17266 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17267 MachinePointerInfo(TrmpAddr, 6),
17270 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17274 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17275 SelectionDAG &DAG) const {
17277 The rounding mode is in bits 11:10 of FPSR, and has the following
17279 00 Round to nearest
17284 FLT_ROUNDS, on the other hand, expects the following:
17291 To perform the conversion, we do:
17292 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17295 MachineFunction &MF = DAG.getMachineFunction();
17296 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17297 unsigned StackAlignment = TFI.getStackAlignment();
17298 MVT VT = Op.getSimpleValueType();
17301 // Save FP Control Word to stack slot
17302 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17303 SDValue StackSlot =
17304 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17306 MachineMemOperand *MMO =
17307 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17308 MachineMemOperand::MOStore, 2, 2);
17310 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17311 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17312 DAG.getVTList(MVT::Other),
17313 Ops, MVT::i16, MMO);
17315 // Load FP Control Word from stack slot
17316 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17317 MachinePointerInfo(), false, false, false, 0);
17319 // Transform as necessary
17321 DAG.getNode(ISD::SRL, DL, MVT::i16,
17322 DAG.getNode(ISD::AND, DL, MVT::i16,
17323 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17324 DAG.getConstant(11, DL, MVT::i8));
17326 DAG.getNode(ISD::SRL, DL, MVT::i16,
17327 DAG.getNode(ISD::AND, DL, MVT::i16,
17328 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17329 DAG.getConstant(9, DL, MVT::i8));
17332 DAG.getNode(ISD::AND, DL, MVT::i16,
17333 DAG.getNode(ISD::ADD, DL, MVT::i16,
17334 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17335 DAG.getConstant(1, DL, MVT::i16)),
17336 DAG.getConstant(3, DL, MVT::i16));
17338 return DAG.getNode((VT.getSizeInBits() < 16 ?
17339 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17342 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17343 MVT VT = Op.getSimpleValueType();
17345 unsigned NumBits = VT.getSizeInBits();
17348 Op = Op.getOperand(0);
17349 if (VT == MVT::i8) {
17350 // Zero extend to i32 since there is not an i8 bsr.
17352 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17355 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17356 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17357 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17359 // If src is zero (i.e. bsr sets ZF), returns NumBits.
17362 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17363 DAG.getConstant(X86::COND_E, dl, MVT::i8),
17366 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17368 // Finally xor with NumBits-1.
17369 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17370 DAG.getConstant(NumBits - 1, dl, OpVT));
17373 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17377 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17378 MVT VT = Op.getSimpleValueType();
17380 unsigned NumBits = VT.getSizeInBits();
17383 Op = Op.getOperand(0);
17384 if (VT == MVT::i8) {
17385 // Zero extend to i32 since there is not an i8 bsr.
17387 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17390 // Issue a bsr (scan bits in reverse).
17391 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17392 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17394 // And xor with NumBits-1.
17395 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17396 DAG.getConstant(NumBits - 1, dl, OpVT));
17399 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17403 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17404 MVT VT = Op.getSimpleValueType();
17405 unsigned NumBits = VT.getScalarSizeInBits();
17408 if (VT.isVector()) {
17409 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17411 SDValue N0 = Op.getOperand(0);
17412 SDValue Zero = DAG.getConstant(0, dl, VT);
17414 // lsb(x) = (x & -x)
17415 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17416 DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17418 // cttz_undef(x) = (width - 1) - ctlz(lsb)
17419 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17420 TLI.isOperationLegal(ISD::CTLZ, VT)) {
17421 SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17422 return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17423 DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17426 // cttz(x) = ctpop(lsb - 1)
17427 SDValue One = DAG.getConstant(1, dl, VT);
17428 return DAG.getNode(ISD::CTPOP, dl, VT,
17429 DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17432 assert(Op.getOpcode() == ISD::CTTZ &&
17433 "Only scalar CTTZ requires custom lowering");
17435 // Issue a bsf (scan bits forward) which also sets EFLAGS.
17436 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17437 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17439 // If src is zero (i.e. bsf sets ZF), returns NumBits.
17442 DAG.getConstant(NumBits, dl, VT),
17443 DAG.getConstant(X86::COND_E, dl, MVT::i8),
17446 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17449 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17450 // ones, and then concatenate the result back.
17451 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17452 MVT VT = Op.getSimpleValueType();
17454 assert(VT.is256BitVector() && VT.isInteger() &&
17455 "Unsupported value type for operation");
17457 unsigned NumElems = VT.getVectorNumElements();
17460 // Extract the LHS vectors
17461 SDValue LHS = Op.getOperand(0);
17462 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17463 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17465 // Extract the RHS vectors
17466 SDValue RHS = Op.getOperand(1);
17467 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17468 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17470 MVT EltVT = VT.getVectorElementType();
17471 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17473 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17474 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17475 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17478 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17479 if (Op.getValueType() == MVT::i1)
17480 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17481 Op.getOperand(0), Op.getOperand(1));
17482 assert(Op.getSimpleValueType().is256BitVector() &&
17483 Op.getSimpleValueType().isInteger() &&
17484 "Only handle AVX 256-bit vector integer operation");
17485 return Lower256IntArith(Op, DAG);
17488 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17489 if (Op.getValueType() == MVT::i1)
17490 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17491 Op.getOperand(0), Op.getOperand(1));
17492 assert(Op.getSimpleValueType().is256BitVector() &&
17493 Op.getSimpleValueType().isInteger() &&
17494 "Only handle AVX 256-bit vector integer operation");
17495 return Lower256IntArith(Op, DAG);
17498 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17499 assert(Op.getSimpleValueType().is256BitVector() &&
17500 Op.getSimpleValueType().isInteger() &&
17501 "Only handle AVX 256-bit vector integer operation");
17502 return Lower256IntArith(Op, DAG);
17505 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17506 SelectionDAG &DAG) {
17508 MVT VT = Op.getSimpleValueType();
17511 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17513 // Decompose 256-bit ops into smaller 128-bit ops.
17514 if (VT.is256BitVector() && !Subtarget->hasInt256())
17515 return Lower256IntArith(Op, DAG);
17517 SDValue A = Op.getOperand(0);
17518 SDValue B = Op.getOperand(1);
17520 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17521 // pairs, multiply and truncate.
17522 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17523 if (Subtarget->hasInt256()) {
17524 if (VT == MVT::v32i8) {
17525 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17526 SDValue Lo = DAG.getIntPtrConstant(0, dl);
17527 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17528 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17529 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17530 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17531 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17532 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17533 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17534 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17537 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17538 return DAG.getNode(
17539 ISD::TRUNCATE, dl, VT,
17540 DAG.getNode(ISD::MUL, dl, ExVT,
17541 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17542 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17545 assert(VT == MVT::v16i8 &&
17546 "Pre-AVX2 support only supports v16i8 multiplication");
17547 MVT ExVT = MVT::v8i16;
17549 // Extract the lo parts and sign extend to i16
17551 if (Subtarget->hasSSE41()) {
17552 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17553 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17555 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17556 -1, 4, -1, 5, -1, 6, -1, 7};
17557 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17558 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17559 ALo = DAG.getBitcast(ExVT, ALo);
17560 BLo = DAG.getBitcast(ExVT, BLo);
17561 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17562 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17565 // Extract the hi parts and sign extend to i16
17567 if (Subtarget->hasSSE41()) {
17568 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
17569 -1, -1, -1, -1, -1, -1, -1, -1};
17570 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17571 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17572 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17573 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17575 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
17576 -1, 12, -1, 13, -1, 14, -1, 15};
17577 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17578 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17579 AHi = DAG.getBitcast(ExVT, AHi);
17580 BHi = DAG.getBitcast(ExVT, BHi);
17581 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17582 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17585 // Multiply, mask the lower 8bits of the lo/hi results and pack
17586 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17587 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17588 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17589 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17590 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17593 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17594 if (VT == MVT::v4i32) {
17595 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17596 "Should not custom lower when pmuldq is available!");
17598 // Extract the odd parts.
17599 static const int UnpackMask[] = { 1, -1, 3, -1 };
17600 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17601 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17603 // Multiply the even parts.
17604 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17605 // Now multiply odd parts.
17606 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17608 Evens = DAG.getBitcast(VT, Evens);
17609 Odds = DAG.getBitcast(VT, Odds);
17611 // Merge the two vectors back together with a shuffle. This expands into 2
17613 static const int ShufMask[] = { 0, 4, 2, 6 };
17614 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17617 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17618 "Only know how to lower V2I64/V4I64/V8I64 multiply");
17620 // Ahi = psrlqi(a, 32);
17621 // Bhi = psrlqi(b, 32);
17623 // AloBlo = pmuludq(a, b);
17624 // AloBhi = pmuludq(a, Bhi);
17625 // AhiBlo = pmuludq(Ahi, b);
17627 // AloBhi = psllqi(AloBhi, 32);
17628 // AhiBlo = psllqi(AhiBlo, 32);
17629 // return AloBlo + AloBhi + AhiBlo;
17631 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17632 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17634 SDValue AhiBlo = Ahi;
17635 SDValue AloBhi = Bhi;
17636 // Bit cast to 32-bit vectors for MULUDQ
17637 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17638 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17639 A = DAG.getBitcast(MulVT, A);
17640 B = DAG.getBitcast(MulVT, B);
17641 Ahi = DAG.getBitcast(MulVT, Ahi);
17642 Bhi = DAG.getBitcast(MulVT, Bhi);
17644 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17645 // After shifting right const values the result may be all-zero.
17646 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17647 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17648 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17650 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17651 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17652 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17655 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17656 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17659 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17660 assert(Subtarget->isTargetWin64() && "Unexpected target");
17661 EVT VT = Op.getValueType();
17662 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17663 "Unexpected return type for lowering");
17667 switch (Op->getOpcode()) {
17668 default: llvm_unreachable("Unexpected request for libcall!");
17669 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
17670 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
17671 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
17672 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
17673 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
17674 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17678 SDValue InChain = DAG.getEntryNode();
17680 TargetLowering::ArgListTy Args;
17681 TargetLowering::ArgListEntry Entry;
17682 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17683 EVT ArgVT = Op->getOperand(i).getValueType();
17684 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17685 "Unexpected argument type for lowering");
17686 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17687 Entry.Node = StackPtr;
17688 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17690 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17691 Entry.Ty = PointerType::get(ArgTy,0);
17692 Entry.isSExt = false;
17693 Entry.isZExt = false;
17694 Args.push_back(Entry);
17697 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17698 getPointerTy(DAG.getDataLayout()));
17700 TargetLowering::CallLoweringInfo CLI(DAG);
17701 CLI.setDebugLoc(dl).setChain(InChain)
17702 .setCallee(getLibcallCallingConv(LC),
17703 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17704 Callee, std::move(Args), 0)
17705 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17707 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17708 return DAG.getBitcast(VT, CallInfo.first);
17711 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17712 SelectionDAG &DAG) {
17713 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17714 EVT VT = Op0.getValueType();
17717 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17718 (VT == MVT::v8i32 && Subtarget->hasInt256()));
17720 // PMULxD operations multiply each even value (starting at 0) of LHS with
17721 // the related value of RHS and produce a widen result.
17722 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17723 // => <2 x i64> <ae|cg>
17725 // In other word, to have all the results, we need to perform two PMULxD:
17726 // 1. one with the even values.
17727 // 2. one with the odd values.
17728 // To achieve #2, with need to place the odd values at an even position.
17730 // Place the odd value at an even position (basically, shift all values 1
17731 // step to the left):
17732 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17733 // <a|b|c|d> => <b|undef|d|undef>
17734 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17735 // <e|f|g|h> => <f|undef|h|undef>
17736 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17738 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17740 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17741 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17743 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17744 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17745 // => <2 x i64> <ae|cg>
17746 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17747 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17748 // => <2 x i64> <bf|dh>
17749 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17751 // Shuffle it back into the right order.
17752 SDValue Highs, Lows;
17753 if (VT == MVT::v8i32) {
17754 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17755 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17756 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17757 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17759 const int HighMask[] = {1, 5, 3, 7};
17760 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17761 const int LowMask[] = {0, 4, 2, 6};
17762 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17765 // If we have a signed multiply but no PMULDQ fix up the high parts of a
17766 // unsigned multiply.
17767 if (IsSigned && !Subtarget->hasSSE41()) {
17768 SDValue ShAmt = DAG.getConstant(
17770 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17771 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17772 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17773 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17774 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17776 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17777 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17780 // The first result of MUL_LOHI is actually the low value, followed by the
17782 SDValue Ops[] = {Lows, Highs};
17783 return DAG.getMergeValues(Ops, dl);
17786 // Return true if the required (according to Opcode) shift-imm form is natively
17787 // supported by the Subtarget
17788 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17790 if (VT.getScalarSizeInBits() < 16)
17793 if (VT.is512BitVector() &&
17794 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17797 bool LShift = VT.is128BitVector() ||
17798 (VT.is256BitVector() && Subtarget->hasInt256());
17800 bool AShift = LShift && (Subtarget->hasVLX() ||
17801 (VT != MVT::v2i64 && VT != MVT::v4i64));
17802 return (Opcode == ISD::SRA) ? AShift : LShift;
17805 // The shift amount is a variable, but it is the same for all vector lanes.
17806 // These instructions are defined together with shift-immediate.
17808 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17810 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17813 // Return true if the required (according to Opcode) variable-shift form is
17814 // natively supported by the Subtarget
17815 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17818 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17821 // vXi16 supported only on AVX-512, BWI
17822 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17825 if (VT.is512BitVector() || Subtarget->hasVLX())
17828 bool LShift = VT.is128BitVector() || VT.is256BitVector();
17829 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
17830 return (Opcode == ISD::SRA) ? AShift : LShift;
17833 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17834 const X86Subtarget *Subtarget) {
17835 MVT VT = Op.getSimpleValueType();
17837 SDValue R = Op.getOperand(0);
17838 SDValue Amt = Op.getOperand(1);
17840 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17841 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17843 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17844 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17845 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17846 SDValue Ex = DAG.getBitcast(ExVT, R);
17848 if (ShiftAmt >= 32) {
17849 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17851 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17852 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17853 ShiftAmt - 32, DAG);
17854 if (VT == MVT::v2i64)
17855 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17856 if (VT == MVT::v4i64)
17857 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17858 {9, 1, 11, 3, 13, 5, 15, 7});
17860 // SRA upper i32, SHL whole i64 and select lower i32.
17861 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17864 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17865 Lower = DAG.getBitcast(ExVT, Lower);
17866 if (VT == MVT::v2i64)
17867 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17868 if (VT == MVT::v4i64)
17869 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17870 {8, 1, 10, 3, 12, 5, 14, 7});
17872 return DAG.getBitcast(VT, Ex);
17875 // Optimize shl/srl/sra with constant shift amount.
17876 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17877 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17878 uint64_t ShiftAmt = ShiftConst->getZExtValue();
17880 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17881 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17883 // i64 SRA needs to be performed as partial shifts.
17884 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17885 Op.getOpcode() == ISD::SRA)
17886 return ArithmeticShiftRight64(ShiftAmt);
17888 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17889 unsigned NumElts = VT.getVectorNumElements();
17890 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17892 if (Op.getOpcode() == ISD::SHL) {
17893 // Simple i8 add case
17895 return DAG.getNode(ISD::ADD, dl, VT, R, R);
17897 // Make a large shift.
17898 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17900 SHL = DAG.getBitcast(VT, SHL);
17901 // Zero out the rightmost bits.
17902 SmallVector<SDValue, 32> V(
17903 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17904 return DAG.getNode(ISD::AND, dl, VT, SHL,
17905 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17907 if (Op.getOpcode() == ISD::SRL) {
17908 // Make a large shift.
17909 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17911 SRL = DAG.getBitcast(VT, SRL);
17912 // Zero out the leftmost bits.
17913 SmallVector<SDValue, 32> V(
17914 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17915 return DAG.getNode(ISD::AND, dl, VT, SRL,
17916 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17918 if (Op.getOpcode() == ISD::SRA) {
17919 if (ShiftAmt == 7) {
17920 // ashr(R, 7) === cmp_slt(R, 0)
17921 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17922 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17925 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17926 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17927 SmallVector<SDValue, 32> V(NumElts,
17928 DAG.getConstant(128 >> ShiftAmt, dl,
17930 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17931 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17932 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17935 llvm_unreachable("Unknown shift opcode.");
17940 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17941 if (!Subtarget->is64Bit() &&
17942 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17944 // Peek through any splat that was introduced for i64 shift vectorization.
17945 int SplatIndex = -1;
17946 if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17947 if (SVN->isSplat()) {
17948 SplatIndex = SVN->getSplatIndex();
17949 Amt = Amt.getOperand(0);
17950 assert(SplatIndex < (int)VT.getVectorNumElements() &&
17951 "Splat shuffle referencing second operand");
17954 if (Amt.getOpcode() != ISD::BITCAST ||
17955 Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17958 Amt = Amt.getOperand(0);
17959 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17960 VT.getVectorNumElements();
17961 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17962 uint64_t ShiftAmt = 0;
17963 unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17964 for (unsigned i = 0; i != Ratio; ++i) {
17965 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17969 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17972 // Check remaining shift amounts (if not a splat).
17973 if (SplatIndex < 0) {
17974 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17975 uint64_t ShAmt = 0;
17976 for (unsigned j = 0; j != Ratio; ++j) {
17977 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17981 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17983 if (ShAmt != ShiftAmt)
17988 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17989 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17991 if (Op.getOpcode() == ISD::SRA)
17992 return ArithmeticShiftRight64(ShiftAmt);
17998 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17999 const X86Subtarget* Subtarget) {
18000 MVT VT = Op.getSimpleValueType();
18002 SDValue R = Op.getOperand(0);
18003 SDValue Amt = Op.getOperand(1);
18005 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18006 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18008 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18009 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18011 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18013 EVT EltVT = VT.getVectorElementType();
18015 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18016 // Check if this build_vector node is doing a splat.
18017 // If so, then set BaseShAmt equal to the splat value.
18018 BaseShAmt = BV->getSplatValue();
18019 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18020 BaseShAmt = SDValue();
18022 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18023 Amt = Amt.getOperand(0);
18025 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18026 if (SVN && SVN->isSplat()) {
18027 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18028 SDValue InVec = Amt.getOperand(0);
18029 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18030 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
18031 "Unexpected shuffle index found!");
18032 BaseShAmt = InVec.getOperand(SplatIdx);
18033 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18034 if (ConstantSDNode *C =
18035 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18036 if (C->getZExtValue() == SplatIdx)
18037 BaseShAmt = InVec.getOperand(1);
18042 // Avoid introducing an extract element from a shuffle.
18043 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18044 DAG.getIntPtrConstant(SplatIdx, dl));
18048 if (BaseShAmt.getNode()) {
18049 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18050 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18051 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18052 else if (EltVT.bitsLT(MVT::i32))
18053 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18055 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18059 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18060 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
18061 Amt.getOpcode() == ISD::BITCAST &&
18062 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18063 Amt = Amt.getOperand(0);
18064 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18065 VT.getVectorNumElements();
18066 std::vector<SDValue> Vals(Ratio);
18067 for (unsigned i = 0; i != Ratio; ++i)
18068 Vals[i] = Amt.getOperand(i);
18069 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18070 for (unsigned j = 0; j != Ratio; ++j)
18071 if (Vals[j] != Amt.getOperand(i + j))
18075 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18076 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18081 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18082 SelectionDAG &DAG) {
18083 MVT VT = Op.getSimpleValueType();
18085 SDValue R = Op.getOperand(0);
18086 SDValue Amt = Op.getOperand(1);
18088 assert(VT.isVector() && "Custom lowering only for vector shifts!");
18089 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18091 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18094 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18097 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18100 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18101 // shifts per-lane and then shuffle the partial results back together.
18102 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18103 // Splat the shift amounts so the scalar shifts above will catch it.
18104 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18105 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18106 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18107 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18108 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18111 // i64 vector arithmetic shift can be emulated with the transform:
18112 // M = lshr(SIGN_BIT, Amt)
18113 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18114 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18115 Op.getOpcode() == ISD::SRA) {
18116 SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18117 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18118 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18119 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18120 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18124 // If possible, lower this packed shift into a vector multiply instead of
18125 // expanding it into a sequence of scalar shifts.
18126 // Do this only if the vector shift count is a constant build_vector.
18127 if (Op.getOpcode() == ISD::SHL &&
18128 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18129 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18130 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18131 SmallVector<SDValue, 8> Elts;
18132 EVT SVT = VT.getScalarType();
18133 unsigned SVTBits = SVT.getSizeInBits();
18134 const APInt &One = APInt(SVTBits, 1);
18135 unsigned NumElems = VT.getVectorNumElements();
18137 for (unsigned i=0; i !=NumElems; ++i) {
18138 SDValue Op = Amt->getOperand(i);
18139 if (Op->getOpcode() == ISD::UNDEF) {
18140 Elts.push_back(Op);
18144 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18145 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18146 uint64_t ShAmt = C.getZExtValue();
18147 if (ShAmt >= SVTBits) {
18148 Elts.push_back(DAG.getUNDEF(SVT));
18151 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18153 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18154 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18157 // Lower SHL with variable shift amount.
18158 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18159 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18161 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18162 DAG.getConstant(0x3f800000U, dl, VT));
18163 Op = DAG.getBitcast(MVT::v4f32, Op);
18164 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18165 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18168 // If possible, lower this shift as a sequence of two shifts by
18169 // constant plus a MOVSS/MOVSD instead of scalarizing it.
18171 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18173 // Could be rewritten as:
18174 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18176 // The advantage is that the two shifts from the example would be
18177 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18178 // the vector shift into four scalar shifts plus four pairs of vector
18180 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18181 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18182 unsigned TargetOpcode = X86ISD::MOVSS;
18183 bool CanBeSimplified;
18184 // The splat value for the first packed shift (the 'X' from the example).
18185 SDValue Amt1 = Amt->getOperand(0);
18186 // The splat value for the second packed shift (the 'Y' from the example).
18187 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18188 Amt->getOperand(2);
18190 // See if it is possible to replace this node with a sequence of
18191 // two shifts followed by a MOVSS/MOVSD
18192 if (VT == MVT::v4i32) {
18193 // Check if it is legal to use a MOVSS.
18194 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18195 Amt2 == Amt->getOperand(3);
18196 if (!CanBeSimplified) {
18197 // Otherwise, check if we can still simplify this node using a MOVSD.
18198 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18199 Amt->getOperand(2) == Amt->getOperand(3);
18200 TargetOpcode = X86ISD::MOVSD;
18201 Amt2 = Amt->getOperand(2);
18204 // Do similar checks for the case where the machine value type
18206 CanBeSimplified = Amt1 == Amt->getOperand(1);
18207 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18208 CanBeSimplified = Amt2 == Amt->getOperand(i);
18210 if (!CanBeSimplified) {
18211 TargetOpcode = X86ISD::MOVSD;
18212 CanBeSimplified = true;
18213 Amt2 = Amt->getOperand(4);
18214 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18215 CanBeSimplified = Amt1 == Amt->getOperand(i);
18216 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18217 CanBeSimplified = Amt2 == Amt->getOperand(j);
18221 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18222 isa<ConstantSDNode>(Amt2)) {
18223 // Replace this node with two shifts followed by a MOVSS/MOVSD.
18224 EVT CastVT = MVT::v4i32;
18226 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18227 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18229 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18230 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18231 if (TargetOpcode == X86ISD::MOVSD)
18232 CastVT = MVT::v2i64;
18233 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18234 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18235 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18237 return DAG.getBitcast(VT, Result);
18241 // v4i32 Non Uniform Shifts.
18242 // If the shift amount is constant we can shift each lane using the SSE2
18243 // immediate shifts, else we need to zero-extend each lane to the lower i64
18244 // and shift using the SSE2 variable shifts.
18245 // The separate results can then be blended together.
18246 if (VT == MVT::v4i32) {
18247 unsigned Opc = Op.getOpcode();
18248 SDValue Amt0, Amt1, Amt2, Amt3;
18249 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18250 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18251 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18252 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18253 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18255 // ISD::SHL is handled above but we include it here for completeness.
18258 llvm_unreachable("Unknown target vector shift node");
18260 Opc = X86ISD::VSHL;
18263 Opc = X86ISD::VSRL;
18266 Opc = X86ISD::VSRA;
18269 // The SSE2 shifts use the lower i64 as the same shift amount for
18270 // all lanes and the upper i64 is ignored. These shuffle masks
18271 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18272 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18273 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18274 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18275 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18276 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18279 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18280 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18281 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18282 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18283 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18284 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18285 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18288 if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
18289 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18290 unsigned ShiftOpcode = Op->getOpcode();
18292 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18293 // On SSE41 targets we make use of the fact that VSELECT lowers
18294 // to PBLENDVB which selects bytes based just on the sign bit.
18295 if (Subtarget->hasSSE41()) {
18296 V0 = DAG.getBitcast(VT, V0);
18297 V1 = DAG.getBitcast(VT, V1);
18298 Sel = DAG.getBitcast(VT, Sel);
18299 return DAG.getBitcast(SelVT,
18300 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18302 // On pre-SSE41 targets we test for the sign bit by comparing to
18303 // zero - a negative value will set all bits of the lanes to true
18304 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18305 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18306 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18307 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18310 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18311 // We can safely do this using i16 shifts as we're only interested in
18312 // the 3 lower bits of each byte.
18313 Amt = DAG.getBitcast(ExtVT, Amt);
18314 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18315 Amt = DAG.getBitcast(VT, Amt);
18317 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18318 // r = VSELECT(r, shift(r, 4), a);
18320 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18321 R = SignBitSelect(VT, Amt, M, R);
18324 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18326 // r = VSELECT(r, shift(r, 2), a);
18327 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18328 R = SignBitSelect(VT, Amt, M, R);
18331 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18333 // return VSELECT(r, shift(r, 1), a);
18334 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18335 R = SignBitSelect(VT, Amt, M, R);
18339 if (Op->getOpcode() == ISD::SRA) {
18340 // For SRA we need to unpack each byte to the higher byte of a i16 vector
18341 // so we can correctly sign extend. We don't care what happens to the
18343 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18344 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18345 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18346 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18347 ALo = DAG.getBitcast(ExtVT, ALo);
18348 AHi = DAG.getBitcast(ExtVT, AHi);
18349 RLo = DAG.getBitcast(ExtVT, RLo);
18350 RHi = DAG.getBitcast(ExtVT, RHi);
18352 // r = VSELECT(r, shift(r, 4), a);
18353 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18354 DAG.getConstant(4, dl, ExtVT));
18355 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18356 DAG.getConstant(4, dl, ExtVT));
18357 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18358 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18361 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18362 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18364 // r = VSELECT(r, shift(r, 2), a);
18365 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18366 DAG.getConstant(2, dl, ExtVT));
18367 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18368 DAG.getConstant(2, dl, ExtVT));
18369 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18370 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18373 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18374 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18376 // r = VSELECT(r, shift(r, 1), a);
18377 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18378 DAG.getConstant(1, dl, ExtVT));
18379 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18380 DAG.getConstant(1, dl, ExtVT));
18381 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18382 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18384 // Logical shift the result back to the lower byte, leaving a zero upper
18386 // meaning that we can safely pack with PACKUSWB.
18388 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18390 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18391 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18395 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18396 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18397 // solution better.
18398 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18399 MVT ExtVT = MVT::v8i32;
18401 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18402 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18403 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18404 return DAG.getNode(ISD::TRUNCATE, dl, VT,
18405 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18408 if (Subtarget->hasInt256() && VT == MVT::v16i16) {
18409 MVT ExtVT = MVT::v8i32;
18410 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18411 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18412 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18413 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18414 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18415 ALo = DAG.getBitcast(ExtVT, ALo);
18416 AHi = DAG.getBitcast(ExtVT, AHi);
18417 RLo = DAG.getBitcast(ExtVT, RLo);
18418 RHi = DAG.getBitcast(ExtVT, RHi);
18419 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18420 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18421 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18422 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18423 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18426 if (VT == MVT::v8i16) {
18427 unsigned ShiftOpcode = Op->getOpcode();
18429 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18430 // On SSE41 targets we make use of the fact that VSELECT lowers
18431 // to PBLENDVB which selects bytes based just on the sign bit.
18432 if (Subtarget->hasSSE41()) {
18433 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18434 V0 = DAG.getBitcast(ExtVT, V0);
18435 V1 = DAG.getBitcast(ExtVT, V1);
18436 Sel = DAG.getBitcast(ExtVT, Sel);
18437 return DAG.getBitcast(
18438 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18440 // On pre-SSE41 targets we splat the sign bit - a negative value will
18441 // set all bits of the lanes to true and VSELECT uses that in
18442 // its OR(AND(V0,C),AND(V1,~C)) lowering.
18444 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18445 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18448 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18449 if (Subtarget->hasSSE41()) {
18450 // On SSE41 targets we need to replicate the shift mask in both
18451 // bytes for PBLENDVB.
18454 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18455 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18457 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18460 // r = VSELECT(r, shift(r, 8), a);
18461 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18462 R = SignBitSelect(Amt, M, R);
18465 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18467 // r = VSELECT(r, shift(r, 4), a);
18468 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18469 R = SignBitSelect(Amt, M, R);
18472 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18474 // r = VSELECT(r, shift(r, 2), a);
18475 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18476 R = SignBitSelect(Amt, M, R);
18479 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18481 // return VSELECT(r, shift(r, 1), a);
18482 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18483 R = SignBitSelect(Amt, M, R);
18487 // Decompose 256-bit shifts into smaller 128-bit shifts.
18488 if (VT.is256BitVector()) {
18489 unsigned NumElems = VT.getVectorNumElements();
18490 MVT EltVT = VT.getVectorElementType();
18491 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18493 // Extract the two vectors
18494 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18495 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18497 // Recreate the shift amount vectors
18498 SDValue Amt1, Amt2;
18499 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18500 // Constant shift amount
18501 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18502 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18503 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18505 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18506 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18508 // Variable shift amount
18509 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18510 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18513 // Issue new vector shifts for the smaller types
18514 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18515 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18517 // Concatenate the result back
18518 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18524 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18525 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18526 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18527 // looks for this combo and may remove the "setcc" instruction if the "setcc"
18528 // has only one use.
18529 SDNode *N = Op.getNode();
18530 SDValue LHS = N->getOperand(0);
18531 SDValue RHS = N->getOperand(1);
18532 unsigned BaseOp = 0;
18535 switch (Op.getOpcode()) {
18536 default: llvm_unreachable("Unknown ovf instruction!");
18538 // A subtract of one will be selected as a INC. Note that INC doesn't
18539 // set CF, so we can't do this for UADDO.
18540 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18542 BaseOp = X86ISD::INC;
18543 Cond = X86::COND_O;
18546 BaseOp = X86ISD::ADD;
18547 Cond = X86::COND_O;
18550 BaseOp = X86ISD::ADD;
18551 Cond = X86::COND_B;
18554 // A subtract of one will be selected as a DEC. Note that DEC doesn't
18555 // set CF, so we can't do this for USUBO.
18556 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18558 BaseOp = X86ISD::DEC;
18559 Cond = X86::COND_O;
18562 BaseOp = X86ISD::SUB;
18563 Cond = X86::COND_O;
18566 BaseOp = X86ISD::SUB;
18567 Cond = X86::COND_B;
18570 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18571 Cond = X86::COND_O;
18573 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18574 if (N->getValueType(0) == MVT::i8) {
18575 BaseOp = X86ISD::UMUL8;
18576 Cond = X86::COND_O;
18579 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18581 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18584 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18585 DAG.getConstant(X86::COND_O, DL, MVT::i32),
18586 SDValue(Sum.getNode(), 2));
18588 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18592 // Also sets EFLAGS.
18593 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18594 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18597 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18598 DAG.getConstant(Cond, DL, MVT::i32),
18599 SDValue(Sum.getNode(), 1));
18601 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18604 /// Returns true if the operand type is exactly twice the native width, and
18605 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18606 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18607 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18608 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18609 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18612 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18613 else if (OpWidth == 128)
18614 return Subtarget->hasCmpxchg16b();
18619 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18620 return needsCmpXchgNb(SI->getValueOperand()->getType());
18623 // Note: this turns large loads into lock cmpxchg8b/16b.
18624 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18625 TargetLowering::AtomicExpansionKind
18626 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18627 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18628 return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
18629 : AtomicExpansionKind::None;
18632 TargetLowering::AtomicExpansionKind
18633 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18634 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18635 Type *MemType = AI->getType();
18637 // If the operand is too big, we must see if cmpxchg8/16b is available
18638 // and default to library calls otherwise.
18639 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18640 return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
18641 : AtomicExpansionKind::None;
18644 AtomicRMWInst::BinOp Op = AI->getOperation();
18647 llvm_unreachable("Unknown atomic operation");
18648 case AtomicRMWInst::Xchg:
18649 case AtomicRMWInst::Add:
18650 case AtomicRMWInst::Sub:
18651 // It's better to use xadd, xsub or xchg for these in all cases.
18652 return AtomicExpansionKind::None;
18653 case AtomicRMWInst::Or:
18654 case AtomicRMWInst::And:
18655 case AtomicRMWInst::Xor:
18656 // If the atomicrmw's result isn't actually used, we can just add a "lock"
18657 // prefix to a normal instruction for these operations.
18658 return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
18659 : AtomicExpansionKind::None;
18660 case AtomicRMWInst::Nand:
18661 case AtomicRMWInst::Max:
18662 case AtomicRMWInst::Min:
18663 case AtomicRMWInst::UMax:
18664 case AtomicRMWInst::UMin:
18665 // These always require a non-trivial set of data operations on x86. We must
18666 // use a cmpxchg loop.
18667 return AtomicExpansionKind::CmpXChg;
18671 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18672 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18673 // no-sse2). There isn't any reason to disable it if the target processor
18675 return Subtarget.hasSSE2() || Subtarget.is64Bit();
18679 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18680 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18681 Type *MemType = AI->getType();
18682 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18683 // there is no benefit in turning such RMWs into loads, and it is actually
18684 // harmful as it introduces a mfence.
18685 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18688 auto Builder = IRBuilder<>(AI);
18689 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18690 auto SynchScope = AI->getSynchScope();
18691 // We must restrict the ordering to avoid generating loads with Release or
18692 // ReleaseAcquire orderings.
18693 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18694 auto Ptr = AI->getPointerOperand();
18696 // Before the load we need a fence. Here is an example lifted from
18697 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18700 // x.store(1, relaxed);
18701 // r1 = y.fetch_add(0, release);
18703 // y.fetch_add(42, acquire);
18704 // r2 = x.load(relaxed);
18705 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18706 // lowered to just a load without a fence. A mfence flushes the store buffer,
18707 // making the optimization clearly correct.
18708 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18709 // otherwise, we might be able to be more aggressive on relaxed idempotent
18710 // rmw. In practice, they do not look useful, so we don't try to be
18711 // especially clever.
18712 if (SynchScope == SingleThread)
18713 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18714 // the IR level, so we must wrap it in an intrinsic.
18717 if (!hasMFENCE(*Subtarget))
18718 // FIXME: it might make sense to use a locked operation here but on a
18719 // different cache-line to prevent cache-line bouncing. In practice it
18720 // is probably a small win, and x86 processors without mfence are rare
18721 // enough that we do not bother.
18725 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18726 Builder.CreateCall(MFence, {});
18728 // Finally we can emit the atomic load.
18729 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18730 AI->getType()->getPrimitiveSizeInBits());
18731 Loaded->setAtomic(Order, SynchScope);
18732 AI->replaceAllUsesWith(Loaded);
18733 AI->eraseFromParent();
18737 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18738 SelectionDAG &DAG) {
18740 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18741 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18742 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18743 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18745 // The only fence that needs an instruction is a sequentially-consistent
18746 // cross-thread fence.
18747 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18748 if (hasMFENCE(*Subtarget))
18749 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18751 SDValue Chain = Op.getOperand(0);
18752 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18754 DAG.getRegister(X86::ESP, MVT::i32), // Base
18755 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
18756 DAG.getRegister(0, MVT::i32), // Index
18757 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
18758 DAG.getRegister(0, MVT::i32), // Segment.
18762 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18763 return SDValue(Res, 0);
18766 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18767 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18770 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18771 SelectionDAG &DAG) {
18772 MVT T = Op.getSimpleValueType();
18776 switch(T.SimpleTy) {
18777 default: llvm_unreachable("Invalid value type!");
18778 case MVT::i8: Reg = X86::AL; size = 1; break;
18779 case MVT::i16: Reg = X86::AX; size = 2; break;
18780 case MVT::i32: Reg = X86::EAX; size = 4; break;
18782 assert(Subtarget->is64Bit() && "Node not type legal!");
18783 Reg = X86::RAX; size = 8;
18786 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18787 Op.getOperand(2), SDValue());
18788 SDValue Ops[] = { cpIn.getValue(0),
18791 DAG.getTargetConstant(size, DL, MVT::i8),
18792 cpIn.getValue(1) };
18793 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18794 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18795 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18799 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18800 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18801 MVT::i32, cpOut.getValue(2));
18802 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18803 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18806 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18807 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18808 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18812 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18813 SelectionDAG &DAG) {
18814 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18815 MVT DstVT = Op.getSimpleValueType();
18817 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18818 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18819 if (DstVT != MVT::f64)
18820 // This conversion needs to be expanded.
18823 SDValue InVec = Op->getOperand(0);
18825 unsigned NumElts = SrcVT.getVectorNumElements();
18826 EVT SVT = SrcVT.getVectorElementType();
18828 // Widen the vector in input in the case of MVT::v2i32.
18829 // Example: from MVT::v2i32 to MVT::v4i32.
18830 SmallVector<SDValue, 16> Elts;
18831 for (unsigned i = 0, e = NumElts; i != e; ++i)
18832 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18833 DAG.getIntPtrConstant(i, dl)));
18835 // Explicitly mark the extra elements as Undef.
18836 Elts.append(NumElts, DAG.getUNDEF(SVT));
18838 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18839 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18840 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18841 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18842 DAG.getIntPtrConstant(0, dl));
18845 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18846 Subtarget->hasMMX() && "Unexpected custom BITCAST");
18847 assert((DstVT == MVT::i64 ||
18848 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18849 "Unexpected custom BITCAST");
18850 // i64 <=> MMX conversions are Legal.
18851 if (SrcVT==MVT::i64 && DstVT.isVector())
18853 if (DstVT==MVT::i64 && SrcVT.isVector())
18855 // MMX <=> MMX conversions are Legal.
18856 if (SrcVT.isVector() && DstVT.isVector())
18858 // All other conversions need to be expanded.
18862 /// Compute the horizontal sum of bytes in V for the elements of VT.
18864 /// Requires V to be a byte vector and VT to be an integer vector type with
18865 /// wider elements than V's type. The width of the elements of VT determines
18866 /// how many bytes of V are summed horizontally to produce each element of the
18868 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18869 const X86Subtarget *Subtarget,
18870 SelectionDAG &DAG) {
18872 MVT ByteVecVT = V.getSimpleValueType();
18873 MVT EltVT = VT.getVectorElementType();
18874 int NumElts = VT.getVectorNumElements();
18875 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18876 "Expected value to have byte element type.");
18877 assert(EltVT != MVT::i8 &&
18878 "Horizontal byte sum only makes sense for wider elements!");
18879 unsigned VecSize = VT.getSizeInBits();
18880 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18882 // PSADBW instruction horizontally add all bytes and leave the result in i64
18883 // chunks, thus directly computes the pop count for v2i64 and v4i64.
18884 if (EltVT == MVT::i64) {
18885 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18886 V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18887 return DAG.getBitcast(VT, V);
18890 if (EltVT == MVT::i32) {
18891 // We unpack the low half and high half into i32s interleaved with zeros so
18892 // that we can use PSADBW to horizontally sum them. The most useful part of
18893 // this is that it lines up the results of two PSADBW instructions to be
18894 // two v2i64 vectors which concatenated are the 4 population counts. We can
18895 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18896 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18897 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18898 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18900 // Do the horizontal sums into two v2i64s.
18901 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18902 Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18903 DAG.getBitcast(ByteVecVT, Low), Zeros);
18904 High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18905 DAG.getBitcast(ByteVecVT, High), Zeros);
18907 // Merge them together.
18908 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18909 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18910 DAG.getBitcast(ShortVecVT, Low),
18911 DAG.getBitcast(ShortVecVT, High));
18913 return DAG.getBitcast(VT, V);
18916 // The only element type left is i16.
18917 assert(EltVT == MVT::i16 && "Unknown how to handle type");
18919 // To obtain pop count for each i16 element starting from the pop count for
18920 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18921 // right by 8. It is important to shift as i16s as i8 vector shift isn't
18922 // directly supported.
18923 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18924 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18925 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18926 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18927 DAG.getBitcast(ByteVecVT, V));
18928 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18931 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18932 const X86Subtarget *Subtarget,
18933 SelectionDAG &DAG) {
18934 MVT VT = Op.getSimpleValueType();
18935 MVT EltVT = VT.getVectorElementType();
18936 unsigned VecSize = VT.getSizeInBits();
18938 // Implement a lookup table in register by using an algorithm based on:
18939 // http://wm.ite.pl/articles/sse-popcount.html
18941 // The general idea is that every lower byte nibble in the input vector is an
18942 // index into a in-register pre-computed pop count table. We then split up the
18943 // input vector in two new ones: (1) a vector with only the shifted-right
18944 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18945 // masked out higher ones) for each byte. PSHUB is used separately with both
18946 // to index the in-register table. Next, both are added and the result is a
18947 // i8 vector where each element contains the pop count for input byte.
18949 // To obtain the pop count for elements != i8, we follow up with the same
18950 // approach and use additional tricks as described below.
18952 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18953 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18954 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18955 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18957 int NumByteElts = VecSize / 8;
18958 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18959 SDValue In = DAG.getBitcast(ByteVecVT, Op);
18960 SmallVector<SDValue, 16> LUTVec;
18961 for (int i = 0; i < NumByteElts; ++i)
18962 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18963 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18964 SmallVector<SDValue, 16> Mask0F(NumByteElts,
18965 DAG.getConstant(0x0F, DL, MVT::i8));
18966 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18969 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18970 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18971 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18974 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18976 // The input vector is used as the shuffle mask that index elements into the
18977 // LUT. After counting low and high nibbles, add the vector to obtain the
18978 // final pop count per i8 element.
18979 SDValue HighPopCnt =
18980 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18981 SDValue LowPopCnt =
18982 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18983 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18985 if (EltVT == MVT::i8)
18988 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18991 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18992 const X86Subtarget *Subtarget,
18993 SelectionDAG &DAG) {
18994 MVT VT = Op.getSimpleValueType();
18995 assert(VT.is128BitVector() &&
18996 "Only 128-bit vector bitmath lowering supported.");
18998 int VecSize = VT.getSizeInBits();
18999 MVT EltVT = VT.getVectorElementType();
19000 int Len = EltVT.getSizeInBits();
19002 // This is the vectorized version of the "best" algorithm from
19003 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19004 // with a minor tweak to use a series of adds + shifts instead of vector
19005 // multiplications. Implemented for all integer vector types. We only use
19006 // this when we don't have SSSE3 which allows a LUT-based lowering that is
19007 // much faster, even faster than using native popcnt instructions.
19009 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19010 MVT VT = V.getSimpleValueType();
19011 SmallVector<SDValue, 32> Shifters(
19012 VT.getVectorNumElements(),
19013 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19014 return DAG.getNode(OpCode, DL, VT, V,
19015 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19017 auto GetMask = [&](SDValue V, APInt Mask) {
19018 MVT VT = V.getSimpleValueType();
19019 SmallVector<SDValue, 32> Masks(
19020 VT.getVectorNumElements(),
19021 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19022 return DAG.getNode(ISD::AND, DL, VT, V,
19023 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19026 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19027 // x86, so set the SRL type to have elements at least i16 wide. This is
19028 // correct because all of our SRLs are followed immediately by a mask anyways
19029 // that handles any bits that sneak into the high bits of the byte elements.
19030 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19034 // v = v - ((v >> 1) & 0x55555555...)
19036 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19037 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19038 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19040 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19041 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19042 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19043 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19044 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19046 // v = (v + (v >> 4)) & 0x0F0F0F0F...
19047 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19048 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19049 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19051 // At this point, V contains the byte-wise population count, and we are
19052 // merely doing a horizontal sum if necessary to get the wider element
19054 if (EltVT == MVT::i8)
19057 return LowerHorizontalByteSum(
19058 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19062 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19063 SelectionDAG &DAG) {
19064 MVT VT = Op.getSimpleValueType();
19065 // FIXME: Need to add AVX-512 support here!
19066 assert((VT.is256BitVector() || VT.is128BitVector()) &&
19067 "Unknown CTPOP type to handle");
19068 SDLoc DL(Op.getNode());
19069 SDValue Op0 = Op.getOperand(0);
19071 if (!Subtarget->hasSSSE3()) {
19072 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19073 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19074 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19077 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19078 unsigned NumElems = VT.getVectorNumElements();
19080 // Extract each 128-bit vector, compute pop count and concat the result.
19081 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19082 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19084 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19085 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19086 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19089 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19092 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19093 SelectionDAG &DAG) {
19094 assert(Op.getValueType().isVector() &&
19095 "We only do custom lowering for vector population count.");
19096 return LowerVectorCTPOP(Op, Subtarget, DAG);
19099 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19100 SDNode *Node = Op.getNode();
19102 EVT T = Node->getValueType(0);
19103 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19104 DAG.getConstant(0, dl, T), Node->getOperand(2));
19105 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19106 cast<AtomicSDNode>(Node)->getMemoryVT(),
19107 Node->getOperand(0),
19108 Node->getOperand(1), negOp,
19109 cast<AtomicSDNode>(Node)->getMemOperand(),
19110 cast<AtomicSDNode>(Node)->getOrdering(),
19111 cast<AtomicSDNode>(Node)->getSynchScope());
19114 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19115 SDNode *Node = Op.getNode();
19117 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19119 // Convert seq_cst store -> xchg
19120 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19121 // FIXME: On 32-bit, store -> fist or movq would be more efficient
19122 // (The only way to get a 16-byte store is cmpxchg16b)
19123 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19124 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19125 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19126 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19127 cast<AtomicSDNode>(Node)->getMemoryVT(),
19128 Node->getOperand(0),
19129 Node->getOperand(1), Node->getOperand(2),
19130 cast<AtomicSDNode>(Node)->getMemOperand(),
19131 cast<AtomicSDNode>(Node)->getOrdering(),
19132 cast<AtomicSDNode>(Node)->getSynchScope());
19133 return Swap.getValue(1);
19135 // Other atomic stores have a simple pattern.
19139 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19140 EVT VT = Op.getNode()->getSimpleValueType(0);
19142 // Let legalize expand this if it isn't a legal type yet.
19143 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19146 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19149 bool ExtraOp = false;
19150 switch (Op.getOpcode()) {
19151 default: llvm_unreachable("Invalid code");
19152 case ISD::ADDC: Opc = X86ISD::ADD; break;
19153 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19154 case ISD::SUBC: Opc = X86ISD::SUB; break;
19155 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19159 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19161 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19162 Op.getOperand(1), Op.getOperand(2));
19165 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19166 SelectionDAG &DAG) {
19167 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19169 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19170 // which returns the values as { float, float } (in XMM0) or
19171 // { double, double } (which is returned in XMM0, XMM1).
19173 SDValue Arg = Op.getOperand(0);
19174 EVT ArgVT = Arg.getValueType();
19175 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19177 TargetLowering::ArgListTy Args;
19178 TargetLowering::ArgListEntry Entry;
19182 Entry.isSExt = false;
19183 Entry.isZExt = false;
19184 Args.push_back(Entry);
19186 bool isF64 = ArgVT == MVT::f64;
19187 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19188 // the small struct {f32, f32} is returned in (eax, edx). For f64,
19189 // the results are returned via SRet in memory.
19190 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
19191 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19193 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19195 Type *RetTy = isF64
19196 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19197 : (Type*)VectorType::get(ArgTy, 4);
19199 TargetLowering::CallLoweringInfo CLI(DAG);
19200 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19201 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19203 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19206 // Returned in xmm0 and xmm1.
19207 return CallResult.first;
19209 // Returned in bits 0:31 and 32:64 xmm0.
19210 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19211 CallResult.first, DAG.getIntPtrConstant(0, dl));
19212 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19213 CallResult.first, DAG.getIntPtrConstant(1, dl));
19214 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19215 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19218 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19219 SelectionDAG &DAG) {
19220 assert(Subtarget->hasAVX512() &&
19221 "MGATHER/MSCATTER are supported on AVX-512 arch only");
19223 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19224 EVT VT = N->getValue().getValueType();
19225 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19228 // X86 scatter kills mask register, so its type should be added to
19229 // the list of return values
19230 if (N->getNumValues() == 1) {
19231 SDValue Index = N->getIndex();
19232 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19233 !Index.getValueType().is512BitVector())
19234 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19236 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19237 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
19238 N->getOperand(3), Index };
19240 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19241 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19242 return SDValue(NewScatter.getNode(), 0);
19247 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19248 SelectionDAG &DAG) {
19249 assert(Subtarget->hasAVX512() &&
19250 "MGATHER/MSCATTER are supported on AVX-512 arch only");
19252 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19253 EVT VT = Op.getValueType();
19254 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19257 SDValue Index = N->getIndex();
19258 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19259 !Index.getValueType().is512BitVector()) {
19260 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19261 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
19262 N->getOperand(3), Index };
19263 DAG.UpdateNodeOperands(N, Ops);
19268 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19269 SelectionDAG &DAG) const {
19270 // TODO: Eventually, the lowering of these nodes should be informed by or
19271 // deferred to the GC strategy for the function in which they appear. For
19272 // now, however, they must be lowered to something. Since they are logically
19273 // no-ops in the case of a null GC strategy (or a GC strategy which does not
19274 // require special handling for these nodes), lower them as literal NOOPs for
19276 SmallVector<SDValue, 2> Ops;
19278 Ops.push_back(Op.getOperand(0));
19279 if (Op->getGluedNode())
19280 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19283 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19284 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19289 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19290 SelectionDAG &DAG) const {
19291 // TODO: Eventually, the lowering of these nodes should be informed by or
19292 // deferred to the GC strategy for the function in which they appear. For
19293 // now, however, they must be lowered to something. Since they are logically
19294 // no-ops in the case of a null GC strategy (or a GC strategy which does not
19295 // require special handling for these nodes), lower them as literal NOOPs for
19297 SmallVector<SDValue, 2> Ops;
19299 Ops.push_back(Op.getOperand(0));
19300 if (Op->getGluedNode())
19301 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19304 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19305 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19310 /// LowerOperation - Provide custom lowering hooks for some operations.
19312 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19313 switch (Op.getOpcode()) {
19314 default: llvm_unreachable("Should not custom lower this!");
19315 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19316 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19317 return LowerCMP_SWAP(Op, Subtarget, DAG);
19318 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
19319 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
19320 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
19321 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
19322 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19323 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
19324 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
19325 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19326 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
19327 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19328 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19329 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
19330 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
19331 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
19332 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
19333 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
19334 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
19335 case ISD::SHL_PARTS:
19336 case ISD::SRA_PARTS:
19337 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
19338 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
19339 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
19340 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
19341 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
19342 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19343 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
19344 case ISD::SIGN_EXTEND_VECTOR_INREG:
19345 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19346 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
19347 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
19348 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
19349 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
19351 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
19352 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
19353 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
19354 case ISD::SETCC: return LowerSETCC(Op, DAG);
19355 case ISD::SELECT: return LowerSELECT(Op, DAG);
19356 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
19357 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
19358 case ISD::VASTART: return LowerVASTART(Op, DAG);
19359 case ISD::VAARG: return LowerVAARG(Op, DAG);
19360 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
19361 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19362 case ISD::INTRINSIC_VOID:
19363 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19364 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
19365 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
19366 case ISD::FRAME_TO_ARGS_OFFSET:
19367 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19368 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19369 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
19370 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
19371 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
19372 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
19373 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
19374 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
19375 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
19376 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19378 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op, DAG);
19379 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
19380 case ISD::UMUL_LOHI:
19381 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
19384 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
19390 case ISD::UMULO: return LowerXALUO(Op, DAG);
19391 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19392 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
19396 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19397 case ISD::ADD: return LowerADD(Op, DAG);
19398 case ISD::SUB: return LowerSUB(Op, DAG);
19402 case ISD::UMIN: return LowerMINMAX(Op, DAG);
19403 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
19404 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
19405 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
19406 case ISD::GC_TRANSITION_START:
19407 return LowerGC_TRANSITION_START(Op, DAG);
19408 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
19412 /// ReplaceNodeResults - Replace a node with an illegal result type
19413 /// with a new node built out of custom code.
19414 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19415 SmallVectorImpl<SDValue>&Results,
19416 SelectionDAG &DAG) const {
19418 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19419 switch (N->getOpcode()) {
19421 llvm_unreachable("Do not know how to custom type legalize this operation!");
19422 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19423 case X86ISD::FMINC:
19425 case X86ISD::FMAXC:
19426 case X86ISD::FMAX: {
19427 EVT VT = N->getValueType(0);
19428 if (VT != MVT::v2f32)
19429 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19430 SDValue UNDEF = DAG.getUNDEF(VT);
19431 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19432 N->getOperand(0), UNDEF);
19433 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19434 N->getOperand(1), UNDEF);
19435 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19438 case ISD::SIGN_EXTEND_INREG:
19443 // We don't want to expand or promote these.
19450 case ISD::UDIVREM: {
19451 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19452 Results.push_back(V);
19455 case ISD::FP_TO_SINT:
19456 case ISD::FP_TO_UINT: {
19457 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19459 std::pair<SDValue,SDValue> Vals =
19460 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19461 SDValue FIST = Vals.first, StackSlot = Vals.second;
19462 if (FIST.getNode()) {
19463 EVT VT = N->getValueType(0);
19464 // Return a load from the stack slot.
19465 if (StackSlot.getNode())
19466 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19467 MachinePointerInfo(),
19468 false, false, false, 0));
19470 Results.push_back(FIST);
19474 case ISD::UINT_TO_FP: {
19475 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19476 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19477 N->getValueType(0) != MVT::v2f32)
19479 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19481 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19483 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19484 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19485 DAG.getBitcast(MVT::v2i64, VBias));
19486 Or = DAG.getBitcast(MVT::v2f64, Or);
19487 // TODO: Are there any fast-math-flags to propagate here?
19488 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19489 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19492 case ISD::FP_ROUND: {
19493 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19495 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19496 Results.push_back(V);
19499 case ISD::FP_EXTEND: {
19500 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19501 // No other ValueType for FP_EXTEND should reach this point.
19502 assert(N->getValueType(0) == MVT::v2f32 &&
19503 "Do not know how to legalize this Node");
19506 case ISD::INTRINSIC_W_CHAIN: {
19507 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19509 default : llvm_unreachable("Do not know how to custom type "
19510 "legalize this intrinsic operation!");
19511 case Intrinsic::x86_rdtsc:
19512 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19514 case Intrinsic::x86_rdtscp:
19515 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19517 case Intrinsic::x86_rdpmc:
19518 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19521 case ISD::READCYCLECOUNTER: {
19522 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19525 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19526 EVT T = N->getValueType(0);
19527 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19528 bool Regs64bit = T == MVT::i128;
19529 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19530 SDValue cpInL, cpInH;
19531 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19532 DAG.getConstant(0, dl, HalfT));
19533 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19534 DAG.getConstant(1, dl, HalfT));
19535 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19536 Regs64bit ? X86::RAX : X86::EAX,
19538 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19539 Regs64bit ? X86::RDX : X86::EDX,
19540 cpInH, cpInL.getValue(1));
19541 SDValue swapInL, swapInH;
19542 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19543 DAG.getConstant(0, dl, HalfT));
19544 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19545 DAG.getConstant(1, dl, HalfT));
19546 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19547 Regs64bit ? X86::RBX : X86::EBX,
19548 swapInL, cpInH.getValue(1));
19549 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19550 Regs64bit ? X86::RCX : X86::ECX,
19551 swapInH, swapInL.getValue(1));
19552 SDValue Ops[] = { swapInH.getValue(0),
19554 swapInH.getValue(1) };
19555 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19556 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19557 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19558 X86ISD::LCMPXCHG8_DAG;
19559 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19560 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19561 Regs64bit ? X86::RAX : X86::EAX,
19562 HalfT, Result.getValue(1));
19563 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19564 Regs64bit ? X86::RDX : X86::EDX,
19565 HalfT, cpOutL.getValue(2));
19566 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19568 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19569 MVT::i32, cpOutH.getValue(2));
19571 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19572 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19573 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19575 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19576 Results.push_back(Success);
19577 Results.push_back(EFLAGS.getValue(1));
19580 case ISD::ATOMIC_SWAP:
19581 case ISD::ATOMIC_LOAD_ADD:
19582 case ISD::ATOMIC_LOAD_SUB:
19583 case ISD::ATOMIC_LOAD_AND:
19584 case ISD::ATOMIC_LOAD_OR:
19585 case ISD::ATOMIC_LOAD_XOR:
19586 case ISD::ATOMIC_LOAD_NAND:
19587 case ISD::ATOMIC_LOAD_MIN:
19588 case ISD::ATOMIC_LOAD_MAX:
19589 case ISD::ATOMIC_LOAD_UMIN:
19590 case ISD::ATOMIC_LOAD_UMAX:
19591 case ISD::ATOMIC_LOAD: {
19592 // Delegate to generic TypeLegalization. Situations we can really handle
19593 // should have already been dealt with by AtomicExpandPass.cpp.
19596 case ISD::BITCAST: {
19597 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19598 EVT DstVT = N->getValueType(0);
19599 EVT SrcVT = N->getOperand(0)->getValueType(0);
19601 if (SrcVT != MVT::f64 ||
19602 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19605 unsigned NumElts = DstVT.getVectorNumElements();
19606 EVT SVT = DstVT.getVectorElementType();
19607 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19608 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19609 MVT::v2f64, N->getOperand(0));
19610 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19612 if (ExperimentalVectorWideningLegalization) {
19613 // If we are legalizing vectors by widening, we already have the desired
19614 // legal vector type, just return it.
19615 Results.push_back(ToVecInt);
19619 SmallVector<SDValue, 8> Elts;
19620 for (unsigned i = 0, e = NumElts; i != e; ++i)
19621 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19622 ToVecInt, DAG.getIntPtrConstant(i, dl)));
19624 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19629 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19630 switch ((X86ISD::NodeType)Opcode) {
19631 case X86ISD::FIRST_NUMBER: break;
19632 case X86ISD::BSF: return "X86ISD::BSF";
19633 case X86ISD::BSR: return "X86ISD::BSR";
19634 case X86ISD::SHLD: return "X86ISD::SHLD";
19635 case X86ISD::SHRD: return "X86ISD::SHRD";
19636 case X86ISD::FAND: return "X86ISD::FAND";
19637 case X86ISD::FANDN: return "X86ISD::FANDN";
19638 case X86ISD::FOR: return "X86ISD::FOR";
19639 case X86ISD::FXOR: return "X86ISD::FXOR";
19640 case X86ISD::FILD: return "X86ISD::FILD";
19641 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
19642 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19643 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19644 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19645 case X86ISD::FLD: return "X86ISD::FLD";
19646 case X86ISD::FST: return "X86ISD::FST";
19647 case X86ISD::CALL: return "X86ISD::CALL";
19648 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
19649 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
19650 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
19651 case X86ISD::BT: return "X86ISD::BT";
19652 case X86ISD::CMP: return "X86ISD::CMP";
19653 case X86ISD::COMI: return "X86ISD::COMI";
19654 case X86ISD::UCOMI: return "X86ISD::UCOMI";
19655 case X86ISD::CMPM: return "X86ISD::CMPM";
19656 case X86ISD::CMPMU: return "X86ISD::CMPMU";
19657 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
19658 case X86ISD::SETCC: return "X86ISD::SETCC";
19659 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
19660 case X86ISD::FSETCC: return "X86ISD::FSETCC";
19661 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
19662 case X86ISD::CMOV: return "X86ISD::CMOV";
19663 case X86ISD::BRCOND: return "X86ISD::BRCOND";
19664 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
19665 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
19666 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
19667 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
19668 case X86ISD::Wrapper: return "X86ISD::Wrapper";
19669 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
19670 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
19671 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
19672 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
19673 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
19674 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
19675 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
19676 case X86ISD::PINSRB: return "X86ISD::PINSRB";
19677 case X86ISD::PINSRW: return "X86ISD::PINSRW";
19678 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
19679 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
19680 case X86ISD::ANDNP: return "X86ISD::ANDNP";
19681 case X86ISD::PSIGN: return "X86ISD::PSIGN";
19682 case X86ISD::BLENDI: return "X86ISD::BLENDI";
19683 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
19684 case X86ISD::ADDUS: return "X86ISD::ADDUS";
19685 case X86ISD::SUBUS: return "X86ISD::SUBUS";
19686 case X86ISD::HADD: return "X86ISD::HADD";
19687 case X86ISD::HSUB: return "X86ISD::HSUB";
19688 case X86ISD::FHADD: return "X86ISD::FHADD";
19689 case X86ISD::FHSUB: return "X86ISD::FHSUB";
19690 case X86ISD::ABS: return "X86ISD::ABS";
19691 case X86ISD::CONFLICT: return "X86ISD::CONFLICT";
19692 case X86ISD::FMAX: return "X86ISD::FMAX";
19693 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
19694 case X86ISD::FMIN: return "X86ISD::FMIN";
19695 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
19696 case X86ISD::FMAXC: return "X86ISD::FMAXC";
19697 case X86ISD::FMINC: return "X86ISD::FMINC";
19698 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
19699 case X86ISD::FRCP: return "X86ISD::FRCP";
19700 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
19701 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
19702 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
19703 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
19704 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
19705 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
19706 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
19707 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
19708 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
19709 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
19710 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
19711 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
19712 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
19713 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
19714 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
19715 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
19716 case X86ISD::VZEXT: return "X86ISD::VZEXT";
19717 case X86ISD::VSEXT: return "X86ISD::VSEXT";
19718 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
19719 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
19720 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
19721 case X86ISD::VINSERT: return "X86ISD::VINSERT";
19722 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
19723 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
19724 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
19725 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
19726 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
19727 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
19728 case X86ISD::VSHL: return "X86ISD::VSHL";
19729 case X86ISD::VSRL: return "X86ISD::VSRL";
19730 case X86ISD::VSRA: return "X86ISD::VSRA";
19731 case X86ISD::VSHLI: return "X86ISD::VSHLI";
19732 case X86ISD::VSRLI: return "X86ISD::VSRLI";
19733 case X86ISD::VSRAI: return "X86ISD::VSRAI";
19734 case X86ISD::CMPP: return "X86ISD::CMPP";
19735 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
19736 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
19737 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
19738 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
19739 case X86ISD::ADD: return "X86ISD::ADD";
19740 case X86ISD::SUB: return "X86ISD::SUB";
19741 case X86ISD::ADC: return "X86ISD::ADC";
19742 case X86ISD::SBB: return "X86ISD::SBB";
19743 case X86ISD::SMUL: return "X86ISD::SMUL";
19744 case X86ISD::UMUL: return "X86ISD::UMUL";
19745 case X86ISD::SMUL8: return "X86ISD::SMUL8";
19746 case X86ISD::UMUL8: return "X86ISD::UMUL8";
19747 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19748 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19749 case X86ISD::INC: return "X86ISD::INC";
19750 case X86ISD::DEC: return "X86ISD::DEC";
19751 case X86ISD::OR: return "X86ISD::OR";
19752 case X86ISD::XOR: return "X86ISD::XOR";
19753 case X86ISD::AND: return "X86ISD::AND";
19754 case X86ISD::BEXTR: return "X86ISD::BEXTR";
19755 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
19756 case X86ISD::PTEST: return "X86ISD::PTEST";
19757 case X86ISD::TESTP: return "X86ISD::TESTP";
19758 case X86ISD::TESTM: return "X86ISD::TESTM";
19759 case X86ISD::TESTNM: return "X86ISD::TESTNM";
19760 case X86ISD::KORTEST: return "X86ISD::KORTEST";
19761 case X86ISD::KTEST: return "X86ISD::KTEST";
19762 case X86ISD::PACKSS: return "X86ISD::PACKSS";
19763 case X86ISD::PACKUS: return "X86ISD::PACKUS";
19764 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
19765 case X86ISD::VALIGN: return "X86ISD::VALIGN";
19766 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
19767 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
19768 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
19769 case X86ISD::SHUFP: return "X86ISD::SHUFP";
19770 case X86ISD::SHUF128: return "X86ISD::SHUF128";
19771 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
19772 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
19773 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
19774 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
19775 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
19776 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
19777 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
19778 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
19779 case X86ISD::MOVSD: return "X86ISD::MOVSD";
19780 case X86ISD::MOVSS: return "X86ISD::MOVSS";
19781 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
19782 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
19783 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
19784 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
19785 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
19786 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
19787 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
19788 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
19789 case X86ISD::VPERMV: return "X86ISD::VPERMV";
19790 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
19791 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
19792 case X86ISD::VPERMI: return "X86ISD::VPERMI";
19793 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
19794 case X86ISD::VRANGE: return "X86ISD::VRANGE";
19795 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
19796 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
19797 case X86ISD::PSADBW: return "X86ISD::PSADBW";
19798 case X86ISD::DBPSADBW: return "X86ISD::DBPSADBW";
19799 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19800 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
19801 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
19802 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
19803 case X86ISD::MFENCE: return "X86ISD::MFENCE";
19804 case X86ISD::SFENCE: return "X86ISD::SFENCE";
19805 case X86ISD::LFENCE: return "X86ISD::LFENCE";
19806 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
19807 case X86ISD::SAHF: return "X86ISD::SAHF";
19808 case X86ISD::RDRAND: return "X86ISD::RDRAND";
19809 case X86ISD::RDSEED: return "X86ISD::RDSEED";
19810 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
19811 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
19812 case X86ISD::FMADD: return "X86ISD::FMADD";
19813 case X86ISD::FMSUB: return "X86ISD::FMSUB";
19814 case X86ISD::FNMADD: return "X86ISD::FNMADD";
19815 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
19816 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
19817 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
19818 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
19819 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
19820 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
19821 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
19822 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
19823 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
19824 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
19825 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
19826 case X86ISD::VGETMANT: return "X86ISD::VGETMANT";
19827 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
19828 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
19829 case X86ISD::XTEST: return "X86ISD::XTEST";
19830 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
19831 case X86ISD::EXPAND: return "X86ISD::EXPAND";
19832 case X86ISD::SELECT: return "X86ISD::SELECT";
19833 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
19834 case X86ISD::RCP28: return "X86ISD::RCP28";
19835 case X86ISD::EXP2: return "X86ISD::EXP2";
19836 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
19837 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
19838 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
19839 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
19840 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
19841 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
19842 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
19843 case X86ISD::SCALEF: return "X86ISD::SCALEF";
19844 case X86ISD::ADDS: return "X86ISD::ADDS";
19845 case X86ISD::SUBS: return "X86ISD::SUBS";
19846 case X86ISD::AVG: return "X86ISD::AVG";
19847 case X86ISD::MULHRS: return "X86ISD::MULHRS";
19848 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
19849 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
19850 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
19851 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
19852 case X86ISD::VFPCLASS: return "X86ISD::VFPCLASS";
19857 // isLegalAddressingMode - Return true if the addressing mode represented
19858 // by AM is legal for this target, for a load/store of the specified type.
19859 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19860 const AddrMode &AM, Type *Ty,
19861 unsigned AS) const {
19862 // X86 supports extremely general addressing modes.
19863 CodeModel::Model M = getTargetMachine().getCodeModel();
19864 Reloc::Model R = getTargetMachine().getRelocationModel();
19866 // X86 allows a sign-extended 32-bit immediate field as a displacement.
19867 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19872 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19874 // If a reference to this global requires an extra load, we can't fold it.
19875 if (isGlobalStubReference(GVFlags))
19878 // If BaseGV requires a register for the PIC base, we cannot also have a
19879 // BaseReg specified.
19880 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19883 // If lower 4G is not available, then we must use rip-relative addressing.
19884 if ((M != CodeModel::Small || R != Reloc::Static) &&
19885 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19889 switch (AM.Scale) {
19895 // These scales always work.
19900 // These scales are formed with basereg+scalereg. Only accept if there is
19905 default: // Other stuff never works.
19912 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19913 unsigned Bits = Ty->getScalarSizeInBits();
19915 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19916 // particularly cheaper than those without.
19920 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19921 // variable shifts just as cheap as scalar ones.
19922 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19925 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19926 // fully general vector.
19930 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19931 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19933 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19934 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19935 return NumBits1 > NumBits2;
19938 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19939 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19942 if (!isTypeLegal(EVT::getEVT(Ty1)))
19945 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19947 // Assuming the caller doesn't have a zeroext or signext return parameter,
19948 // truncation all the way down to i1 is valid.
19952 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19953 return isInt<32>(Imm);
19956 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19957 // Can also use sub to handle negated immediates.
19958 return isInt<32>(Imm);
19961 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19962 if (!VT1.isInteger() || !VT2.isInteger())
19964 unsigned NumBits1 = VT1.getSizeInBits();
19965 unsigned NumBits2 = VT2.getSizeInBits();
19966 return NumBits1 > NumBits2;
19969 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19970 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19971 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19974 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19975 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19976 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19979 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19980 EVT VT1 = Val.getValueType();
19981 if (isZExtFree(VT1, VT2))
19984 if (Val.getOpcode() != ISD::LOAD)
19987 if (!VT1.isSimple() || !VT1.isInteger() ||
19988 !VT2.isSimple() || !VT2.isInteger())
19991 switch (VT1.getSimpleVT().SimpleTy) {
19996 // X86 has 8, 16, and 32-bit zero-extending loads.
20003 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20006 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20007 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
20010 VT = VT.getScalarType();
20012 if (!VT.isSimple())
20015 switch (VT.getSimpleVT().SimpleTy) {
20026 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20027 // i16 instructions are longer (0x66 prefix) and potentially slower.
20028 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20031 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20032 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20033 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20034 /// are assumed to be legal.
20036 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20038 if (!VT.isSimple())
20041 // Not for i1 vectors
20042 if (VT.getScalarType() == MVT::i1)
20045 // Very little shuffling can be done for 64-bit vectors right now.
20046 if (VT.getSizeInBits() == 64)
20049 // We only care that the types being shuffled are legal. The lowering can
20050 // handle any possible shuffle mask that results.
20051 return isTypeLegal(VT.getSimpleVT());
20055 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20057 // Just delegate to the generic legality, clear masks aren't special.
20058 return isShuffleMaskLegal(Mask, VT);
20061 //===----------------------------------------------------------------------===//
20062 // X86 Scheduler Hooks
20063 //===----------------------------------------------------------------------===//
20065 /// Utility function to emit xbegin specifying the start of an RTM region.
20066 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20067 const TargetInstrInfo *TII) {
20068 DebugLoc DL = MI->getDebugLoc();
20070 const BasicBlock *BB = MBB->getBasicBlock();
20071 MachineFunction::iterator I = MBB;
20074 // For the v = xbegin(), we generate
20085 MachineBasicBlock *thisMBB = MBB;
20086 MachineFunction *MF = MBB->getParent();
20087 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20088 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20089 MF->insert(I, mainMBB);
20090 MF->insert(I, sinkMBB);
20092 // Transfer the remainder of BB and its successor edges to sinkMBB.
20093 sinkMBB->splice(sinkMBB->begin(), MBB,
20094 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20095 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20099 // # fallthrough to mainMBB
20100 // # abortion to sinkMBB
20101 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20102 thisMBB->addSuccessor(mainMBB);
20103 thisMBB->addSuccessor(sinkMBB);
20107 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20108 mainMBB->addSuccessor(sinkMBB);
20111 // EAX is live into the sinkMBB
20112 sinkMBB->addLiveIn(X86::EAX);
20113 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20114 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20117 MI->eraseFromParent();
20121 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20122 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20123 // in the .td file.
20124 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20125 const TargetInstrInfo *TII) {
20127 switch (MI->getOpcode()) {
20128 default: llvm_unreachable("illegal opcode!");
20129 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
20130 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20131 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
20132 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20133 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
20134 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20135 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
20136 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20139 DebugLoc dl = MI->getDebugLoc();
20140 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20142 unsigned NumArgs = MI->getNumOperands();
20143 for (unsigned i = 1; i < NumArgs; ++i) {
20144 MachineOperand &Op = MI->getOperand(i);
20145 if (!(Op.isReg() && Op.isImplicit()))
20146 MIB.addOperand(Op);
20148 if (MI->hasOneMemOperand())
20149 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20151 BuildMI(*BB, MI, dl,
20152 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20153 .addReg(X86::XMM0);
20155 MI->eraseFromParent();
20159 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20160 // defs in an instruction pattern
20161 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20162 const TargetInstrInfo *TII) {
20164 switch (MI->getOpcode()) {
20165 default: llvm_unreachable("illegal opcode!");
20166 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
20167 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20168 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
20169 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20170 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
20171 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20172 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
20173 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20176 DebugLoc dl = MI->getDebugLoc();
20177 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20179 unsigned NumArgs = MI->getNumOperands(); // remove the results
20180 for (unsigned i = 1; i < NumArgs; ++i) {
20181 MachineOperand &Op = MI->getOperand(i);
20182 if (!(Op.isReg() && Op.isImplicit()))
20183 MIB.addOperand(Op);
20185 if (MI->hasOneMemOperand())
20186 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20188 BuildMI(*BB, MI, dl,
20189 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20192 MI->eraseFromParent();
20196 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20197 const X86Subtarget *Subtarget) {
20198 DebugLoc dl = MI->getDebugLoc();
20199 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20200 // Address into RAX/EAX, other two args into ECX, EDX.
20201 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20202 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20203 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20204 for (int i = 0; i < X86::AddrNumOperands; ++i)
20205 MIB.addOperand(MI->getOperand(i));
20207 unsigned ValOps = X86::AddrNumOperands;
20208 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20209 .addReg(MI->getOperand(ValOps).getReg());
20210 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20211 .addReg(MI->getOperand(ValOps+1).getReg());
20213 // The instruction doesn't actually take any operands though.
20214 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20216 MI->eraseFromParent(); // The pseudo is gone now.
20220 MachineBasicBlock *
20221 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20222 MachineBasicBlock *MBB) const {
20223 // Emit va_arg instruction on X86-64.
20225 // Operands to this pseudo-instruction:
20226 // 0 ) Output : destination address (reg)
20227 // 1-5) Input : va_list address (addr, i64mem)
20228 // 6 ) ArgSize : Size (in bytes) of vararg type
20229 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20230 // 8 ) Align : Alignment of type
20231 // 9 ) EFLAGS (implicit-def)
20233 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20234 static_assert(X86::AddrNumOperands == 5,
20235 "VAARG_64 assumes 5 address operands");
20237 unsigned DestReg = MI->getOperand(0).getReg();
20238 MachineOperand &Base = MI->getOperand(1);
20239 MachineOperand &Scale = MI->getOperand(2);
20240 MachineOperand &Index = MI->getOperand(3);
20241 MachineOperand &Disp = MI->getOperand(4);
20242 MachineOperand &Segment = MI->getOperand(5);
20243 unsigned ArgSize = MI->getOperand(6).getImm();
20244 unsigned ArgMode = MI->getOperand(7).getImm();
20245 unsigned Align = MI->getOperand(8).getImm();
20247 // Memory Reference
20248 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20249 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20250 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20252 // Machine Information
20253 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20254 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20255 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20256 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20257 DebugLoc DL = MI->getDebugLoc();
20259 // struct va_list {
20262 // i64 overflow_area (address)
20263 // i64 reg_save_area (address)
20265 // sizeof(va_list) = 24
20266 // alignment(va_list) = 8
20268 unsigned TotalNumIntRegs = 6;
20269 unsigned TotalNumXMMRegs = 8;
20270 bool UseGPOffset = (ArgMode == 1);
20271 bool UseFPOffset = (ArgMode == 2);
20272 unsigned MaxOffset = TotalNumIntRegs * 8 +
20273 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20275 /* Align ArgSize to a multiple of 8 */
20276 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20277 bool NeedsAlign = (Align > 8);
20279 MachineBasicBlock *thisMBB = MBB;
20280 MachineBasicBlock *overflowMBB;
20281 MachineBasicBlock *offsetMBB;
20282 MachineBasicBlock *endMBB;
20284 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
20285 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
20286 unsigned OffsetReg = 0;
20288 if (!UseGPOffset && !UseFPOffset) {
20289 // If we only pull from the overflow region, we don't create a branch.
20290 // We don't need to alter control flow.
20291 OffsetDestReg = 0; // unused
20292 OverflowDestReg = DestReg;
20294 offsetMBB = nullptr;
20295 overflowMBB = thisMBB;
20298 // First emit code to check if gp_offset (or fp_offset) is below the bound.
20299 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20300 // If not, pull from overflow_area. (branch to overflowMBB)
20305 // offsetMBB overflowMBB
20310 // Registers for the PHI in endMBB
20311 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20312 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20314 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20315 MachineFunction *MF = MBB->getParent();
20316 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20317 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20318 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20320 MachineFunction::iterator MBBIter = MBB;
20323 // Insert the new basic blocks
20324 MF->insert(MBBIter, offsetMBB);
20325 MF->insert(MBBIter, overflowMBB);
20326 MF->insert(MBBIter, endMBB);
20328 // Transfer the remainder of MBB and its successor edges to endMBB.
20329 endMBB->splice(endMBB->begin(), thisMBB,
20330 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20331 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20333 // Make offsetMBB and overflowMBB successors of thisMBB
20334 thisMBB->addSuccessor(offsetMBB);
20335 thisMBB->addSuccessor(overflowMBB);
20337 // endMBB is a successor of both offsetMBB and overflowMBB
20338 offsetMBB->addSuccessor(endMBB);
20339 overflowMBB->addSuccessor(endMBB);
20341 // Load the offset value into a register
20342 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20343 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20347 .addDisp(Disp, UseFPOffset ? 4 : 0)
20348 .addOperand(Segment)
20349 .setMemRefs(MMOBegin, MMOEnd);
20351 // Check if there is enough room left to pull this argument.
20352 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20354 .addImm(MaxOffset + 8 - ArgSizeA8);
20356 // Branch to "overflowMBB" if offset >= max
20357 // Fall through to "offsetMBB" otherwise
20358 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20359 .addMBB(overflowMBB);
20362 // In offsetMBB, emit code to use the reg_save_area.
20364 assert(OffsetReg != 0);
20366 // Read the reg_save_area address.
20367 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20368 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20373 .addOperand(Segment)
20374 .setMemRefs(MMOBegin, MMOEnd);
20376 // Zero-extend the offset
20377 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20378 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20381 .addImm(X86::sub_32bit);
20383 // Add the offset to the reg_save_area to get the final address.
20384 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20385 .addReg(OffsetReg64)
20386 .addReg(RegSaveReg);
20388 // Compute the offset for the next argument
20389 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20390 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20392 .addImm(UseFPOffset ? 16 : 8);
20394 // Store it back into the va_list.
20395 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20399 .addDisp(Disp, UseFPOffset ? 4 : 0)
20400 .addOperand(Segment)
20401 .addReg(NextOffsetReg)
20402 .setMemRefs(MMOBegin, MMOEnd);
20405 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20410 // Emit code to use overflow area
20413 // Load the overflow_area address into a register.
20414 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20415 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20420 .addOperand(Segment)
20421 .setMemRefs(MMOBegin, MMOEnd);
20423 // If we need to align it, do so. Otherwise, just copy the address
20424 // to OverflowDestReg.
20426 // Align the overflow address
20427 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20428 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20430 // aligned_addr = (addr + (align-1)) & ~(align-1)
20431 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20432 .addReg(OverflowAddrReg)
20435 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20437 .addImm(~(uint64_t)(Align-1));
20439 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20440 .addReg(OverflowAddrReg);
20443 // Compute the next overflow address after this argument.
20444 // (the overflow address should be kept 8-byte aligned)
20445 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20446 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20447 .addReg(OverflowDestReg)
20448 .addImm(ArgSizeA8);
20450 // Store the new overflow address.
20451 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20456 .addOperand(Segment)
20457 .addReg(NextAddrReg)
20458 .setMemRefs(MMOBegin, MMOEnd);
20460 // If we branched, emit the PHI to the front of endMBB.
20462 BuildMI(*endMBB, endMBB->begin(), DL,
20463 TII->get(X86::PHI), DestReg)
20464 .addReg(OffsetDestReg).addMBB(offsetMBB)
20465 .addReg(OverflowDestReg).addMBB(overflowMBB);
20468 // Erase the pseudo instruction
20469 MI->eraseFromParent();
20474 MachineBasicBlock *
20475 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20477 MachineBasicBlock *MBB) const {
20478 // Emit code to save XMM registers to the stack. The ABI says that the
20479 // number of registers to save is given in %al, so it's theoretically
20480 // possible to do an indirect jump trick to avoid saving all of them,
20481 // however this code takes a simpler approach and just executes all
20482 // of the stores if %al is non-zero. It's less code, and it's probably
20483 // easier on the hardware branch predictor, and stores aren't all that
20484 // expensive anyway.
20486 // Create the new basic blocks. One block contains all the XMM stores,
20487 // and one block is the final destination regardless of whether any
20488 // stores were performed.
20489 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20490 MachineFunction *F = MBB->getParent();
20491 MachineFunction::iterator MBBIter = MBB;
20493 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20494 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20495 F->insert(MBBIter, XMMSaveMBB);
20496 F->insert(MBBIter, EndMBB);
20498 // Transfer the remainder of MBB and its successor edges to EndMBB.
20499 EndMBB->splice(EndMBB->begin(), MBB,
20500 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20501 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20503 // The original block will now fall through to the XMM save block.
20504 MBB->addSuccessor(XMMSaveMBB);
20505 // The XMMSaveMBB will fall through to the end block.
20506 XMMSaveMBB->addSuccessor(EndMBB);
20508 // Now add the instructions.
20509 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20510 DebugLoc DL = MI->getDebugLoc();
20512 unsigned CountReg = MI->getOperand(0).getReg();
20513 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20514 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20516 if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20517 // If %al is 0, branch around the XMM save block.
20518 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20519 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20520 MBB->addSuccessor(EndMBB);
20523 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20524 // that was just emitted, but clearly shouldn't be "saved".
20525 assert((MI->getNumOperands() <= 3 ||
20526 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20527 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20528 && "Expected last argument to be EFLAGS");
20529 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20530 // In the XMM save block, save all the XMM argument registers.
20531 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20532 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20533 MachineMemOperand *MMO = F->getMachineMemOperand(
20534 MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20535 MachineMemOperand::MOStore,
20536 /*Size=*/16, /*Align=*/16);
20537 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20538 .addFrameIndex(RegSaveFrameIndex)
20539 .addImm(/*Scale=*/1)
20540 .addReg(/*IndexReg=*/0)
20541 .addImm(/*Disp=*/Offset)
20542 .addReg(/*Segment=*/0)
20543 .addReg(MI->getOperand(i).getReg())
20544 .addMemOperand(MMO);
20547 MI->eraseFromParent(); // The pseudo instruction is gone now.
20552 // The EFLAGS operand of SelectItr might be missing a kill marker
20553 // because there were multiple uses of EFLAGS, and ISel didn't know
20554 // which to mark. Figure out whether SelectItr should have had a
20555 // kill marker, and set it if it should. Returns the correct kill
20557 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20558 MachineBasicBlock* BB,
20559 const TargetRegisterInfo* TRI) {
20560 // Scan forward through BB for a use/def of EFLAGS.
20561 MachineBasicBlock::iterator miI(std::next(SelectItr));
20562 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20563 const MachineInstr& mi = *miI;
20564 if (mi.readsRegister(X86::EFLAGS))
20566 if (mi.definesRegister(X86::EFLAGS))
20567 break; // Should have kill-flag - update below.
20570 // If we hit the end of the block, check whether EFLAGS is live into a
20572 if (miI == BB->end()) {
20573 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20574 sEnd = BB->succ_end();
20575 sItr != sEnd; ++sItr) {
20576 MachineBasicBlock* succ = *sItr;
20577 if (succ->isLiveIn(X86::EFLAGS))
20582 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20583 // out. SelectMI should have a kill flag on EFLAGS.
20584 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20588 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20589 // together with other CMOV pseudo-opcodes into a single basic-block with
20590 // conditional jump around it.
20591 static bool isCMOVPseudo(MachineInstr *MI) {
20592 switch (MI->getOpcode()) {
20593 case X86::CMOV_FR32:
20594 case X86::CMOV_FR64:
20595 case X86::CMOV_GR8:
20596 case X86::CMOV_GR16:
20597 case X86::CMOV_GR32:
20598 case X86::CMOV_RFP32:
20599 case X86::CMOV_RFP64:
20600 case X86::CMOV_RFP80:
20601 case X86::CMOV_V2F64:
20602 case X86::CMOV_V2I64:
20603 case X86::CMOV_V4F32:
20604 case X86::CMOV_V4F64:
20605 case X86::CMOV_V4I64:
20606 case X86::CMOV_V16F32:
20607 case X86::CMOV_V8F32:
20608 case X86::CMOV_V8F64:
20609 case X86::CMOV_V8I64:
20610 case X86::CMOV_V8I1:
20611 case X86::CMOV_V16I1:
20612 case X86::CMOV_V32I1:
20613 case X86::CMOV_V64I1:
20621 MachineBasicBlock *
20622 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20623 MachineBasicBlock *BB) const {
20624 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20625 DebugLoc DL = MI->getDebugLoc();
20627 // To "insert" a SELECT_CC instruction, we actually have to insert the
20628 // diamond control-flow pattern. The incoming instruction knows the
20629 // destination vreg to set, the condition code register to branch on, the
20630 // true/false values to select between, and a branch opcode to use.
20631 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20632 MachineFunction::iterator It = BB;
20638 // cmpTY ccX, r1, r2
20640 // fallthrough --> copy0MBB
20641 MachineBasicBlock *thisMBB = BB;
20642 MachineFunction *F = BB->getParent();
20644 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20645 // as described above, by inserting a BB, and then making a PHI at the join
20646 // point to select the true and false operands of the CMOV in the PHI.
20648 // The code also handles two different cases of multiple CMOV opcodes
20652 // In this case, there are multiple CMOVs in a row, all which are based on
20653 // the same condition setting (or the exact opposite condition setting).
20654 // In this case we can lower all the CMOVs using a single inserted BB, and
20655 // then make a number of PHIs at the join point to model the CMOVs. The only
20656 // trickiness here, is that in a case like:
20658 // t2 = CMOV cond1 t1, f1
20659 // t3 = CMOV cond1 t2, f2
20661 // when rewriting this into PHIs, we have to perform some renaming on the
20662 // temps since you cannot have a PHI operand refer to a PHI result earlier
20663 // in the same block. The "simple" but wrong lowering would be:
20665 // t2 = PHI t1(BB1), f1(BB2)
20666 // t3 = PHI t2(BB1), f2(BB2)
20668 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20669 // renaming is to note that on the path through BB1, t2 is really just a
20670 // copy of t1, and do that renaming, properly generating:
20672 // t2 = PHI t1(BB1), f1(BB2)
20673 // t3 = PHI t1(BB1), f2(BB2)
20675 // Case 2, we lower cascaded CMOVs such as
20677 // (CMOV (CMOV F, T, cc1), T, cc2)
20679 // to two successives branches. For that, we look for another CMOV as the
20680 // following instruction.
20682 // Without this, we would add a PHI between the two jumps, which ends up
20683 // creating a few copies all around. For instance, for
20685 // (sitofp (zext (fcmp une)))
20687 // we would generate:
20689 // ucomiss %xmm1, %xmm0
20690 // movss <1.0f>, %xmm0
20691 // movaps %xmm0, %xmm1
20693 // xorps %xmm1, %xmm1
20696 // movaps %xmm1, %xmm0
20700 // because this custom-inserter would have generated:
20712 // A: X = ...; Y = ...
20714 // C: Z = PHI [X, A], [Y, B]
20716 // E: PHI [X, C], [Z, D]
20718 // If we lower both CMOVs in a single step, we can instead generate:
20730 // A: X = ...; Y = ...
20732 // E: PHI [X, A], [X, C], [Y, D]
20734 // Which, in our sitofp/fcmp example, gives us something like:
20736 // ucomiss %xmm1, %xmm0
20737 // movss <1.0f>, %xmm0
20740 // xorps %xmm0, %xmm0
20744 MachineInstr *CascadedCMOV = nullptr;
20745 MachineInstr *LastCMOV = MI;
20746 X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20747 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20748 MachineBasicBlock::iterator NextMIIt =
20749 std::next(MachineBasicBlock::iterator(MI));
20751 // Check for case 1, where there are multiple CMOVs with the same condition
20752 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
20753 // number of jumps the most.
20755 if (isCMOVPseudo(MI)) {
20756 // See if we have a string of CMOVS with the same condition.
20757 while (NextMIIt != BB->end() &&
20758 isCMOVPseudo(NextMIIt) &&
20759 (NextMIIt->getOperand(3).getImm() == CC ||
20760 NextMIIt->getOperand(3).getImm() == OppCC)) {
20761 LastCMOV = &*NextMIIt;
20766 // This checks for case 2, but only do this if we didn't already find
20767 // case 1, as indicated by LastCMOV == MI.
20768 if (LastCMOV == MI &&
20769 NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20770 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20771 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20772 CascadedCMOV = &*NextMIIt;
20775 MachineBasicBlock *jcc1MBB = nullptr;
20777 // If we have a cascaded CMOV, we lower it to two successive branches to
20778 // the same block. EFLAGS is used by both, so mark it as live in the second.
20779 if (CascadedCMOV) {
20780 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20781 F->insert(It, jcc1MBB);
20782 jcc1MBB->addLiveIn(X86::EFLAGS);
20785 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20786 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20787 F->insert(It, copy0MBB);
20788 F->insert(It, sinkMBB);
20790 // If the EFLAGS register isn't dead in the terminator, then claim that it's
20791 // live into the sink and copy blocks.
20792 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20794 MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20795 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20796 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20797 copy0MBB->addLiveIn(X86::EFLAGS);
20798 sinkMBB->addLiveIn(X86::EFLAGS);
20801 // Transfer the remainder of BB and its successor edges to sinkMBB.
20802 sinkMBB->splice(sinkMBB->begin(), BB,
20803 std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20804 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20806 // Add the true and fallthrough blocks as its successors.
20807 if (CascadedCMOV) {
20808 // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20809 BB->addSuccessor(jcc1MBB);
20811 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20812 // jump to the sinkMBB.
20813 jcc1MBB->addSuccessor(copy0MBB);
20814 jcc1MBB->addSuccessor(sinkMBB);
20816 BB->addSuccessor(copy0MBB);
20819 // The true block target of the first (or only) branch is always sinkMBB.
20820 BB->addSuccessor(sinkMBB);
20822 // Create the conditional branch instruction.
20823 unsigned Opc = X86::GetCondBranchFromCond(CC);
20824 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20826 if (CascadedCMOV) {
20827 unsigned Opc2 = X86::GetCondBranchFromCond(
20828 (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20829 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20833 // %FalseValue = ...
20834 // # fallthrough to sinkMBB
20835 copy0MBB->addSuccessor(sinkMBB);
20838 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20840 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20841 MachineBasicBlock::iterator MIItEnd =
20842 std::next(MachineBasicBlock::iterator(LastCMOV));
20843 MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20844 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20845 MachineInstrBuilder MIB;
20847 // As we are creating the PHIs, we have to be careful if there is more than
20848 // one. Later CMOVs may reference the results of earlier CMOVs, but later
20849 // PHIs have to reference the individual true/false inputs from earlier PHIs.
20850 // That also means that PHI construction must work forward from earlier to
20851 // later, and that the code must maintain a mapping from earlier PHI's
20852 // destination registers, and the registers that went into the PHI.
20854 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20855 unsigned DestReg = MIIt->getOperand(0).getReg();
20856 unsigned Op1Reg = MIIt->getOperand(1).getReg();
20857 unsigned Op2Reg = MIIt->getOperand(2).getReg();
20859 // If this CMOV we are generating is the opposite condition from
20860 // the jump we generated, then we have to swap the operands for the
20861 // PHI that is going to be generated.
20862 if (MIIt->getOperand(3).getImm() == OppCC)
20863 std::swap(Op1Reg, Op2Reg);
20865 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20866 Op1Reg = RegRewriteTable[Op1Reg].first;
20868 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20869 Op2Reg = RegRewriteTable[Op2Reg].second;
20871 MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20872 TII->get(X86::PHI), DestReg)
20873 .addReg(Op1Reg).addMBB(copy0MBB)
20874 .addReg(Op2Reg).addMBB(thisMBB);
20876 // Add this PHI to the rewrite table.
20877 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20880 // If we have a cascaded CMOV, the second Jcc provides the same incoming
20881 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20882 if (CascadedCMOV) {
20883 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20884 // Copy the PHI result to the register defined by the second CMOV.
20885 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20886 DL, TII->get(TargetOpcode::COPY),
20887 CascadedCMOV->getOperand(0).getReg())
20888 .addReg(MI->getOperand(0).getReg());
20889 CascadedCMOV->eraseFromParent();
20892 // Now remove the CMOV(s).
20893 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20894 (MIIt++)->eraseFromParent();
20899 MachineBasicBlock *
20900 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20901 MachineBasicBlock *BB) const {
20902 // Combine the following atomic floating-point modification pattern:
20903 // a.store(reg OP a.load(acquire), release)
20904 // Transform them into:
20905 // OPss (%gpr), %xmm
20906 // movss %xmm, (%gpr)
20907 // Or sd equivalent for 64-bit operations.
20909 switch (MI->getOpcode()) {
20910 default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20911 case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20912 case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20914 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20915 DebugLoc DL = MI->getDebugLoc();
20916 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20917 unsigned MSrc = MI->getOperand(0).getReg();
20918 unsigned VSrc = MI->getOperand(5).getReg();
20919 MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20920 .addReg(/*Base=*/MSrc)
20921 .addImm(/*Scale=*/1)
20922 .addReg(/*Index=*/0)
20925 MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20926 MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20928 .addReg(/*Base=*/MSrc)
20929 .addImm(/*Scale=*/1)
20930 .addReg(/*Index=*/0)
20931 .addImm(/*Disp=*/0)
20932 .addReg(/*Segment=*/0);
20933 MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20934 MI->eraseFromParent(); // The pseudo instruction is gone now.
20938 MachineBasicBlock *
20939 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20940 MachineBasicBlock *BB) const {
20941 MachineFunction *MF = BB->getParent();
20942 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20943 DebugLoc DL = MI->getDebugLoc();
20944 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20946 assert(MF->shouldSplitStack());
20948 const bool Is64Bit = Subtarget->is64Bit();
20949 const bool IsLP64 = Subtarget->isTarget64BitLP64();
20951 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20952 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20955 // ... [Till the alloca]
20956 // If stacklet is not large enough, jump to mallocMBB
20959 // Allocate by subtracting from RSP
20960 // Jump to continueMBB
20963 // Allocate by call to runtime
20967 // [rest of original BB]
20970 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20971 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20972 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20974 MachineRegisterInfo &MRI = MF->getRegInfo();
20975 const TargetRegisterClass *AddrRegClass =
20976 getRegClassFor(getPointerTy(MF->getDataLayout()));
20978 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20979 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20980 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20981 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20982 sizeVReg = MI->getOperand(1).getReg(),
20983 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20985 MachineFunction::iterator MBBIter = BB;
20988 MF->insert(MBBIter, bumpMBB);
20989 MF->insert(MBBIter, mallocMBB);
20990 MF->insert(MBBIter, continueMBB);
20992 continueMBB->splice(continueMBB->begin(), BB,
20993 std::next(MachineBasicBlock::iterator(MI)), BB->end());
20994 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20996 // Add code to the main basic block to check if the stack limit has been hit,
20997 // and if so, jump to mallocMBB otherwise to bumpMBB.
20998 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20999 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
21000 .addReg(tmpSPVReg).addReg(sizeVReg);
21001 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
21002 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
21003 .addReg(SPLimitVReg);
21004 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
21006 // bumpMBB simply decreases the stack pointer, since we know the current
21007 // stacklet has enough space.
21008 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
21009 .addReg(SPLimitVReg);
21010 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
21011 .addReg(SPLimitVReg);
21012 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21014 // Calls into a routine in libgcc to allocate more space from the heap.
21015 const uint32_t *RegMask =
21016 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
21018 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21020 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21021 .addExternalSymbol("__morestack_allocate_stack_space")
21022 .addRegMask(RegMask)
21023 .addReg(X86::RDI, RegState::Implicit)
21024 .addReg(X86::RAX, RegState::ImplicitDefine);
21025 } else if (Is64Bit) {
21026 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21028 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21029 .addExternalSymbol("__morestack_allocate_stack_space")
21030 .addRegMask(RegMask)
21031 .addReg(X86::EDI, RegState::Implicit)
21032 .addReg(X86::EAX, RegState::ImplicitDefine);
21034 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21036 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21037 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21038 .addExternalSymbol("__morestack_allocate_stack_space")
21039 .addRegMask(RegMask)
21040 .addReg(X86::EAX, RegState::ImplicitDefine);
21044 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21047 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21048 .addReg(IsLP64 ? X86::RAX : X86::EAX);
21049 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21051 // Set up the CFG correctly.
21052 BB->addSuccessor(bumpMBB);
21053 BB->addSuccessor(mallocMBB);
21054 mallocMBB->addSuccessor(continueMBB);
21055 bumpMBB->addSuccessor(continueMBB);
21057 // Take care of the PHI nodes.
21058 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21059 MI->getOperand(0).getReg())
21060 .addReg(mallocPtrVReg).addMBB(mallocMBB)
21061 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21063 // Delete the original pseudo instruction.
21064 MI->eraseFromParent();
21067 return continueMBB;
21070 MachineBasicBlock *
21071 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21072 MachineBasicBlock *BB) const {
21073 DebugLoc DL = MI->getDebugLoc();
21075 assert(!Subtarget->isTargetMachO());
21077 Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
21080 MI->eraseFromParent(); // The pseudo instruction is gone now.
21084 MachineBasicBlock *
21085 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
21086 MachineBasicBlock *BB) const {
21087 // This is pretty easy. We're taking the value that we received from
21088 // our load from the relocation, sticking it in either RDI (x86-64)
21089 // or EAX and doing an indirect call. The return value will then
21090 // be in the normal return register.
21091 MachineFunction *F = BB->getParent();
21092 const X86InstrInfo *TII = Subtarget->getInstrInfo();
21093 DebugLoc DL = MI->getDebugLoc();
21095 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
21096 assert(MI->getOperand(3).isGlobal() && "This should be a global");
21098 // Get a register mask for the lowered call.
21099 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
21100 // proper register mask.
21101 const uint32_t *RegMask =
21102 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
21103 if (Subtarget->is64Bit()) {
21104 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21105 TII->get(X86::MOV64rm), X86::RDI)
21107 .addImm(0).addReg(0)
21108 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21109 MI->getOperand(3).getTargetFlags())
21111 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21112 addDirectMem(MIB, X86::RDI);
21113 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21114 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21115 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21116 TII->get(X86::MOV32rm), X86::EAX)
21118 .addImm(0).addReg(0)
21119 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21120 MI->getOperand(3).getTargetFlags())
21122 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21123 addDirectMem(MIB, X86::EAX);
21124 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21126 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21127 TII->get(X86::MOV32rm), X86::EAX)
21128 .addReg(TII->getGlobalBaseReg(F))
21129 .addImm(0).addReg(0)
21130 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21131 MI->getOperand(3).getTargetFlags())
21133 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21134 addDirectMem(MIB, X86::EAX);
21135 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21138 MI->eraseFromParent(); // The pseudo instruction is gone now.
21142 MachineBasicBlock *
21143 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21144 MachineBasicBlock *MBB) const {
21145 DebugLoc DL = MI->getDebugLoc();
21146 MachineFunction *MF = MBB->getParent();
21147 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21148 MachineRegisterInfo &MRI = MF->getRegInfo();
21150 const BasicBlock *BB = MBB->getBasicBlock();
21151 MachineFunction::iterator I = MBB;
21154 // Memory Reference
21155 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21156 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21159 unsigned MemOpndSlot = 0;
21161 unsigned CurOp = 0;
21163 DstReg = MI->getOperand(CurOp++).getReg();
21164 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21165 assert(RC->hasType(MVT::i32) && "Invalid destination!");
21166 unsigned mainDstReg = MRI.createVirtualRegister(RC);
21167 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21169 MemOpndSlot = CurOp;
21171 MVT PVT = getPointerTy(MF->getDataLayout());
21172 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21173 "Invalid Pointer Size!");
21175 // For v = setjmp(buf), we generate
21178 // buf[LabelOffset] = restoreMBB
21179 // SjLjSetup restoreMBB
21185 // v = phi(main, restore)
21188 // if base pointer being used, load it from frame
21191 MachineBasicBlock *thisMBB = MBB;
21192 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21193 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21194 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21195 MF->insert(I, mainMBB);
21196 MF->insert(I, sinkMBB);
21197 MF->push_back(restoreMBB);
21199 MachineInstrBuilder MIB;
21201 // Transfer the remainder of BB and its successor edges to sinkMBB.
21202 sinkMBB->splice(sinkMBB->begin(), MBB,
21203 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21204 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21207 unsigned PtrStoreOpc = 0;
21208 unsigned LabelReg = 0;
21209 const int64_t LabelOffset = 1 * PVT.getStoreSize();
21210 Reloc::Model RM = MF->getTarget().getRelocationModel();
21211 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21212 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21214 // Prepare IP either in reg or imm.
21215 if (!UseImmLabel) {
21216 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21217 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21218 LabelReg = MRI.createVirtualRegister(PtrRC);
21219 if (Subtarget->is64Bit()) {
21220 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21224 .addMBB(restoreMBB)
21227 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21228 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21229 .addReg(XII->getGlobalBaseReg(MF))
21232 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21236 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21238 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21239 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21240 if (i == X86::AddrDisp)
21241 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21243 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21246 MIB.addReg(LabelReg);
21248 MIB.addMBB(restoreMBB);
21249 MIB.setMemRefs(MMOBegin, MMOEnd);
21251 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21252 .addMBB(restoreMBB);
21254 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21255 MIB.addRegMask(RegInfo->getNoPreservedMask());
21256 thisMBB->addSuccessor(mainMBB);
21257 thisMBB->addSuccessor(restoreMBB);
21261 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21262 mainMBB->addSuccessor(sinkMBB);
21265 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21266 TII->get(X86::PHI), DstReg)
21267 .addReg(mainDstReg).addMBB(mainMBB)
21268 .addReg(restoreDstReg).addMBB(restoreMBB);
21271 if (RegInfo->hasBasePointer(*MF)) {
21272 const bool Uses64BitFramePtr =
21273 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21274 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21275 X86FI->setRestoreBasePointer(MF);
21276 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21277 unsigned BasePtr = RegInfo->getBaseRegister();
21278 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21279 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21280 FramePtr, true, X86FI->getRestoreBasePointerOffset())
21281 .setMIFlag(MachineInstr::FrameSetup);
21283 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21284 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21285 restoreMBB->addSuccessor(sinkMBB);
21287 MI->eraseFromParent();
21291 MachineBasicBlock *
21292 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21293 MachineBasicBlock *MBB) const {
21294 DebugLoc DL = MI->getDebugLoc();
21295 MachineFunction *MF = MBB->getParent();
21296 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21297 MachineRegisterInfo &MRI = MF->getRegInfo();
21299 // Memory Reference
21300 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21301 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21303 MVT PVT = getPointerTy(MF->getDataLayout());
21304 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21305 "Invalid Pointer Size!");
21307 const TargetRegisterClass *RC =
21308 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21309 unsigned Tmp = MRI.createVirtualRegister(RC);
21310 // Since FP is only updated here but NOT referenced, it's treated as GPR.
21311 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21312 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21313 unsigned SP = RegInfo->getStackRegister();
21315 MachineInstrBuilder MIB;
21317 const int64_t LabelOffset = 1 * PVT.getStoreSize();
21318 const int64_t SPOffset = 2 * PVT.getStoreSize();
21320 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21321 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21324 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21325 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21326 MIB.addOperand(MI->getOperand(i));
21327 MIB.setMemRefs(MMOBegin, MMOEnd);
21329 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21330 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21331 if (i == X86::AddrDisp)
21332 MIB.addDisp(MI->getOperand(i), LabelOffset);
21334 MIB.addOperand(MI->getOperand(i));
21336 MIB.setMemRefs(MMOBegin, MMOEnd);
21338 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21339 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21340 if (i == X86::AddrDisp)
21341 MIB.addDisp(MI->getOperand(i), SPOffset);
21343 MIB.addOperand(MI->getOperand(i));
21345 MIB.setMemRefs(MMOBegin, MMOEnd);
21347 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21349 MI->eraseFromParent();
21353 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21354 // accumulator loops. Writing back to the accumulator allows the coalescer
21355 // to remove extra copies in the loop.
21356 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
21357 MachineBasicBlock *
21358 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21359 MachineBasicBlock *MBB) const {
21360 MachineOperand &AddendOp = MI->getOperand(3);
21362 // Bail out early if the addend isn't a register - we can't switch these.
21363 if (!AddendOp.isReg())
21366 MachineFunction &MF = *MBB->getParent();
21367 MachineRegisterInfo &MRI = MF.getRegInfo();
21369 // Check whether the addend is defined by a PHI:
21370 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21371 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21372 if (!AddendDef.isPHI())
21375 // Look for the following pattern:
21377 // %addend = phi [%entry, 0], [%loop, %result]
21379 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21383 // %addend = phi [%entry, 0], [%loop, %result]
21385 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21387 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21388 assert(AddendDef.getOperand(i).isReg());
21389 MachineOperand PHISrcOp = AddendDef.getOperand(i);
21390 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21391 if (&PHISrcInst == MI) {
21392 // Found a matching instruction.
21393 unsigned NewFMAOpc = 0;
21394 switch (MI->getOpcode()) {
21395 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21396 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21397 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21398 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21399 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21400 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21401 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21402 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21403 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21404 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21405 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21406 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21407 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21408 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21409 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21410 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21411 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21412 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21413 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21414 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21416 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21417 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21418 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21419 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21420 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21421 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21422 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21423 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21424 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21425 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21426 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21427 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21428 default: llvm_unreachable("Unrecognized FMA variant.");
21431 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21432 MachineInstrBuilder MIB =
21433 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21434 .addOperand(MI->getOperand(0))
21435 .addOperand(MI->getOperand(3))
21436 .addOperand(MI->getOperand(2))
21437 .addOperand(MI->getOperand(1));
21438 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21439 MI->eraseFromParent();
21446 MachineBasicBlock *
21447 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21448 MachineBasicBlock *BB) const {
21449 switch (MI->getOpcode()) {
21450 default: llvm_unreachable("Unexpected instr type to insert");
21451 case X86::TAILJMPd64:
21452 case X86::TAILJMPr64:
21453 case X86::TAILJMPm64:
21454 case X86::TAILJMPd64_REX:
21455 case X86::TAILJMPr64_REX:
21456 case X86::TAILJMPm64_REX:
21457 llvm_unreachable("TAILJMP64 would not be touched here.");
21458 case X86::TCRETURNdi64:
21459 case X86::TCRETURNri64:
21460 case X86::TCRETURNmi64:
21462 case X86::WIN_ALLOCA:
21463 return EmitLoweredWinAlloca(MI, BB);
21464 case X86::SEG_ALLOCA_32:
21465 case X86::SEG_ALLOCA_64:
21466 return EmitLoweredSegAlloca(MI, BB);
21467 case X86::TLSCall_32:
21468 case X86::TLSCall_64:
21469 return EmitLoweredTLSCall(MI, BB);
21470 case X86::CMOV_FR32:
21471 case X86::CMOV_FR64:
21472 case X86::CMOV_GR8:
21473 case X86::CMOV_GR16:
21474 case X86::CMOV_GR32:
21475 case X86::CMOV_RFP32:
21476 case X86::CMOV_RFP64:
21477 case X86::CMOV_RFP80:
21478 case X86::CMOV_V2F64:
21479 case X86::CMOV_V2I64:
21480 case X86::CMOV_V4F32:
21481 case X86::CMOV_V4F64:
21482 case X86::CMOV_V4I64:
21483 case X86::CMOV_V16F32:
21484 case X86::CMOV_V8F32:
21485 case X86::CMOV_V8F64:
21486 case X86::CMOV_V8I64:
21487 case X86::CMOV_V8I1:
21488 case X86::CMOV_V16I1:
21489 case X86::CMOV_V32I1:
21490 case X86::CMOV_V64I1:
21491 return EmitLoweredSelect(MI, BB);
21493 case X86::RELEASE_FADD32mr:
21494 case X86::RELEASE_FADD64mr:
21495 return EmitLoweredAtomicFP(MI, BB);
21497 case X86::FP32_TO_INT16_IN_MEM:
21498 case X86::FP32_TO_INT32_IN_MEM:
21499 case X86::FP32_TO_INT64_IN_MEM:
21500 case X86::FP64_TO_INT16_IN_MEM:
21501 case X86::FP64_TO_INT32_IN_MEM:
21502 case X86::FP64_TO_INT64_IN_MEM:
21503 case X86::FP80_TO_INT16_IN_MEM:
21504 case X86::FP80_TO_INT32_IN_MEM:
21505 case X86::FP80_TO_INT64_IN_MEM: {
21506 MachineFunction *F = BB->getParent();
21507 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21508 DebugLoc DL = MI->getDebugLoc();
21510 // Change the floating point control register to use "round towards zero"
21511 // mode when truncating to an integer value.
21512 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21513 addFrameReference(BuildMI(*BB, MI, DL,
21514 TII->get(X86::FNSTCW16m)), CWFrameIdx);
21516 // Load the old value of the high byte of the control word...
21518 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21519 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21522 // Set the high part to be round to zero...
21523 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21526 // Reload the modified control word now...
21527 addFrameReference(BuildMI(*BB, MI, DL,
21528 TII->get(X86::FLDCW16m)), CWFrameIdx);
21530 // Restore the memory image of control word to original value
21531 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21534 // Get the X86 opcode to use.
21536 switch (MI->getOpcode()) {
21537 default: llvm_unreachable("illegal opcode!");
21538 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21539 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21540 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21541 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21542 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21543 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21544 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21545 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21546 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21550 MachineOperand &Op = MI->getOperand(0);
21552 AM.BaseType = X86AddressMode::RegBase;
21553 AM.Base.Reg = Op.getReg();
21555 AM.BaseType = X86AddressMode::FrameIndexBase;
21556 AM.Base.FrameIndex = Op.getIndex();
21558 Op = MI->getOperand(1);
21560 AM.Scale = Op.getImm();
21561 Op = MI->getOperand(2);
21563 AM.IndexReg = Op.getImm();
21564 Op = MI->getOperand(3);
21565 if (Op.isGlobal()) {
21566 AM.GV = Op.getGlobal();
21568 AM.Disp = Op.getImm();
21570 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21571 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21573 // Reload the original control word now.
21574 addFrameReference(BuildMI(*BB, MI, DL,
21575 TII->get(X86::FLDCW16m)), CWFrameIdx);
21577 MI->eraseFromParent(); // The pseudo instruction is gone now.
21580 // String/text processing lowering.
21581 case X86::PCMPISTRM128REG:
21582 case X86::VPCMPISTRM128REG:
21583 case X86::PCMPISTRM128MEM:
21584 case X86::VPCMPISTRM128MEM:
21585 case X86::PCMPESTRM128REG:
21586 case X86::VPCMPESTRM128REG:
21587 case X86::PCMPESTRM128MEM:
21588 case X86::VPCMPESTRM128MEM:
21589 assert(Subtarget->hasSSE42() &&
21590 "Target must have SSE4.2 or AVX features enabled");
21591 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21593 // String/text processing lowering.
21594 case X86::PCMPISTRIREG:
21595 case X86::VPCMPISTRIREG:
21596 case X86::PCMPISTRIMEM:
21597 case X86::VPCMPISTRIMEM:
21598 case X86::PCMPESTRIREG:
21599 case X86::VPCMPESTRIREG:
21600 case X86::PCMPESTRIMEM:
21601 case X86::VPCMPESTRIMEM:
21602 assert(Subtarget->hasSSE42() &&
21603 "Target must have SSE4.2 or AVX features enabled");
21604 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21606 // Thread synchronization.
21608 return EmitMonitor(MI, BB, Subtarget);
21612 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21614 case X86::VASTART_SAVE_XMM_REGS:
21615 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21617 case X86::VAARG_64:
21618 return EmitVAARG64WithCustomInserter(MI, BB);
21620 case X86::EH_SjLj_SetJmp32:
21621 case X86::EH_SjLj_SetJmp64:
21622 return emitEHSjLjSetJmp(MI, BB);
21624 case X86::EH_SjLj_LongJmp32:
21625 case X86::EH_SjLj_LongJmp64:
21626 return emitEHSjLjLongJmp(MI, BB);
21628 case TargetOpcode::STATEPOINT:
21629 // As an implementation detail, STATEPOINT shares the STACKMAP format at
21630 // this point in the process. We diverge later.
21631 return emitPatchPoint(MI, BB);
21633 case TargetOpcode::STACKMAP:
21634 case TargetOpcode::PATCHPOINT:
21635 return emitPatchPoint(MI, BB);
21637 case X86::VFMADDPDr213r:
21638 case X86::VFMADDPSr213r:
21639 case X86::VFMADDSDr213r:
21640 case X86::VFMADDSSr213r:
21641 case X86::VFMSUBPDr213r:
21642 case X86::VFMSUBPSr213r:
21643 case X86::VFMSUBSDr213r:
21644 case X86::VFMSUBSSr213r:
21645 case X86::VFNMADDPDr213r:
21646 case X86::VFNMADDPSr213r:
21647 case X86::VFNMADDSDr213r:
21648 case X86::VFNMADDSSr213r:
21649 case X86::VFNMSUBPDr213r:
21650 case X86::VFNMSUBPSr213r:
21651 case X86::VFNMSUBSDr213r:
21652 case X86::VFNMSUBSSr213r:
21653 case X86::VFMADDSUBPDr213r:
21654 case X86::VFMADDSUBPSr213r:
21655 case X86::VFMSUBADDPDr213r:
21656 case X86::VFMSUBADDPSr213r:
21657 case X86::VFMADDPDr213rY:
21658 case X86::VFMADDPSr213rY:
21659 case X86::VFMSUBPDr213rY:
21660 case X86::VFMSUBPSr213rY:
21661 case X86::VFNMADDPDr213rY:
21662 case X86::VFNMADDPSr213rY:
21663 case X86::VFNMSUBPDr213rY:
21664 case X86::VFNMSUBPSr213rY:
21665 case X86::VFMADDSUBPDr213rY:
21666 case X86::VFMADDSUBPSr213rY:
21667 case X86::VFMSUBADDPDr213rY:
21668 case X86::VFMSUBADDPSr213rY:
21669 return emitFMA3Instr(MI, BB);
21673 //===----------------------------------------------------------------------===//
21674 // X86 Optimization Hooks
21675 //===----------------------------------------------------------------------===//
21677 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21680 const SelectionDAG &DAG,
21681 unsigned Depth) const {
21682 unsigned BitWidth = KnownZero.getBitWidth();
21683 unsigned Opc = Op.getOpcode();
21684 assert((Opc >= ISD::BUILTIN_OP_END ||
21685 Opc == ISD::INTRINSIC_WO_CHAIN ||
21686 Opc == ISD::INTRINSIC_W_CHAIN ||
21687 Opc == ISD::INTRINSIC_VOID) &&
21688 "Should use MaskedValueIsZero if you don't know whether Op"
21689 " is a target node!");
21691 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
21705 // These nodes' second result is a boolean.
21706 if (Op.getResNo() == 0)
21709 case X86ISD::SETCC:
21710 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21712 case ISD::INTRINSIC_WO_CHAIN: {
21713 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21714 unsigned NumLoBits = 0;
21717 case Intrinsic::x86_sse_movmsk_ps:
21718 case Intrinsic::x86_avx_movmsk_ps_256:
21719 case Intrinsic::x86_sse2_movmsk_pd:
21720 case Intrinsic::x86_avx_movmsk_pd_256:
21721 case Intrinsic::x86_mmx_pmovmskb:
21722 case Intrinsic::x86_sse2_pmovmskb_128:
21723 case Intrinsic::x86_avx2_pmovmskb: {
21724 // High bits of movmskp{s|d}, pmovmskb are known zero.
21726 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
21727 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
21728 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
21729 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
21730 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
21731 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
21732 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
21733 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
21735 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21744 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21746 const SelectionDAG &,
21747 unsigned Depth) const {
21748 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21749 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21750 return Op.getValueType().getScalarType().getSizeInBits();
21756 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21757 /// node is a GlobalAddress + offset.
21758 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21759 const GlobalValue* &GA,
21760 int64_t &Offset) const {
21761 if (N->getOpcode() == X86ISD::Wrapper) {
21762 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21763 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21764 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21768 return TargetLowering::isGAPlusOffset(N, GA, Offset);
21771 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21772 /// same as extracting the high 128-bit part of 256-bit vector and then
21773 /// inserting the result into the low part of a new 256-bit vector
21774 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21775 EVT VT = SVOp->getValueType(0);
21776 unsigned NumElems = VT.getVectorNumElements();
21778 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21779 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21780 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21781 SVOp->getMaskElt(j) >= 0)
21787 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21788 /// same as extracting the low 128-bit part of 256-bit vector and then
21789 /// inserting the result into the high part of a new 256-bit vector
21790 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21791 EVT VT = SVOp->getValueType(0);
21792 unsigned NumElems = VT.getVectorNumElements();
21794 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21795 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21796 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21797 SVOp->getMaskElt(j) >= 0)
21803 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21804 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21805 TargetLowering::DAGCombinerInfo &DCI,
21806 const X86Subtarget* Subtarget) {
21808 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21809 SDValue V1 = SVOp->getOperand(0);
21810 SDValue V2 = SVOp->getOperand(1);
21811 EVT VT = SVOp->getValueType(0);
21812 unsigned NumElems = VT.getVectorNumElements();
21814 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21815 V2.getOpcode() == ISD::CONCAT_VECTORS) {
21819 // V UNDEF BUILD_VECTOR UNDEF
21821 // CONCAT_VECTOR CONCAT_VECTOR
21824 // RESULT: V + zero extended
21826 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21827 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21828 V1.getOperand(1).getOpcode() != ISD::UNDEF)
21831 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21834 // To match the shuffle mask, the first half of the mask should
21835 // be exactly the first vector, and all the rest a splat with the
21836 // first element of the second one.
21837 for (unsigned i = 0; i != NumElems/2; ++i)
21838 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21839 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21842 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21843 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21844 if (Ld->hasNUsesOfValue(1, 0)) {
21845 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21846 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21848 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21850 Ld->getPointerInfo(),
21851 Ld->getAlignment(),
21852 false/*isVolatile*/, true/*ReadMem*/,
21853 false/*WriteMem*/);
21855 // Make sure the newly-created LOAD is in the same position as Ld in
21856 // terms of dependency. We create a TokenFactor for Ld and ResNode,
21857 // and update uses of Ld's output chain to use the TokenFactor.
21858 if (Ld->hasAnyUseOfValue(1)) {
21859 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21860 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21861 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21862 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21863 SDValue(ResNode.getNode(), 1));
21866 return DAG.getBitcast(VT, ResNode);
21870 // Emit a zeroed vector and insert the desired subvector on its
21872 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21873 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21874 return DCI.CombineTo(N, InsV);
21877 //===--------------------------------------------------------------------===//
21878 // Combine some shuffles into subvector extracts and inserts:
21881 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21882 if (isShuffleHigh128VectorInsertLow(SVOp)) {
21883 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21884 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21885 return DCI.CombineTo(N, InsV);
21888 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21889 if (isShuffleLow128VectorInsertHigh(SVOp)) {
21890 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21891 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21892 return DCI.CombineTo(N, InsV);
21898 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21901 /// This is the leaf of the recursive combinine below. When we have found some
21902 /// chain of single-use x86 shuffle instructions and accumulated the combined
21903 /// shuffle mask represented by them, this will try to pattern match that mask
21904 /// into either a single instruction if there is a special purpose instruction
21905 /// for this operation, or into a PSHUFB instruction which is a fully general
21906 /// instruction but should only be used to replace chains over a certain depth.
21907 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21908 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21909 TargetLowering::DAGCombinerInfo &DCI,
21910 const X86Subtarget *Subtarget) {
21911 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21913 // Find the operand that enters the chain. Note that multiple uses are OK
21914 // here, we're not going to remove the operand we find.
21915 SDValue Input = Op.getOperand(0);
21916 while (Input.getOpcode() == ISD::BITCAST)
21917 Input = Input.getOperand(0);
21919 MVT VT = Input.getSimpleValueType();
21920 MVT RootVT = Root.getSimpleValueType();
21923 // Just remove no-op shuffle masks.
21924 if (Mask.size() == 1) {
21925 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21930 // Use the float domain if the operand type is a floating point type.
21931 bool FloatDomain = VT.isFloatingPoint();
21933 // For floating point shuffles, we don't have free copies in the shuffle
21934 // instructions or the ability to load as part of the instruction, so
21935 // canonicalize their shuffles to UNPCK or MOV variants.
21937 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21938 // vectors because it can have a load folded into it that UNPCK cannot. This
21939 // doesn't preclude something switching to the shorter encoding post-RA.
21941 // FIXME: Should teach these routines about AVX vector widths.
21942 if (FloatDomain && VT.getSizeInBits() == 128) {
21943 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21944 bool Lo = Mask.equals({0, 0});
21947 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21948 // is no slower than UNPCKLPD but has the option to fold the input operand
21949 // into even an unaligned memory load.
21950 if (Lo && Subtarget->hasSSE3()) {
21951 Shuffle = X86ISD::MOVDDUP;
21952 ShuffleVT = MVT::v2f64;
21954 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21955 // than the UNPCK variants.
21956 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21957 ShuffleVT = MVT::v4f32;
21959 if (Depth == 1 && Root->getOpcode() == Shuffle)
21960 return false; // Nothing to do!
21961 Op = DAG.getBitcast(ShuffleVT, Input);
21962 DCI.AddToWorklist(Op.getNode());
21963 if (Shuffle == X86ISD::MOVDDUP)
21964 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21966 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21967 DCI.AddToWorklist(Op.getNode());
21968 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21972 if (Subtarget->hasSSE3() &&
21973 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21974 bool Lo = Mask.equals({0, 0, 2, 2});
21975 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21976 MVT ShuffleVT = MVT::v4f32;
21977 if (Depth == 1 && Root->getOpcode() == Shuffle)
21978 return false; // Nothing to do!
21979 Op = DAG.getBitcast(ShuffleVT, Input);
21980 DCI.AddToWorklist(Op.getNode());
21981 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21982 DCI.AddToWorklist(Op.getNode());
21983 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21987 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21988 bool Lo = Mask.equals({0, 0, 1, 1});
21989 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21990 MVT ShuffleVT = MVT::v4f32;
21991 if (Depth == 1 && Root->getOpcode() == Shuffle)
21992 return false; // Nothing to do!
21993 Op = DAG.getBitcast(ShuffleVT, Input);
21994 DCI.AddToWorklist(Op.getNode());
21995 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21996 DCI.AddToWorklist(Op.getNode());
21997 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22003 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
22004 // variants as none of these have single-instruction variants that are
22005 // superior to the UNPCK formulation.
22006 if (!FloatDomain && VT.getSizeInBits() == 128 &&
22007 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22008 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
22009 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
22011 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
22012 bool Lo = Mask[0] == 0;
22013 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22014 if (Depth == 1 && Root->getOpcode() == Shuffle)
22015 return false; // Nothing to do!
22017 switch (Mask.size()) {
22019 ShuffleVT = MVT::v8i16;
22022 ShuffleVT = MVT::v16i8;
22025 llvm_unreachable("Impossible mask size!");
22027 Op = DAG.getBitcast(ShuffleVT, Input);
22028 DCI.AddToWorklist(Op.getNode());
22029 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22030 DCI.AddToWorklist(Op.getNode());
22031 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22036 // Don't try to re-form single instruction chains under any circumstances now
22037 // that we've done encoding canonicalization for them.
22041 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22042 // can replace them with a single PSHUFB instruction profitably. Intel's
22043 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22044 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22045 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22046 SmallVector<SDValue, 16> PSHUFBMask;
22047 int NumBytes = VT.getSizeInBits() / 8;
22048 int Ratio = NumBytes / Mask.size();
22049 for (int i = 0; i < NumBytes; ++i) {
22050 if (Mask[i / Ratio] == SM_SentinelUndef) {
22051 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22054 int M = Mask[i / Ratio] != SM_SentinelZero
22055 ? Ratio * Mask[i / Ratio] + i % Ratio
22057 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
22059 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
22060 Op = DAG.getBitcast(ByteVT, Input);
22061 DCI.AddToWorklist(Op.getNode());
22062 SDValue PSHUFBMaskOp =
22063 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
22064 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22065 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
22066 DCI.AddToWorklist(Op.getNode());
22067 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22072 // Failed to find any combines.
22076 /// \brief Fully generic combining of x86 shuffle instructions.
22078 /// This should be the last combine run over the x86 shuffle instructions. Once
22079 /// they have been fully optimized, this will recursively consider all chains
22080 /// of single-use shuffle instructions, build a generic model of the cumulative
22081 /// shuffle operation, and check for simpler instructions which implement this
22082 /// operation. We use this primarily for two purposes:
22084 /// 1) Collapse generic shuffles to specialized single instructions when
22085 /// equivalent. In most cases, this is just an encoding size win, but
22086 /// sometimes we will collapse multiple generic shuffles into a single
22087 /// special-purpose shuffle.
22088 /// 2) Look for sequences of shuffle instructions with 3 or more total
22089 /// instructions, and replace them with the slightly more expensive SSSE3
22090 /// PSHUFB instruction if available. We do this as the last combining step
22091 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
22092 /// a suitable short sequence of other instructions. The PHUFB will either
22093 /// use a register or have to read from memory and so is slightly (but only
22094 /// slightly) more expensive than the other shuffle instructions.
22096 /// Because this is inherently a quadratic operation (for each shuffle in
22097 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
22098 /// This should never be an issue in practice as the shuffle lowering doesn't
22099 /// produce sequences of more than 8 instructions.
22101 /// FIXME: We will currently miss some cases where the redundant shuffling
22102 /// would simplify under the threshold for PSHUFB formation because of
22103 /// combine-ordering. To fix this, we should do the redundant instruction
22104 /// combining in this recursive walk.
22105 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
22106 ArrayRef<int> RootMask,
22107 int Depth, bool HasPSHUFB,
22109 TargetLowering::DAGCombinerInfo &DCI,
22110 const X86Subtarget *Subtarget) {
22111 // Bound the depth of our recursive combine because this is ultimately
22112 // quadratic in nature.
22116 // Directly rip through bitcasts to find the underlying operand.
22117 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22118 Op = Op.getOperand(0);
22120 MVT VT = Op.getSimpleValueType();
22121 if (!VT.isVector())
22122 return false; // Bail if we hit a non-vector.
22124 assert(Root.getSimpleValueType().isVector() &&
22125 "Shuffles operate on vector types!");
22126 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22127 "Can only combine shuffles of the same vector register size.");
22129 if (!isTargetShuffle(Op.getOpcode()))
22131 SmallVector<int, 16> OpMask;
22133 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22134 // We only can combine unary shuffles which we can decode the mask for.
22135 if (!HaveMask || !IsUnary)
22138 assert(VT.getVectorNumElements() == OpMask.size() &&
22139 "Different mask size from vector size!");
22140 assert(((RootMask.size() > OpMask.size() &&
22141 RootMask.size() % OpMask.size() == 0) ||
22142 (OpMask.size() > RootMask.size() &&
22143 OpMask.size() % RootMask.size() == 0) ||
22144 OpMask.size() == RootMask.size()) &&
22145 "The smaller number of elements must divide the larger.");
22146 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22147 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22148 assert(((RootRatio == 1 && OpRatio == 1) ||
22149 (RootRatio == 1) != (OpRatio == 1)) &&
22150 "Must not have a ratio for both incoming and op masks!");
22152 SmallVector<int, 16> Mask;
22153 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22155 // Merge this shuffle operation's mask into our accumulated mask. Note that
22156 // this shuffle's mask will be the first applied to the input, followed by the
22157 // root mask to get us all the way to the root value arrangement. The reason
22158 // for this order is that we are recursing up the operation chain.
22159 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22160 int RootIdx = i / RootRatio;
22161 if (RootMask[RootIdx] < 0) {
22162 // This is a zero or undef lane, we're done.
22163 Mask.push_back(RootMask[RootIdx]);
22167 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22168 int OpIdx = RootMaskedIdx / OpRatio;
22169 if (OpMask[OpIdx] < 0) {
22170 // The incoming lanes are zero or undef, it doesn't matter which ones we
22172 Mask.push_back(OpMask[OpIdx]);
22176 // Ok, we have non-zero lanes, map them through.
22177 Mask.push_back(OpMask[OpIdx] * OpRatio +
22178 RootMaskedIdx % OpRatio);
22181 // See if we can recurse into the operand to combine more things.
22182 switch (Op.getOpcode()) {
22183 case X86ISD::PSHUFB:
22185 case X86ISD::PSHUFD:
22186 case X86ISD::PSHUFHW:
22187 case X86ISD::PSHUFLW:
22188 if (Op.getOperand(0).hasOneUse() &&
22189 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22190 HasPSHUFB, DAG, DCI, Subtarget))
22194 case X86ISD::UNPCKL:
22195 case X86ISD::UNPCKH:
22196 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
22197 // We can't check for single use, we have to check that this shuffle is the only user.
22198 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22199 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22200 HasPSHUFB, DAG, DCI, Subtarget))
22205 // Minor canonicalization of the accumulated shuffle mask to make it easier
22206 // to match below. All this does is detect masks with squential pairs of
22207 // elements, and shrink them to the half-width mask. It does this in a loop
22208 // so it will reduce the size of the mask to the minimal width mask which
22209 // performs an equivalent shuffle.
22210 SmallVector<int, 16> WidenedMask;
22211 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22212 Mask = std::move(WidenedMask);
22213 WidenedMask.clear();
22216 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22220 /// \brief Get the PSHUF-style mask from PSHUF node.
22222 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22223 /// PSHUF-style masks that can be reused with such instructions.
22224 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22225 MVT VT = N.getSimpleValueType();
22226 SmallVector<int, 4> Mask;
22228 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22232 // If we have more than 128-bits, only the low 128-bits of shuffle mask
22233 // matter. Check that the upper masks are repeats and remove them.
22234 if (VT.getSizeInBits() > 128) {
22235 int LaneElts = 128 / VT.getScalarSizeInBits();
22237 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22238 for (int j = 0; j < LaneElts; ++j)
22239 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22240 "Mask doesn't repeat in high 128-bit lanes!");
22242 Mask.resize(LaneElts);
22245 switch (N.getOpcode()) {
22246 case X86ISD::PSHUFD:
22248 case X86ISD::PSHUFLW:
22251 case X86ISD::PSHUFHW:
22252 Mask.erase(Mask.begin(), Mask.begin() + 4);
22253 for (int &M : Mask)
22257 llvm_unreachable("No valid shuffle instruction found!");
22261 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22263 /// We walk up the chain and look for a combinable shuffle, skipping over
22264 /// shuffles that we could hoist this shuffle's transformation past without
22265 /// altering anything.
22267 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22269 TargetLowering::DAGCombinerInfo &DCI) {
22270 assert(N.getOpcode() == X86ISD::PSHUFD &&
22271 "Called with something other than an x86 128-bit half shuffle!");
22274 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22275 // of the shuffles in the chain so that we can form a fresh chain to replace
22277 SmallVector<SDValue, 8> Chain;
22278 SDValue V = N.getOperand(0);
22279 for (; V.hasOneUse(); V = V.getOperand(0)) {
22280 switch (V.getOpcode()) {
22282 return SDValue(); // Nothing combined!
22285 // Skip bitcasts as we always know the type for the target specific
22289 case X86ISD::PSHUFD:
22290 // Found another dword shuffle.
22293 case X86ISD::PSHUFLW:
22294 // Check that the low words (being shuffled) are the identity in the
22295 // dword shuffle, and the high words are self-contained.
22296 if (Mask[0] != 0 || Mask[1] != 1 ||
22297 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22300 Chain.push_back(V);
22303 case X86ISD::PSHUFHW:
22304 // Check that the high words (being shuffled) are the identity in the
22305 // dword shuffle, and the low words are self-contained.
22306 if (Mask[2] != 2 || Mask[3] != 3 ||
22307 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22310 Chain.push_back(V);
22313 case X86ISD::UNPCKL:
22314 case X86ISD::UNPCKH:
22315 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22316 // shuffle into a preceding word shuffle.
22317 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
22318 V.getSimpleValueType().getScalarType() != MVT::i16)
22321 // Search for a half-shuffle which we can combine with.
22322 unsigned CombineOp =
22323 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22324 if (V.getOperand(0) != V.getOperand(1) ||
22325 !V->isOnlyUserOf(V.getOperand(0).getNode()))
22327 Chain.push_back(V);
22328 V = V.getOperand(0);
22330 switch (V.getOpcode()) {
22332 return SDValue(); // Nothing to combine.
22334 case X86ISD::PSHUFLW:
22335 case X86ISD::PSHUFHW:
22336 if (V.getOpcode() == CombineOp)
22339 Chain.push_back(V);
22343 V = V.getOperand(0);
22347 } while (V.hasOneUse());
22350 // Break out of the loop if we break out of the switch.
22354 if (!V.hasOneUse())
22355 // We fell out of the loop without finding a viable combining instruction.
22358 // Merge this node's mask and our incoming mask.
22359 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22360 for (int &M : Mask)
22362 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22363 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22365 // Rebuild the chain around this new shuffle.
22366 while (!Chain.empty()) {
22367 SDValue W = Chain.pop_back_val();
22369 if (V.getValueType() != W.getOperand(0).getValueType())
22370 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22372 switch (W.getOpcode()) {
22374 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22376 case X86ISD::UNPCKL:
22377 case X86ISD::UNPCKH:
22378 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22381 case X86ISD::PSHUFD:
22382 case X86ISD::PSHUFLW:
22383 case X86ISD::PSHUFHW:
22384 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22388 if (V.getValueType() != N.getValueType())
22389 V = DAG.getBitcast(N.getValueType(), V);
22391 // Return the new chain to replace N.
22395 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
22397 /// We walk up the chain, skipping shuffles of the other half and looking
22398 /// through shuffles which switch halves trying to find a shuffle of the same
22399 /// pair of dwords.
22400 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22402 TargetLowering::DAGCombinerInfo &DCI) {
22404 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22405 "Called with something other than an x86 128-bit half shuffle!");
22407 unsigned CombineOpcode = N.getOpcode();
22409 // Walk up a single-use chain looking for a combinable shuffle.
22410 SDValue V = N.getOperand(0);
22411 for (; V.hasOneUse(); V = V.getOperand(0)) {
22412 switch (V.getOpcode()) {
22414 return false; // Nothing combined!
22417 // Skip bitcasts as we always know the type for the target specific
22421 case X86ISD::PSHUFLW:
22422 case X86ISD::PSHUFHW:
22423 if (V.getOpcode() == CombineOpcode)
22426 // Other-half shuffles are no-ops.
22429 // Break out of the loop if we break out of the switch.
22433 if (!V.hasOneUse())
22434 // We fell out of the loop without finding a viable combining instruction.
22437 // Combine away the bottom node as its shuffle will be accumulated into
22438 // a preceding shuffle.
22439 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22441 // Record the old value.
22444 // Merge this node's mask and our incoming mask (adjusted to account for all
22445 // the pshufd instructions encountered).
22446 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22447 for (int &M : Mask)
22449 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22450 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22452 // Check that the shuffles didn't cancel each other out. If not, we need to
22453 // combine to the new one.
22455 // Replace the combinable shuffle with the combined one, updating all users
22456 // so that we re-evaluate the chain here.
22457 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22462 /// \brief Try to combine x86 target specific shuffles.
22463 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22464 TargetLowering::DAGCombinerInfo &DCI,
22465 const X86Subtarget *Subtarget) {
22467 MVT VT = N.getSimpleValueType();
22468 SmallVector<int, 4> Mask;
22470 switch (N.getOpcode()) {
22471 case X86ISD::PSHUFD:
22472 case X86ISD::PSHUFLW:
22473 case X86ISD::PSHUFHW:
22474 Mask = getPSHUFShuffleMask(N);
22475 assert(Mask.size() == 4);
22481 // Nuke no-op shuffles that show up after combining.
22482 if (isNoopShuffleMask(Mask))
22483 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22485 // Look for simplifications involving one or two shuffle instructions.
22486 SDValue V = N.getOperand(0);
22487 switch (N.getOpcode()) {
22490 case X86ISD::PSHUFLW:
22491 case X86ISD::PSHUFHW:
22492 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22494 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22495 return SDValue(); // We combined away this shuffle, so we're done.
22497 // See if this reduces to a PSHUFD which is no more expensive and can
22498 // combine with more operations. Note that it has to at least flip the
22499 // dwords as otherwise it would have been removed as a no-op.
22500 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22501 int DMask[] = {0, 1, 2, 3};
22502 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22503 DMask[DOffset + 0] = DOffset + 1;
22504 DMask[DOffset + 1] = DOffset + 0;
22505 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22506 V = DAG.getBitcast(DVT, V);
22507 DCI.AddToWorklist(V.getNode());
22508 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22509 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22510 DCI.AddToWorklist(V.getNode());
22511 return DAG.getBitcast(VT, V);
22514 // Look for shuffle patterns which can be implemented as a single unpack.
22515 // FIXME: This doesn't handle the location of the PSHUFD generically, and
22516 // only works when we have a PSHUFD followed by two half-shuffles.
22517 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22518 (V.getOpcode() == X86ISD::PSHUFLW ||
22519 V.getOpcode() == X86ISD::PSHUFHW) &&
22520 V.getOpcode() != N.getOpcode() &&
22522 SDValue D = V.getOperand(0);
22523 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22524 D = D.getOperand(0);
22525 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22526 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22527 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22528 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22529 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22531 for (int i = 0; i < 4; ++i) {
22532 WordMask[i + NOffset] = Mask[i] + NOffset;
22533 WordMask[i + VOffset] = VMask[i] + VOffset;
22535 // Map the word mask through the DWord mask.
22537 for (int i = 0; i < 8; ++i)
22538 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22539 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22540 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22541 // We can replace all three shuffles with an unpack.
22542 V = DAG.getBitcast(VT, D.getOperand(0));
22543 DCI.AddToWorklist(V.getNode());
22544 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22553 case X86ISD::PSHUFD:
22554 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22563 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22565 /// We combine this directly on the abstract vector shuffle nodes so it is
22566 /// easier to generically match. We also insert dummy vector shuffle nodes for
22567 /// the operands which explicitly discard the lanes which are unused by this
22568 /// operation to try to flow through the rest of the combiner the fact that
22569 /// they're unused.
22570 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22572 EVT VT = N->getValueType(0);
22574 // We only handle target-independent shuffles.
22575 // FIXME: It would be easy and harmless to use the target shuffle mask
22576 // extraction tool to support more.
22577 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22580 auto *SVN = cast<ShuffleVectorSDNode>(N);
22581 ArrayRef<int> Mask = SVN->getMask();
22582 SDValue V1 = N->getOperand(0);
22583 SDValue V2 = N->getOperand(1);
22585 // We require the first shuffle operand to be the SUB node, and the second to
22586 // be the ADD node.
22587 // FIXME: We should support the commuted patterns.
22588 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22591 // If there are other uses of these operations we can't fold them.
22592 if (!V1->hasOneUse() || !V2->hasOneUse())
22595 // Ensure that both operations have the same operands. Note that we can
22596 // commute the FADD operands.
22597 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22598 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22599 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22602 // We're looking for blends between FADD and FSUB nodes. We insist on these
22603 // nodes being lined up in a specific expected pattern.
22604 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22605 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22606 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22609 // Only specific types are legal at this point, assert so we notice if and
22610 // when these change.
22611 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22612 VT == MVT::v4f64) &&
22613 "Unknown vector type encountered!");
22615 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22618 /// PerformShuffleCombine - Performs several different shuffle combines.
22619 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22620 TargetLowering::DAGCombinerInfo &DCI,
22621 const X86Subtarget *Subtarget) {
22623 SDValue N0 = N->getOperand(0);
22624 SDValue N1 = N->getOperand(1);
22625 EVT VT = N->getValueType(0);
22627 // Don't create instructions with illegal types after legalize types has run.
22628 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22629 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22632 // If we have legalized the vector types, look for blends of FADD and FSUB
22633 // nodes that we can fuse into an ADDSUB node.
22634 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22635 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22638 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22639 if (Subtarget->hasFp256() && VT.is256BitVector() &&
22640 N->getOpcode() == ISD::VECTOR_SHUFFLE)
22641 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22643 // During Type Legalization, when promoting illegal vector types,
22644 // the backend might introduce new shuffle dag nodes and bitcasts.
22646 // This code performs the following transformation:
22647 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22648 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22650 // We do this only if both the bitcast and the BINOP dag nodes have
22651 // one use. Also, perform this transformation only if the new binary
22652 // operation is legal. This is to avoid introducing dag nodes that
22653 // potentially need to be further expanded (or custom lowered) into a
22654 // less optimal sequence of dag nodes.
22655 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22656 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22657 N0.getOpcode() == ISD::BITCAST) {
22658 SDValue BC0 = N0.getOperand(0);
22659 EVT SVT = BC0.getValueType();
22660 unsigned Opcode = BC0.getOpcode();
22661 unsigned NumElts = VT.getVectorNumElements();
22663 if (BC0.hasOneUse() && SVT.isVector() &&
22664 SVT.getVectorNumElements() * 2 == NumElts &&
22665 TLI.isOperationLegal(Opcode, VT)) {
22666 bool CanFold = false;
22678 unsigned SVTNumElts = SVT.getVectorNumElements();
22679 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22680 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22681 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22682 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22683 CanFold = SVOp->getMaskElt(i) < 0;
22686 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22687 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22688 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22689 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22694 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22695 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22696 // consecutive, non-overlapping, and in the right order.
22697 SmallVector<SDValue, 16> Elts;
22698 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22699 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22701 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22704 if (isTargetShuffle(N->getOpcode())) {
22706 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22707 if (Shuffle.getNode())
22710 // Try recursively combining arbitrary sequences of x86 shuffle
22711 // instructions into higher-order shuffles. We do this after combining
22712 // specific PSHUF instruction sequences into their minimal form so that we
22713 // can evaluate how many specialized shuffle instructions are involved in
22714 // a particular chain.
22715 SmallVector<int, 1> NonceMask; // Just a placeholder.
22716 NonceMask.push_back(0);
22717 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22718 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22720 return SDValue(); // This routine will use CombineTo to replace N.
22726 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22727 /// specific shuffle of a load can be folded into a single element load.
22728 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22729 /// shuffles have been custom lowered so we need to handle those here.
22730 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22731 TargetLowering::DAGCombinerInfo &DCI) {
22732 if (DCI.isBeforeLegalizeOps())
22735 SDValue InVec = N->getOperand(0);
22736 SDValue EltNo = N->getOperand(1);
22738 if (!isa<ConstantSDNode>(EltNo))
22741 EVT OriginalVT = InVec.getValueType();
22743 if (InVec.getOpcode() == ISD::BITCAST) {
22744 // Don't duplicate a load with other uses.
22745 if (!InVec.hasOneUse())
22747 EVT BCVT = InVec.getOperand(0).getValueType();
22748 if (!BCVT.isVector() ||
22749 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22751 InVec = InVec.getOperand(0);
22754 EVT CurrentVT = InVec.getValueType();
22756 if (!isTargetShuffle(InVec.getOpcode()))
22759 // Don't duplicate a load with other uses.
22760 if (!InVec.hasOneUse())
22763 SmallVector<int, 16> ShuffleMask;
22765 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22766 ShuffleMask, UnaryShuffle))
22769 // Select the input vector, guarding against out of range extract vector.
22770 unsigned NumElems = CurrentVT.getVectorNumElements();
22771 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22772 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22773 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22774 : InVec.getOperand(1);
22776 // If inputs to shuffle are the same for both ops, then allow 2 uses
22777 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22778 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22780 if (LdNode.getOpcode() == ISD::BITCAST) {
22781 // Don't duplicate a load with other uses.
22782 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22785 AllowedUses = 1; // only allow 1 load use if we have a bitcast
22786 LdNode = LdNode.getOperand(0);
22789 if (!ISD::isNormalLoad(LdNode.getNode()))
22792 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22794 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22797 EVT EltVT = N->getValueType(0);
22798 // If there's a bitcast before the shuffle, check if the load type and
22799 // alignment is valid.
22800 unsigned Align = LN0->getAlignment();
22801 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22802 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22803 EltVT.getTypeForEVT(*DAG.getContext()));
22805 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22808 // All checks match so transform back to vector_shuffle so that DAG combiner
22809 // can finish the job
22812 // Create shuffle node taking into account the case that its a unary shuffle
22813 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22814 : InVec.getOperand(1);
22815 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22816 InVec.getOperand(0), Shuffle,
22818 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22819 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22823 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22824 /// special and don't usually play with other vector types, it's better to
22825 /// handle them early to be sure we emit efficient code by avoiding
22826 /// store-load conversions.
22827 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22828 if (N->getValueType(0) != MVT::x86mmx ||
22829 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22830 N->getOperand(0)->getValueType(0) != MVT::v2i32)
22833 SDValue V = N->getOperand(0);
22834 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22835 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22836 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22837 N->getValueType(0), V.getOperand(0));
22842 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22843 /// generation and convert it from being a bunch of shuffles and extracts
22844 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22845 /// storing the value and loading scalars back, while for x64 we should
22846 /// use 64-bit extracts and shifts.
22847 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22848 TargetLowering::DAGCombinerInfo &DCI) {
22849 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22852 SDValue InputVector = N->getOperand(0);
22853 SDLoc dl(InputVector);
22854 // Detect mmx to i32 conversion through a v2i32 elt extract.
22855 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22856 N->getValueType(0) == MVT::i32 &&
22857 InputVector.getValueType() == MVT::v2i32) {
22859 // The bitcast source is a direct mmx result.
22860 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22861 if (MMXSrc.getValueType() == MVT::x86mmx)
22862 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22863 N->getValueType(0),
22864 InputVector.getNode()->getOperand(0));
22866 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22867 SDValue MMXSrcOp = MMXSrc.getOperand(0);
22868 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22869 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22870 MMXSrcOp.getOpcode() == ISD::BITCAST &&
22871 MMXSrcOp.getValueType() == MVT::v1i64 &&
22872 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22873 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22874 N->getValueType(0),
22875 MMXSrcOp.getOperand(0));
22878 EVT VT = N->getValueType(0);
22880 if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22881 InputVector.getOpcode() == ISD::BITCAST &&
22882 dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22883 uint64_t ExtractedElt =
22884 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22885 uint64_t InputValue =
22886 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22887 uint64_t Res = (InputValue >> ExtractedElt) & 1;
22888 return DAG.getConstant(Res, dl, MVT::i1);
22890 // Only operate on vectors of 4 elements, where the alternative shuffling
22891 // gets to be more expensive.
22892 if (InputVector.getValueType() != MVT::v4i32)
22895 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22896 // single use which is a sign-extend or zero-extend, and all elements are
22898 SmallVector<SDNode *, 4> Uses;
22899 unsigned ExtractedElements = 0;
22900 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22901 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22902 if (UI.getUse().getResNo() != InputVector.getResNo())
22905 SDNode *Extract = *UI;
22906 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22909 if (Extract->getValueType(0) != MVT::i32)
22911 if (!Extract->hasOneUse())
22913 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22914 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22916 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22919 // Record which element was extracted.
22920 ExtractedElements |=
22921 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22923 Uses.push_back(Extract);
22926 // If not all the elements were used, this may not be worthwhile.
22927 if (ExtractedElements != 15)
22930 // Ok, we've now decided to do the transformation.
22931 // If 64-bit shifts are legal, use the extract-shift sequence,
22932 // otherwise bounce the vector off the cache.
22933 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22936 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22937 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22938 auto &DL = DAG.getDataLayout();
22939 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22940 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22941 DAG.getConstant(0, dl, VecIdxTy));
22942 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22943 DAG.getConstant(1, dl, VecIdxTy));
22945 SDValue ShAmt = DAG.getConstant(
22946 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22947 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22948 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22949 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22950 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22951 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22952 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22954 // Store the value to a temporary stack slot.
22955 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22956 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22957 MachinePointerInfo(), false, false, 0);
22959 EVT ElementType = InputVector.getValueType().getVectorElementType();
22960 unsigned EltSize = ElementType.getSizeInBits() / 8;
22962 // Replace each use (extract) with a load of the appropriate element.
22963 for (unsigned i = 0; i < 4; ++i) {
22964 uint64_t Offset = EltSize * i;
22965 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22966 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22968 SDValue ScalarAddr =
22969 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22971 // Load the scalar.
22972 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22973 ScalarAddr, MachinePointerInfo(),
22974 false, false, false, 0);
22979 // Replace the extracts
22980 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22981 UE = Uses.end(); UI != UE; ++UI) {
22982 SDNode *Extract = *UI;
22984 SDValue Idx = Extract->getOperand(1);
22985 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22986 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22989 // The replacement was made in place; don't return anything.
22994 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22995 const X86Subtarget *Subtarget) {
22997 SDValue Cond = N->getOperand(0);
22998 SDValue LHS = N->getOperand(1);
22999 SDValue RHS = N->getOperand(2);
23001 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
23002 SDValue CondSrc = Cond->getOperand(0);
23003 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
23004 Cond = CondSrc->getOperand(0);
23007 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
23010 // A vselect where all conditions and data are constants can be optimized into
23011 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23012 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23013 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23016 unsigned MaskValue = 0;
23017 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23020 MVT VT = N->getSimpleValueType(0);
23021 unsigned NumElems = VT.getVectorNumElements();
23022 SmallVector<int, 8> ShuffleMask(NumElems, -1);
23023 for (unsigned i = 0; i < NumElems; ++i) {
23024 // Be sure we emit undef where we can.
23025 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
23026 ShuffleMask[i] = -1;
23028 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
23031 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23032 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
23034 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
23037 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
23039 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
23040 TargetLowering::DAGCombinerInfo &DCI,
23041 const X86Subtarget *Subtarget) {
23043 SDValue Cond = N->getOperand(0);
23044 // Get the LHS/RHS of the select.
23045 SDValue LHS = N->getOperand(1);
23046 SDValue RHS = N->getOperand(2);
23047 EVT VT = LHS.getValueType();
23048 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23050 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
23051 // instructions match the semantics of the common C idiom x<y?x:y but not
23052 // x<=y?x:y, because of how they handle negative zero (which can be
23053 // ignored in unsafe-math mode).
23054 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
23055 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
23056 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
23057 (Subtarget->hasSSE2() ||
23058 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
23059 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23061 unsigned Opcode = 0;
23062 // Check for x CC y ? x : y.
23063 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23064 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23068 // Converting this to a min would handle NaNs incorrectly, and swapping
23069 // the operands would cause it to handle comparisons between positive
23070 // and negative zero incorrectly.
23071 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23072 if (!DAG.getTarget().Options.UnsafeFPMath &&
23073 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23075 std::swap(LHS, RHS);
23077 Opcode = X86ISD::FMIN;
23080 // Converting this to a min would handle comparisons between positive
23081 // and negative zero incorrectly.
23082 if (!DAG.getTarget().Options.UnsafeFPMath &&
23083 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23085 Opcode = X86ISD::FMIN;
23088 // Converting this to a min would handle both negative zeros and NaNs
23089 // incorrectly, but we can swap the operands to fix both.
23090 std::swap(LHS, RHS);
23094 Opcode = X86ISD::FMIN;
23098 // Converting this to a max would handle comparisons between positive
23099 // and negative zero incorrectly.
23100 if (!DAG.getTarget().Options.UnsafeFPMath &&
23101 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23103 Opcode = X86ISD::FMAX;
23106 // Converting this to a max would handle NaNs incorrectly, and swapping
23107 // the operands would cause it to handle comparisons between positive
23108 // and negative zero incorrectly.
23109 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23110 if (!DAG.getTarget().Options.UnsafeFPMath &&
23111 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23113 std::swap(LHS, RHS);
23115 Opcode = X86ISD::FMAX;
23118 // Converting this to a max would handle both negative zeros and NaNs
23119 // incorrectly, but we can swap the operands to fix both.
23120 std::swap(LHS, RHS);
23124 Opcode = X86ISD::FMAX;
23127 // Check for x CC y ? y : x -- a min/max with reversed arms.
23128 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23129 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23133 // Converting this to a min would handle comparisons between positive
23134 // and negative zero incorrectly, and swapping the operands would
23135 // cause it to handle NaNs incorrectly.
23136 if (!DAG.getTarget().Options.UnsafeFPMath &&
23137 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23138 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23140 std::swap(LHS, RHS);
23142 Opcode = X86ISD::FMIN;
23145 // Converting this to a min would handle NaNs incorrectly.
23146 if (!DAG.getTarget().Options.UnsafeFPMath &&
23147 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23149 Opcode = X86ISD::FMIN;
23152 // Converting this to a min would handle both negative zeros and NaNs
23153 // incorrectly, but we can swap the operands to fix both.
23154 std::swap(LHS, RHS);
23158 Opcode = X86ISD::FMIN;
23162 // Converting this to a max would handle NaNs incorrectly.
23163 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23165 Opcode = X86ISD::FMAX;
23168 // Converting this to a max would handle comparisons between positive
23169 // and negative zero incorrectly, and swapping the operands would
23170 // cause it to handle NaNs incorrectly.
23171 if (!DAG.getTarget().Options.UnsafeFPMath &&
23172 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23173 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23175 std::swap(LHS, RHS);
23177 Opcode = X86ISD::FMAX;
23180 // Converting this to a max would handle both negative zeros and NaNs
23181 // incorrectly, but we can swap the operands to fix both.
23182 std::swap(LHS, RHS);
23186 Opcode = X86ISD::FMAX;
23192 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23195 EVT CondVT = Cond.getValueType();
23196 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23197 CondVT.getVectorElementType() == MVT::i1) {
23198 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23199 // lowering on KNL. In this case we convert it to
23200 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23201 // The same situation for all 128 and 256-bit vectors of i8 and i16.
23202 // Since SKX these selects have a proper lowering.
23203 EVT OpVT = LHS.getValueType();
23204 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23205 (OpVT.getVectorElementType() == MVT::i8 ||
23206 OpVT.getVectorElementType() == MVT::i16) &&
23207 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23208 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23209 DCI.AddToWorklist(Cond.getNode());
23210 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23213 // If this is a select between two integer constants, try to do some
23215 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23216 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23217 // Don't do this for crazy integer types.
23218 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23219 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23220 // so that TrueC (the true value) is larger than FalseC.
23221 bool NeedsCondInvert = false;
23223 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23224 // Efficiently invertible.
23225 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
23226 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
23227 isa<ConstantSDNode>(Cond.getOperand(1))))) {
23228 NeedsCondInvert = true;
23229 std::swap(TrueC, FalseC);
23232 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
23233 if (FalseC->getAPIntValue() == 0 &&
23234 TrueC->getAPIntValue().isPowerOf2()) {
23235 if (NeedsCondInvert) // Invert the condition if needed.
23236 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23237 DAG.getConstant(1, DL, Cond.getValueType()));
23239 // Zero extend the condition if needed.
23240 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23242 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23243 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23244 DAG.getConstant(ShAmt, DL, MVT::i8));
23247 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23248 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23249 if (NeedsCondInvert) // Invert the condition if needed.
23250 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23251 DAG.getConstant(1, DL, Cond.getValueType()));
23253 // Zero extend the condition if needed.
23254 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23255 FalseC->getValueType(0), Cond);
23256 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23257 SDValue(FalseC, 0));
23260 // Optimize cases that will turn into an LEA instruction. This requires
23261 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23262 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23263 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23264 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23266 bool isFastMultiplier = false;
23268 switch ((unsigned char)Diff) {
23270 case 1: // result = add base, cond
23271 case 2: // result = lea base( , cond*2)
23272 case 3: // result = lea base(cond, cond*2)
23273 case 4: // result = lea base( , cond*4)
23274 case 5: // result = lea base(cond, cond*4)
23275 case 8: // result = lea base( , cond*8)
23276 case 9: // result = lea base(cond, cond*8)
23277 isFastMultiplier = true;
23282 if (isFastMultiplier) {
23283 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23284 if (NeedsCondInvert) // Invert the condition if needed.
23285 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23286 DAG.getConstant(1, DL, Cond.getValueType()));
23288 // Zero extend the condition if needed.
23289 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23291 // Scale the condition by the difference.
23293 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23294 DAG.getConstant(Diff, DL,
23295 Cond.getValueType()));
23297 // Add the base if non-zero.
23298 if (FalseC->getAPIntValue() != 0)
23299 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23300 SDValue(FalseC, 0));
23307 // Canonicalize max and min:
23308 // (x > y) ? x : y -> (x >= y) ? x : y
23309 // (x < y) ? x : y -> (x <= y) ? x : y
23310 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23311 // the need for an extra compare
23312 // against zero. e.g.
23313 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23315 // testl %edi, %edi
23317 // cmovgl %edi, %eax
23321 // cmovsl %eax, %edi
23322 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23323 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23324 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23325 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23330 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23331 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23332 Cond.getOperand(0), Cond.getOperand(1), NewCC);
23333 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23338 // Early exit check
23339 if (!TLI.isTypeLegal(VT))
23342 // Match VSELECTs into subs with unsigned saturation.
23343 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23344 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23345 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23346 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23347 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23349 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23350 // left side invert the predicate to simplify logic below.
23352 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23354 CC = ISD::getSetCCInverse(CC, true);
23355 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23359 if (Other.getNode() && Other->getNumOperands() == 2 &&
23360 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23361 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23362 SDValue CondRHS = Cond->getOperand(1);
23364 // Look for a general sub with unsigned saturation first.
23365 // x >= y ? x-y : 0 --> subus x, y
23366 // x > y ? x-y : 0 --> subus x, y
23367 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23368 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23369 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23371 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23372 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23373 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23374 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23375 // If the RHS is a constant we have to reverse the const
23376 // canonicalization.
23377 // x > C-1 ? x+-C : 0 --> subus x, C
23378 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23379 CondRHSConst->getAPIntValue() ==
23380 (-OpRHSConst->getAPIntValue() - 1))
23381 return DAG.getNode(
23382 X86ISD::SUBUS, DL, VT, OpLHS,
23383 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23385 // Another special case: If C was a sign bit, the sub has been
23386 // canonicalized into a xor.
23387 // FIXME: Would it be better to use computeKnownBits to determine
23388 // whether it's safe to decanonicalize the xor?
23389 // x s< 0 ? x^C : 0 --> subus x, C
23390 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23391 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23392 OpRHSConst->getAPIntValue().isSignBit())
23393 // Note that we have to rebuild the RHS constant here to ensure we
23394 // don't rely on particular values of undef lanes.
23395 return DAG.getNode(
23396 X86ISD::SUBUS, DL, VT, OpLHS,
23397 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23402 // Simplify vector selection if condition value type matches vselect
23404 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23405 assert(Cond.getValueType().isVector() &&
23406 "vector select expects a vector selector!");
23408 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23409 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23411 // Try invert the condition if true value is not all 1s and false value
23413 if (!TValIsAllOnes && !FValIsAllZeros &&
23414 // Check if the selector will be produced by CMPP*/PCMP*
23415 Cond.getOpcode() == ISD::SETCC &&
23416 // Check if SETCC has already been promoted
23417 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23419 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23420 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23422 if (TValIsAllZeros || FValIsAllOnes) {
23423 SDValue CC = Cond.getOperand(2);
23424 ISD::CondCode NewCC =
23425 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23426 Cond.getOperand(0).getValueType().isInteger());
23427 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23428 std::swap(LHS, RHS);
23429 TValIsAllOnes = FValIsAllOnes;
23430 FValIsAllZeros = TValIsAllZeros;
23434 if (TValIsAllOnes || FValIsAllZeros) {
23437 if (TValIsAllOnes && FValIsAllZeros)
23439 else if (TValIsAllOnes)
23441 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23442 else if (FValIsAllZeros)
23443 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23444 DAG.getBitcast(CondVT, LHS));
23446 return DAG.getBitcast(VT, Ret);
23450 // We should generate an X86ISD::BLENDI from a vselect if its argument
23451 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23452 // constants. This specific pattern gets generated when we split a
23453 // selector for a 512 bit vector in a machine without AVX512 (but with
23454 // 256-bit vectors), during legalization:
23456 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23458 // Iff we find this pattern and the build_vectors are built from
23459 // constants, we translate the vselect into a shuffle_vector that we
23460 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23461 if ((N->getOpcode() == ISD::VSELECT ||
23462 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23463 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23464 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23465 if (Shuffle.getNode())
23469 // If this is a *dynamic* select (non-constant condition) and we can match
23470 // this node with one of the variable blend instructions, restructure the
23471 // condition so that the blends can use the high bit of each element and use
23472 // SimplifyDemandedBits to simplify the condition operand.
23473 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23474 !DCI.isBeforeLegalize() &&
23475 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23476 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23478 // Don't optimize vector selects that map to mask-registers.
23482 // We can only handle the cases where VSELECT is directly legal on the
23483 // subtarget. We custom lower VSELECT nodes with constant conditions and
23484 // this makes it hard to see whether a dynamic VSELECT will correctly
23485 // lower, so we both check the operation's status and explicitly handle the
23486 // cases where a *dynamic* blend will fail even though a constant-condition
23487 // blend could be custom lowered.
23488 // FIXME: We should find a better way to handle this class of problems.
23489 // Potentially, we should combine constant-condition vselect nodes
23490 // pre-legalization into shuffles and not mark as many types as custom
23492 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23494 // FIXME: We don't support i16-element blends currently. We could and
23495 // should support them by making *all* the bits in the condition be set
23496 // rather than just the high bit and using an i8-element blend.
23497 if (VT.getScalarType() == MVT::i16)
23499 // Dynamic blending was only available from SSE4.1 onward.
23500 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23502 // Byte blends are only available in AVX2
23503 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23504 !Subtarget->hasAVX2())
23507 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23508 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23510 APInt KnownZero, KnownOne;
23511 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23512 DCI.isBeforeLegalizeOps());
23513 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23514 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23516 // If we changed the computation somewhere in the DAG, this change
23517 // will affect all users of Cond.
23518 // Make sure it is fine and update all the nodes so that we do not
23519 // use the generic VSELECT anymore. Otherwise, we may perform
23520 // wrong optimizations as we messed up with the actual expectation
23521 // for the vector boolean values.
23522 if (Cond != TLO.Old) {
23523 // Check all uses of that condition operand to check whether it will be
23524 // consumed by non-BLEND instructions, which may depend on all bits are
23526 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23528 if (I->getOpcode() != ISD::VSELECT)
23529 // TODO: Add other opcodes eventually lowered into BLEND.
23532 // Update all the users of the condition, before committing the change,
23533 // so that the VSELECT optimizations that expect the correct vector
23534 // boolean value will not be triggered.
23535 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23537 DAG.ReplaceAllUsesOfValueWith(
23539 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23540 Cond, I->getOperand(1), I->getOperand(2)));
23541 DCI.CommitTargetLoweringOpt(TLO);
23544 // At this point, only Cond is changed. Change the condition
23545 // just for N to keep the opportunity to optimize all other
23546 // users their own way.
23547 DAG.ReplaceAllUsesOfValueWith(
23549 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23550 TLO.New, N->getOperand(1), N->getOperand(2)));
23558 // Check whether a boolean test is testing a boolean value generated by
23559 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23562 // Simplify the following patterns:
23563 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23564 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23565 // to (Op EFLAGS Cond)
23567 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23568 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23569 // to (Op EFLAGS !Cond)
23571 // where Op could be BRCOND or CMOV.
23573 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23574 // Quit if not CMP and SUB with its value result used.
23575 if (Cmp.getOpcode() != X86ISD::CMP &&
23576 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23579 // Quit if not used as a boolean value.
23580 if (CC != X86::COND_E && CC != X86::COND_NE)
23583 // Check CMP operands. One of them should be 0 or 1 and the other should be
23584 // an SetCC or extended from it.
23585 SDValue Op1 = Cmp.getOperand(0);
23586 SDValue Op2 = Cmp.getOperand(1);
23589 const ConstantSDNode* C = nullptr;
23590 bool needOppositeCond = (CC == X86::COND_E);
23591 bool checkAgainstTrue = false; // Is it a comparison against 1?
23593 if ((C = dyn_cast<ConstantSDNode>(Op1)))
23595 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23597 else // Quit if all operands are not constants.
23600 if (C->getZExtValue() == 1) {
23601 needOppositeCond = !needOppositeCond;
23602 checkAgainstTrue = true;
23603 } else if (C->getZExtValue() != 0)
23604 // Quit if the constant is neither 0 or 1.
23607 bool truncatedToBoolWithAnd = false;
23608 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23609 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23610 SetCC.getOpcode() == ISD::TRUNCATE ||
23611 SetCC.getOpcode() == ISD::AND) {
23612 if (SetCC.getOpcode() == ISD::AND) {
23614 ConstantSDNode *CS;
23615 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23616 CS->getZExtValue() == 1)
23618 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23619 CS->getZExtValue() == 1)
23623 SetCC = SetCC.getOperand(OpIdx);
23624 truncatedToBoolWithAnd = true;
23626 SetCC = SetCC.getOperand(0);
23629 switch (SetCC.getOpcode()) {
23630 case X86ISD::SETCC_CARRY:
23631 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23632 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23633 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23634 // truncated to i1 using 'and'.
23635 if (checkAgainstTrue && !truncatedToBoolWithAnd)
23637 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23638 "Invalid use of SETCC_CARRY!");
23640 case X86ISD::SETCC:
23641 // Set the condition code or opposite one if necessary.
23642 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23643 if (needOppositeCond)
23644 CC = X86::GetOppositeBranchCondition(CC);
23645 return SetCC.getOperand(1);
23646 case X86ISD::CMOV: {
23647 // Check whether false/true value has canonical one, i.e. 0 or 1.
23648 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23649 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23650 // Quit if true value is not a constant.
23653 // Quit if false value is not a constant.
23655 SDValue Op = SetCC.getOperand(0);
23656 // Skip 'zext' or 'trunc' node.
23657 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23658 Op.getOpcode() == ISD::TRUNCATE)
23659 Op = Op.getOperand(0);
23660 // A special case for rdrand/rdseed, where 0 is set if false cond is
23662 if ((Op.getOpcode() != X86ISD::RDRAND &&
23663 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23666 // Quit if false value is not the constant 0 or 1.
23667 bool FValIsFalse = true;
23668 if (FVal && FVal->getZExtValue() != 0) {
23669 if (FVal->getZExtValue() != 1)
23671 // If FVal is 1, opposite cond is needed.
23672 needOppositeCond = !needOppositeCond;
23673 FValIsFalse = false;
23675 // Quit if TVal is not the constant opposite of FVal.
23676 if (FValIsFalse && TVal->getZExtValue() != 1)
23678 if (!FValIsFalse && TVal->getZExtValue() != 0)
23680 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23681 if (needOppositeCond)
23682 CC = X86::GetOppositeBranchCondition(CC);
23683 return SetCC.getOperand(3);
23690 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23692 /// (X86or (X86setcc) (X86setcc))
23693 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
23694 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23695 X86::CondCode &CC1, SDValue &Flags,
23697 if (Cond->getOpcode() == X86ISD::CMP) {
23698 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23699 if (!CondOp1C || !CondOp1C->isNullValue())
23702 Cond = Cond->getOperand(0);
23707 SDValue SetCC0, SetCC1;
23708 switch (Cond->getOpcode()) {
23709 default: return false;
23716 SetCC0 = Cond->getOperand(0);
23717 SetCC1 = Cond->getOperand(1);
23721 // Make sure we have SETCC nodes, using the same flags value.
23722 if (SetCC0.getOpcode() != X86ISD::SETCC ||
23723 SetCC1.getOpcode() != X86ISD::SETCC ||
23724 SetCC0->getOperand(1) != SetCC1->getOperand(1))
23727 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23728 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23729 Flags = SetCC0->getOperand(1);
23733 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23734 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23735 TargetLowering::DAGCombinerInfo &DCI,
23736 const X86Subtarget *Subtarget) {
23739 // If the flag operand isn't dead, don't touch this CMOV.
23740 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23743 SDValue FalseOp = N->getOperand(0);
23744 SDValue TrueOp = N->getOperand(1);
23745 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23746 SDValue Cond = N->getOperand(3);
23748 if (CC == X86::COND_E || CC == X86::COND_NE) {
23749 switch (Cond.getOpcode()) {
23753 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23754 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23755 return (CC == X86::COND_E) ? FalseOp : TrueOp;
23761 Flags = checkBoolTestSetCCCombine(Cond, CC);
23762 if (Flags.getNode() &&
23763 // Extra check as FCMOV only supports a subset of X86 cond.
23764 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23765 SDValue Ops[] = { FalseOp, TrueOp,
23766 DAG.getConstant(CC, DL, MVT::i8), Flags };
23767 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23770 // If this is a select between two integer constants, try to do some
23771 // optimizations. Note that the operands are ordered the opposite of SELECT
23773 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23774 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23775 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23776 // larger than FalseC (the false value).
23777 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23778 CC = X86::GetOppositeBranchCondition(CC);
23779 std::swap(TrueC, FalseC);
23780 std::swap(TrueOp, FalseOp);
23783 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
23784 // This is efficient for any integer data type (including i8/i16) and
23786 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23787 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23788 DAG.getConstant(CC, DL, MVT::i8), Cond);
23790 // Zero extend the condition if needed.
23791 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23793 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23794 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23795 DAG.getConstant(ShAmt, DL, MVT::i8));
23796 if (N->getNumValues() == 2) // Dead flag value?
23797 return DCI.CombineTo(N, Cond, SDValue());
23801 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
23802 // for any integer data type, including i8/i16.
23803 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23804 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23805 DAG.getConstant(CC, DL, MVT::i8), Cond);
23807 // Zero extend the condition if needed.
23808 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23809 FalseC->getValueType(0), Cond);
23810 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23811 SDValue(FalseC, 0));
23813 if (N->getNumValues() == 2) // Dead flag value?
23814 return DCI.CombineTo(N, Cond, SDValue());
23818 // Optimize cases that will turn into an LEA instruction. This requires
23819 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23820 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23821 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23822 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23824 bool isFastMultiplier = false;
23826 switch ((unsigned char)Diff) {
23828 case 1: // result = add base, cond
23829 case 2: // result = lea base( , cond*2)
23830 case 3: // result = lea base(cond, cond*2)
23831 case 4: // result = lea base( , cond*4)
23832 case 5: // result = lea base(cond, cond*4)
23833 case 8: // result = lea base( , cond*8)
23834 case 9: // result = lea base(cond, cond*8)
23835 isFastMultiplier = true;
23840 if (isFastMultiplier) {
23841 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23842 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23843 DAG.getConstant(CC, DL, MVT::i8), Cond);
23844 // Zero extend the condition if needed.
23845 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23847 // Scale the condition by the difference.
23849 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23850 DAG.getConstant(Diff, DL, Cond.getValueType()));
23852 // Add the base if non-zero.
23853 if (FalseC->getAPIntValue() != 0)
23854 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23855 SDValue(FalseC, 0));
23856 if (N->getNumValues() == 2) // Dead flag value?
23857 return DCI.CombineTo(N, Cond, SDValue());
23864 // Handle these cases:
23865 // (select (x != c), e, c) -> select (x != c), e, x),
23866 // (select (x == c), c, e) -> select (x == c), x, e)
23867 // where the c is an integer constant, and the "select" is the combination
23868 // of CMOV and CMP.
23870 // The rationale for this change is that the conditional-move from a constant
23871 // needs two instructions, however, conditional-move from a register needs
23872 // only one instruction.
23874 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23875 // some instruction-combining opportunities. This opt needs to be
23876 // postponed as late as possible.
23878 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23879 // the DCI.xxxx conditions are provided to postpone the optimization as
23880 // late as possible.
23882 ConstantSDNode *CmpAgainst = nullptr;
23883 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23884 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23885 !isa<ConstantSDNode>(Cond.getOperand(0))) {
23887 if (CC == X86::COND_NE &&
23888 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23889 CC = X86::GetOppositeBranchCondition(CC);
23890 std::swap(TrueOp, FalseOp);
23893 if (CC == X86::COND_E &&
23894 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23895 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23896 DAG.getConstant(CC, DL, MVT::i8), Cond };
23897 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23902 // Fold and/or of setcc's to double CMOV:
23903 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23904 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23906 // This combine lets us generate:
23907 // cmovcc1 (jcc1 if we don't have CMOV)
23913 // cmovne (jne if we don't have CMOV)
23914 // When we can't use the CMOV instruction, it might increase branch
23916 // When we can use CMOV, or when there is no mispredict, this improves
23917 // throughput and reduces register pressure.
23919 if (CC == X86::COND_NE) {
23921 X86::CondCode CC0, CC1;
23923 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23925 std::swap(FalseOp, TrueOp);
23926 CC0 = X86::GetOppositeBranchCondition(CC0);
23927 CC1 = X86::GetOppositeBranchCondition(CC1);
23930 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23932 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23933 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23934 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23935 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23943 /// PerformMulCombine - Optimize a single multiply with constant into two
23944 /// in order to implement it with two cheaper instructions, e.g.
23945 /// LEA + SHL, LEA + LEA.
23946 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23947 TargetLowering::DAGCombinerInfo &DCI) {
23948 // An imul is usually smaller than the alternative sequence.
23949 if (DAG.getMachineFunction().getFunction()->optForMinSize())
23952 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23955 EVT VT = N->getValueType(0);
23956 if (VT != MVT::i64 && VT != MVT::i32)
23959 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23962 uint64_t MulAmt = C->getZExtValue();
23963 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23966 uint64_t MulAmt1 = 0;
23967 uint64_t MulAmt2 = 0;
23968 if ((MulAmt % 9) == 0) {
23970 MulAmt2 = MulAmt / 9;
23971 } else if ((MulAmt % 5) == 0) {
23973 MulAmt2 = MulAmt / 5;
23974 } else if ((MulAmt % 3) == 0) {
23976 MulAmt2 = MulAmt / 3;
23979 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23982 if (isPowerOf2_64(MulAmt2) &&
23983 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23984 // If second multiplifer is pow2, issue it first. We want the multiply by
23985 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23987 std::swap(MulAmt1, MulAmt2);
23990 if (isPowerOf2_64(MulAmt1))
23991 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23992 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23994 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23995 DAG.getConstant(MulAmt1, DL, VT));
23997 if (isPowerOf2_64(MulAmt2))
23998 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23999 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
24001 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
24002 DAG.getConstant(MulAmt2, DL, VT));
24004 // Do not add new nodes to DAG combiner worklist.
24005 DCI.CombineTo(N, NewMul, false);
24010 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
24011 SDValue N0 = N->getOperand(0);
24012 SDValue N1 = N->getOperand(1);
24013 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
24014 EVT VT = N0.getValueType();
24016 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
24017 // since the result of setcc_c is all zero's or all ones.
24018 if (VT.isInteger() && !VT.isVector() &&
24019 N1C && N0.getOpcode() == ISD::AND &&
24020 N0.getOperand(1).getOpcode() == ISD::Constant) {
24021 SDValue N00 = N0.getOperand(0);
24022 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
24023 APInt ShAmt = N1C->getAPIntValue();
24024 Mask = Mask.shl(ShAmt);
24025 bool MaskOK = false;
24026 // We can handle cases concerning bit-widening nodes containing setcc_c if
24027 // we carefully interrogate the mask to make sure we are semantics
24029 // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
24030 // of the underlying setcc_c operation if the setcc_c was zero extended.
24031 // Consider the following example:
24032 // zext(setcc_c) -> i32 0x0000FFFF
24033 // c1 -> i32 0x0000FFFF
24034 // c2 -> i32 0x00000001
24035 // (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
24036 // (and setcc_c, (c1 << c2)) -> i32 0x0000FFFE
24037 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24039 } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
24040 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24042 } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
24043 N00.getOpcode() == ISD::ANY_EXTEND) &&
24044 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24045 MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
24047 if (MaskOK && Mask != 0) {
24049 return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
24053 // Hardware support for vector shifts is sparse which makes us scalarize the
24054 // vector operations in many cases. Also, on sandybridge ADD is faster than
24056 // (shl V, 1) -> add V,V
24057 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24058 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24059 assert(N0.getValueType().isVector() && "Invalid vector shift type");
24060 // We shift all of the values by one. In many cases we do not have
24061 // hardware support for this operation. This is better expressed as an ADD
24063 if (N1SplatC->getAPIntValue() == 1)
24064 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24070 /// \brief Returns a vector of 0s if the node in input is a vector logical
24071 /// shift by a constant amount which is known to be bigger than or equal
24072 /// to the vector element size in bits.
24073 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24074 const X86Subtarget *Subtarget) {
24075 EVT VT = N->getValueType(0);
24077 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24078 (!Subtarget->hasInt256() ||
24079 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24082 SDValue Amt = N->getOperand(1);
24084 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24085 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24086 APInt ShiftAmt = AmtSplat->getAPIntValue();
24087 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
24089 // SSE2/AVX2 logical shifts always return a vector of 0s
24090 // if the shift amount is bigger than or equal to
24091 // the element size. The constant shift amount will be
24092 // encoded as a 8-bit immediate.
24093 if (ShiftAmt.trunc(8).uge(MaxAmount))
24094 return getZeroVector(VT, Subtarget, DAG, DL);
24100 /// PerformShiftCombine - Combine shifts.
24101 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24102 TargetLowering::DAGCombinerInfo &DCI,
24103 const X86Subtarget *Subtarget) {
24104 if (N->getOpcode() == ISD::SHL)
24105 if (SDValue V = PerformSHLCombine(N, DAG))
24108 // Try to fold this logical shift into a zero vector.
24109 if (N->getOpcode() != ISD::SRA)
24110 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
24116 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
24117 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24118 // and friends. Likewise for OR -> CMPNEQSS.
24119 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24120 TargetLowering::DAGCombinerInfo &DCI,
24121 const X86Subtarget *Subtarget) {
24124 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24125 // we're requiring SSE2 for both.
24126 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24127 SDValue N0 = N->getOperand(0);
24128 SDValue N1 = N->getOperand(1);
24129 SDValue CMP0 = N0->getOperand(1);
24130 SDValue CMP1 = N1->getOperand(1);
24133 // The SETCCs should both refer to the same CMP.
24134 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24137 SDValue CMP00 = CMP0->getOperand(0);
24138 SDValue CMP01 = CMP0->getOperand(1);
24139 EVT VT = CMP00.getValueType();
24141 if (VT == MVT::f32 || VT == MVT::f64) {
24142 bool ExpectingFlags = false;
24143 // Check for any users that want flags:
24144 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24145 !ExpectingFlags && UI != UE; ++UI)
24146 switch (UI->getOpcode()) {
24151 ExpectingFlags = true;
24153 case ISD::CopyToReg:
24154 case ISD::SIGN_EXTEND:
24155 case ISD::ZERO_EXTEND:
24156 case ISD::ANY_EXTEND:
24160 if (!ExpectingFlags) {
24161 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24162 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24164 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24165 X86::CondCode tmp = cc0;
24170 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
24171 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24172 // FIXME: need symbolic constants for these magic numbers.
24173 // See X86ATTInstPrinter.cpp:printSSECC().
24174 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24175 if (Subtarget->hasAVX512()) {
24176 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24178 DAG.getConstant(x86cc, DL, MVT::i8));
24179 if (N->getValueType(0) != MVT::i1)
24180 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24184 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24185 CMP00.getValueType(), CMP00, CMP01,
24186 DAG.getConstant(x86cc, DL,
24189 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24190 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24192 if (is64BitFP && !Subtarget->is64Bit()) {
24193 // On a 32-bit target, we cannot bitcast the 64-bit float to a
24194 // 64-bit integer, since that's not a legal type. Since
24195 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24196 // bits, but can do this little dance to extract the lowest 32 bits
24197 // and work with those going forward.
24198 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24200 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
24201 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24202 Vector32, DAG.getIntPtrConstant(0, DL));
24206 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
24207 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24208 DAG.getConstant(1, DL, IntVT));
24209 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
24211 return OneBitOfTruth;
24219 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24220 /// so it can be folded inside ANDNP.
24221 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24222 EVT VT = N->getValueType(0);
24224 // Match direct AllOnes for 128 and 256-bit vectors
24225 if (ISD::isBuildVectorAllOnes(N))
24228 // Look through a bit convert.
24229 if (N->getOpcode() == ISD::BITCAST)
24230 N = N->getOperand(0).getNode();
24232 // Sometimes the operand may come from a insert_subvector building a 256-bit
24234 if (VT.is256BitVector() &&
24235 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24236 SDValue V1 = N->getOperand(0);
24237 SDValue V2 = N->getOperand(1);
24239 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24240 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24241 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24242 ISD::isBuildVectorAllOnes(V2.getNode()))
24249 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24250 // register. In most cases we actually compare or select YMM-sized registers
24251 // and mixing the two types creates horrible code. This method optimizes
24252 // some of the transition sequences.
24253 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24254 TargetLowering::DAGCombinerInfo &DCI,
24255 const X86Subtarget *Subtarget) {
24256 EVT VT = N->getValueType(0);
24257 if (!VT.is256BitVector())
24260 assert((N->getOpcode() == ISD::ANY_EXTEND ||
24261 N->getOpcode() == ISD::ZERO_EXTEND ||
24262 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24264 SDValue Narrow = N->getOperand(0);
24265 EVT NarrowVT = Narrow->getValueType(0);
24266 if (!NarrowVT.is128BitVector())
24269 if (Narrow->getOpcode() != ISD::XOR &&
24270 Narrow->getOpcode() != ISD::AND &&
24271 Narrow->getOpcode() != ISD::OR)
24274 SDValue N0 = Narrow->getOperand(0);
24275 SDValue N1 = Narrow->getOperand(1);
24278 // The Left side has to be a trunc.
24279 if (N0.getOpcode() != ISD::TRUNCATE)
24282 // The type of the truncated inputs.
24283 EVT WideVT = N0->getOperand(0)->getValueType(0);
24287 // The right side has to be a 'trunc' or a constant vector.
24288 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24289 ConstantSDNode *RHSConstSplat = nullptr;
24290 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24291 RHSConstSplat = RHSBV->getConstantSplatNode();
24292 if (!RHSTrunc && !RHSConstSplat)
24295 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24297 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24300 // Set N0 and N1 to hold the inputs to the new wide operation.
24301 N0 = N0->getOperand(0);
24302 if (RHSConstSplat) {
24303 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24304 SDValue(RHSConstSplat, 0));
24305 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24306 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24307 } else if (RHSTrunc) {
24308 N1 = N1->getOperand(0);
24311 // Generate the wide operation.
24312 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24313 unsigned Opcode = N->getOpcode();
24315 case ISD::ANY_EXTEND:
24317 case ISD::ZERO_EXTEND: {
24318 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24319 APInt Mask = APInt::getAllOnesValue(InBits);
24320 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24321 return DAG.getNode(ISD::AND, DL, VT,
24322 Op, DAG.getConstant(Mask, DL, VT));
24324 case ISD::SIGN_EXTEND:
24325 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24326 Op, DAG.getValueType(NarrowVT));
24328 llvm_unreachable("Unexpected opcode");
24332 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24333 TargetLowering::DAGCombinerInfo &DCI,
24334 const X86Subtarget *Subtarget) {
24335 SDValue N0 = N->getOperand(0);
24336 SDValue N1 = N->getOperand(1);
24339 // A vector zext_in_reg may be represented as a shuffle,
24340 // feeding into a bitcast (this represents anyext) feeding into
24341 // an and with a mask.
24342 // We'd like to try to combine that into a shuffle with zero
24343 // plus a bitcast, removing the and.
24344 if (N0.getOpcode() != ISD::BITCAST ||
24345 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24348 // The other side of the AND should be a splat of 2^C, where C
24349 // is the number of bits in the source type.
24350 if (N1.getOpcode() == ISD::BITCAST)
24351 N1 = N1.getOperand(0);
24352 if (N1.getOpcode() != ISD::BUILD_VECTOR)
24354 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24356 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24357 EVT SrcType = Shuffle->getValueType(0);
24359 // We expect a single-source shuffle
24360 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24363 unsigned SrcSize = SrcType.getScalarSizeInBits();
24365 APInt SplatValue, SplatUndef;
24366 unsigned SplatBitSize;
24368 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24369 SplatBitSize, HasAnyUndefs))
24372 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24373 // Make sure the splat matches the mask we expect
24374 if (SplatBitSize > ResSize ||
24375 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24378 // Make sure the input and output size make sense
24379 if (SrcSize >= ResSize || ResSize % SrcSize)
24382 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24383 // The number of u's between each two values depends on the ratio between
24384 // the source and dest type.
24385 unsigned ZextRatio = ResSize / SrcSize;
24386 bool IsZext = true;
24387 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24388 if (i % ZextRatio) {
24389 if (Shuffle->getMaskElt(i) > 0) {
24395 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24396 // Expected element number
24406 // Ok, perform the transformation - replace the shuffle with
24407 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24408 // (instead of undef) where the k elements come from the zero vector.
24409 SmallVector<int, 8> Mask;
24410 unsigned NumElems = SrcType.getVectorNumElements();
24411 for (unsigned i = 0; i < NumElems; ++i)
24413 Mask.push_back(NumElems);
24415 Mask.push_back(i / ZextRatio);
24417 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24418 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24419 return DAG.getBitcast(N0.getValueType(), NewShuffle);
24422 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24423 TargetLowering::DAGCombinerInfo &DCI,
24424 const X86Subtarget *Subtarget) {
24425 if (DCI.isBeforeLegalizeOps())
24428 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24431 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24434 EVT VT = N->getValueType(0);
24435 SDValue N0 = N->getOperand(0);
24436 SDValue N1 = N->getOperand(1);
24439 // Create BEXTR instructions
24440 // BEXTR is ((X >> imm) & (2**size-1))
24441 if (VT == MVT::i32 || VT == MVT::i64) {
24442 // Check for BEXTR.
24443 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24444 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24445 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24446 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24447 if (MaskNode && ShiftNode) {
24448 uint64_t Mask = MaskNode->getZExtValue();
24449 uint64_t Shift = ShiftNode->getZExtValue();
24450 if (isMask_64(Mask)) {
24451 uint64_t MaskSize = countPopulation(Mask);
24452 if (Shift + MaskSize <= VT.getSizeInBits())
24453 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24454 DAG.getConstant(Shift | (MaskSize << 8), DL,
24463 // Want to form ANDNP nodes:
24464 // 1) In the hopes of then easily combining them with OR and AND nodes
24465 // to form PBLEND/PSIGN.
24466 // 2) To match ANDN packed intrinsics
24467 if (VT != MVT::v2i64 && VT != MVT::v4i64)
24470 // Check LHS for vnot
24471 if (N0.getOpcode() == ISD::XOR &&
24472 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24473 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24474 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24476 // Check RHS for vnot
24477 if (N1.getOpcode() == ISD::XOR &&
24478 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24479 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24480 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24485 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24486 TargetLowering::DAGCombinerInfo &DCI,
24487 const X86Subtarget *Subtarget) {
24488 if (DCI.isBeforeLegalizeOps())
24491 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24494 SDValue N0 = N->getOperand(0);
24495 SDValue N1 = N->getOperand(1);
24496 EVT VT = N->getValueType(0);
24498 // look for psign/blend
24499 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24500 if (!Subtarget->hasSSSE3() ||
24501 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24504 // Canonicalize pandn to RHS
24505 if (N0.getOpcode() == X86ISD::ANDNP)
24507 // or (and (m, y), (pandn m, x))
24508 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24509 SDValue Mask = N1.getOperand(0);
24510 SDValue X = N1.getOperand(1);
24512 if (N0.getOperand(0) == Mask)
24513 Y = N0.getOperand(1);
24514 if (N0.getOperand(1) == Mask)
24515 Y = N0.getOperand(0);
24517 // Check to see if the mask appeared in both the AND and ANDNP and
24521 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24522 // Look through mask bitcast.
24523 if (Mask.getOpcode() == ISD::BITCAST)
24524 Mask = Mask.getOperand(0);
24525 if (X.getOpcode() == ISD::BITCAST)
24526 X = X.getOperand(0);
24527 if (Y.getOpcode() == ISD::BITCAST)
24528 Y = Y.getOperand(0);
24530 EVT MaskVT = Mask.getValueType();
24532 // Validate that the Mask operand is a vector sra node.
24533 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24534 // there is no psrai.b
24535 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24536 unsigned SraAmt = ~0;
24537 if (Mask.getOpcode() == ISD::SRA) {
24538 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24539 if (auto *AmtConst = AmtBV->getConstantSplatNode())
24540 SraAmt = AmtConst->getZExtValue();
24541 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24542 SDValue SraC = Mask.getOperand(1);
24543 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
24545 if ((SraAmt + 1) != EltBits)
24550 // Now we know we at least have a plendvb with the mask val. See if
24551 // we can form a psignb/w/d.
24552 // psign = x.type == y.type == mask.type && y = sub(0, x);
24553 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24554 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24555 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24556 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24557 "Unsupported VT for PSIGN");
24558 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24559 return DAG.getBitcast(VT, Mask);
24561 // PBLENDVB only available on SSE 4.1
24562 if (!Subtarget->hasSSE41())
24565 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24567 X = DAG.getBitcast(BlendVT, X);
24568 Y = DAG.getBitcast(BlendVT, Y);
24569 Mask = DAG.getBitcast(BlendVT, Mask);
24570 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24571 return DAG.getBitcast(VT, Mask);
24575 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24578 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24579 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24581 // SHLD/SHRD instructions have lower register pressure, but on some
24582 // platforms they have higher latency than the equivalent
24583 // series of shifts/or that would otherwise be generated.
24584 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24585 // have higher latencies and we are not optimizing for size.
24586 if (!OptForSize && Subtarget->isSHLDSlow())
24589 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24591 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24593 if (!N0.hasOneUse() || !N1.hasOneUse())
24596 SDValue ShAmt0 = N0.getOperand(1);
24597 if (ShAmt0.getValueType() != MVT::i8)
24599 SDValue ShAmt1 = N1.getOperand(1);
24600 if (ShAmt1.getValueType() != MVT::i8)
24602 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24603 ShAmt0 = ShAmt0.getOperand(0);
24604 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24605 ShAmt1 = ShAmt1.getOperand(0);
24608 unsigned Opc = X86ISD::SHLD;
24609 SDValue Op0 = N0.getOperand(0);
24610 SDValue Op1 = N1.getOperand(0);
24611 if (ShAmt0.getOpcode() == ISD::SUB) {
24612 Opc = X86ISD::SHRD;
24613 std::swap(Op0, Op1);
24614 std::swap(ShAmt0, ShAmt1);
24617 unsigned Bits = VT.getSizeInBits();
24618 if (ShAmt1.getOpcode() == ISD::SUB) {
24619 SDValue Sum = ShAmt1.getOperand(0);
24620 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24621 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24622 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24623 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24624 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24625 return DAG.getNode(Opc, DL, VT,
24627 DAG.getNode(ISD::TRUNCATE, DL,
24630 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24631 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24633 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24634 return DAG.getNode(Opc, DL, VT,
24635 N0.getOperand(0), N1.getOperand(0),
24636 DAG.getNode(ISD::TRUNCATE, DL,
24643 // Generate NEG and CMOV for integer abs.
24644 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24645 EVT VT = N->getValueType(0);
24647 // Since X86 does not have CMOV for 8-bit integer, we don't convert
24648 // 8-bit integer abs to NEG and CMOV.
24649 if (VT.isInteger() && VT.getSizeInBits() == 8)
24652 SDValue N0 = N->getOperand(0);
24653 SDValue N1 = N->getOperand(1);
24656 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24657 // and change it to SUB and CMOV.
24658 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24659 N0.getOpcode() == ISD::ADD &&
24660 N0.getOperand(1) == N1 &&
24661 N1.getOpcode() == ISD::SRA &&
24662 N1.getOperand(0) == N0.getOperand(0))
24663 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24664 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24665 // Generate SUB & CMOV.
24666 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24667 DAG.getConstant(0, DL, VT), N0.getOperand(0));
24669 SDValue Ops[] = { N0.getOperand(0), Neg,
24670 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24671 SDValue(Neg.getNode(), 1) };
24672 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24677 // Try to turn tests against the signbit in the form of:
24678 // XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24681 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24682 // This is only worth doing if the output type is i8.
24683 if (N->getValueType(0) != MVT::i8)
24686 SDValue N0 = N->getOperand(0);
24687 SDValue N1 = N->getOperand(1);
24689 // We should be performing an xor against a truncated shift.
24690 if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24693 // Make sure we are performing an xor against one.
24694 if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24697 // SetCC on x86 zero extends so only act on this if it's a logical shift.
24698 SDValue Shift = N0.getOperand(0);
24699 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24702 // Make sure we are truncating from one of i16, i32 or i64.
24703 EVT ShiftTy = Shift.getValueType();
24704 if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24707 // Make sure the shift amount extracts the sign bit.
24708 if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24709 Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24712 // Create a greater-than comparison against -1.
24713 // N.B. Using SETGE against 0 works but we want a canonical looking
24714 // comparison, using SETGT matches up with what TranslateX86CC.
24716 SDValue ShiftOp = Shift.getOperand(0);
24717 EVT ShiftOpTy = ShiftOp.getValueType();
24718 SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24719 DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24723 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24724 TargetLowering::DAGCombinerInfo &DCI,
24725 const X86Subtarget *Subtarget) {
24726 if (DCI.isBeforeLegalizeOps())
24729 if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24732 if (Subtarget->hasCMov())
24733 if (SDValue RV = performIntegerAbsCombine(N, DAG))
24739 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24740 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24741 TargetLowering::DAGCombinerInfo &DCI,
24742 const X86Subtarget *Subtarget) {
24743 LoadSDNode *Ld = cast<LoadSDNode>(N);
24744 EVT RegVT = Ld->getValueType(0);
24745 EVT MemVT = Ld->getMemoryVT();
24747 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24749 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24750 // into two 16-byte operations.
24751 ISD::LoadExtType Ext = Ld->getExtensionType();
24753 unsigned AddressSpace = Ld->getAddressSpace();
24754 unsigned Alignment = Ld->getAlignment();
24755 if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24756 Ext == ISD::NON_EXTLOAD &&
24757 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24758 AddressSpace, Alignment, &Fast) && !Fast) {
24759 unsigned NumElems = RegVT.getVectorNumElements();
24763 SDValue Ptr = Ld->getBasePtr();
24764 SDValue Increment =
24765 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24767 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24769 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24770 Ld->getPointerInfo(), Ld->isVolatile(),
24771 Ld->isNonTemporal(), Ld->isInvariant(),
24773 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24774 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24775 Ld->getPointerInfo(), Ld->isVolatile(),
24776 Ld->isNonTemporal(), Ld->isInvariant(),
24777 std::min(16U, Alignment));
24778 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24780 Load2.getValue(1));
24782 SDValue NewVec = DAG.getUNDEF(RegVT);
24783 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24784 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24785 return DCI.CombineTo(N, NewVec, TF, true);
24791 /// PerformMLOADCombine - Resolve extending loads
24792 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24793 TargetLowering::DAGCombinerInfo &DCI,
24794 const X86Subtarget *Subtarget) {
24795 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24796 if (Mld->getExtensionType() != ISD::SEXTLOAD)
24799 EVT VT = Mld->getValueType(0);
24800 unsigned NumElems = VT.getVectorNumElements();
24801 EVT LdVT = Mld->getMemoryVT();
24804 assert(LdVT != VT && "Cannot extend to the same type");
24805 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24806 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24807 // From, To sizes and ElemCount must be pow of two
24808 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24809 "Unexpected size for extending masked load");
24811 unsigned SizeRatio = ToSz / FromSz;
24812 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24814 // Create a type on which we perform the shuffle
24815 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24816 LdVT.getScalarType(), NumElems*SizeRatio);
24817 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24819 // Convert Src0 value
24820 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24821 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24822 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24823 for (unsigned i = 0; i != NumElems; ++i)
24824 ShuffleVec[i] = i * SizeRatio;
24826 // Can't shuffle using an illegal type.
24827 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24828 && "WideVecVT should be legal");
24829 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24830 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24832 // Prepare the new mask
24834 SDValue Mask = Mld->getMask();
24835 if (Mask.getValueType() == VT) {
24836 // Mask and original value have the same type
24837 NewMask = DAG.getBitcast(WideVecVT, Mask);
24838 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24839 for (unsigned i = 0; i != NumElems; ++i)
24840 ShuffleVec[i] = i * SizeRatio;
24841 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24842 ShuffleVec[i] = NumElems*SizeRatio;
24843 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24844 DAG.getConstant(0, dl, WideVecVT),
24848 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24849 unsigned WidenNumElts = NumElems*SizeRatio;
24850 unsigned MaskNumElts = VT.getVectorNumElements();
24851 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24854 unsigned NumConcat = WidenNumElts / MaskNumElts;
24855 SmallVector<SDValue, 16> Ops(NumConcat);
24856 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24858 for (unsigned i = 1; i != NumConcat; ++i)
24861 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24864 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24865 Mld->getBasePtr(), NewMask, WideSrc0,
24866 Mld->getMemoryVT(), Mld->getMemOperand(),
24868 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24869 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24872 /// PerformMSTORECombine - Resolve truncating stores
24873 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24874 const X86Subtarget *Subtarget) {
24875 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24876 if (!Mst->isTruncatingStore())
24879 EVT VT = Mst->getValue().getValueType();
24880 unsigned NumElems = VT.getVectorNumElements();
24881 EVT StVT = Mst->getMemoryVT();
24884 assert(StVT != VT && "Cannot truncate to the same type");
24885 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24886 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24888 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24890 // The truncating store is legal in some cases. For example
24891 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24892 // are designated for truncate store.
24893 // In this case we don't need any further transformations.
24894 if (TLI.isTruncStoreLegal(VT, StVT))
24897 // From, To sizes and ElemCount must be pow of two
24898 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24899 "Unexpected size for truncating masked store");
24900 // We are going to use the original vector elt for storing.
24901 // Accumulated smaller vector elements must be a multiple of the store size.
24902 assert (((NumElems * FromSz) % ToSz) == 0 &&
24903 "Unexpected ratio for truncating masked store");
24905 unsigned SizeRatio = FromSz / ToSz;
24906 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24908 // Create a type on which we perform the shuffle
24909 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24910 StVT.getScalarType(), NumElems*SizeRatio);
24912 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24914 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24915 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24916 for (unsigned i = 0; i != NumElems; ++i)
24917 ShuffleVec[i] = i * SizeRatio;
24919 // Can't shuffle using an illegal type.
24920 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24921 && "WideVecVT should be legal");
24923 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24924 DAG.getUNDEF(WideVecVT),
24928 SDValue Mask = Mst->getMask();
24929 if (Mask.getValueType() == VT) {
24930 // Mask and original value have the same type
24931 NewMask = DAG.getBitcast(WideVecVT, Mask);
24932 for (unsigned i = 0; i != NumElems; ++i)
24933 ShuffleVec[i] = i * SizeRatio;
24934 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24935 ShuffleVec[i] = NumElems*SizeRatio;
24936 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24937 DAG.getConstant(0, dl, WideVecVT),
24941 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24942 unsigned WidenNumElts = NumElems*SizeRatio;
24943 unsigned MaskNumElts = VT.getVectorNumElements();
24944 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24947 unsigned NumConcat = WidenNumElts / MaskNumElts;
24948 SmallVector<SDValue, 16> Ops(NumConcat);
24949 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24951 for (unsigned i = 1; i != NumConcat; ++i)
24954 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24957 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24958 NewMask, StVT, Mst->getMemOperand(), false);
24960 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24961 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24962 const X86Subtarget *Subtarget) {
24963 StoreSDNode *St = cast<StoreSDNode>(N);
24964 EVT VT = St->getValue().getValueType();
24965 EVT StVT = St->getMemoryVT();
24967 SDValue StoredVal = St->getOperand(1);
24968 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24970 // If we are saving a concatenation of two XMM registers and 32-byte stores
24971 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24973 unsigned AddressSpace = St->getAddressSpace();
24974 unsigned Alignment = St->getAlignment();
24975 if (VT.is256BitVector() && StVT == VT &&
24976 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24977 AddressSpace, Alignment, &Fast) && !Fast) {
24978 unsigned NumElems = VT.getVectorNumElements();
24982 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24983 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24986 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24987 SDValue Ptr0 = St->getBasePtr();
24988 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24990 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24991 St->getPointerInfo(), St->isVolatile(),
24992 St->isNonTemporal(), Alignment);
24993 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24994 St->getPointerInfo(), St->isVolatile(),
24995 St->isNonTemporal(),
24996 std::min(16U, Alignment));
24997 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
25000 // Optimize trunc store (of multiple scalars) to shuffle and store.
25001 // First, pack all of the elements in one place. Next, store to memory
25002 // in fewer chunks.
25003 if (St->isTruncatingStore() && VT.isVector()) {
25004 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25005 unsigned NumElems = VT.getVectorNumElements();
25006 assert(StVT != VT && "Cannot truncate to the same type");
25007 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25008 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25010 // The truncating store is legal in some cases. For example
25011 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25012 // are designated for truncate store.
25013 // In this case we don't need any further transformations.
25014 if (TLI.isTruncStoreLegal(VT, StVT))
25017 // From, To sizes and ElemCount must be pow of two
25018 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
25019 // We are going to use the original vector elt for storing.
25020 // Accumulated smaller vector elements must be a multiple of the store size.
25021 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
25023 unsigned SizeRatio = FromSz / ToSz;
25025 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25027 // Create a type on which we perform the shuffle
25028 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25029 StVT.getScalarType(), NumElems*SizeRatio);
25031 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25033 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
25034 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
25035 for (unsigned i = 0; i != NumElems; ++i)
25036 ShuffleVec[i] = i * SizeRatio;
25038 // Can't shuffle using an illegal type.
25039 if (!TLI.isTypeLegal(WideVecVT))
25042 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25043 DAG.getUNDEF(WideVecVT),
25045 // At this point all of the data is stored at the bottom of the
25046 // register. We now need to save it to mem.
25048 // Find the largest store unit
25049 MVT StoreType = MVT::i8;
25050 for (MVT Tp : MVT::integer_valuetypes()) {
25051 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
25055 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
25056 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
25057 (64 <= NumElems * ToSz))
25058 StoreType = MVT::f64;
25060 // Bitcast the original vector into a vector of store-size units
25061 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
25062 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
25063 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
25064 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
25065 SmallVector<SDValue, 8> Chains;
25066 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
25067 TLI.getPointerTy(DAG.getDataLayout()));
25068 SDValue Ptr = St->getBasePtr();
25070 // Perform one or more big stores into memory.
25071 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
25072 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
25073 StoreType, ShuffWide,
25074 DAG.getIntPtrConstant(i, dl));
25075 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
25076 St->getPointerInfo(), St->isVolatile(),
25077 St->isNonTemporal(), St->getAlignment());
25078 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25079 Chains.push_back(Ch);
25082 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
25085 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
25086 // the FP state in cases where an emms may be missing.
25087 // A preferable solution to the general problem is to figure out the right
25088 // places to insert EMMS. This qualifies as a quick hack.
25090 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
25091 if (VT.getSizeInBits() != 64)
25094 const Function *F = DAG.getMachineFunction().getFunction();
25095 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
25097 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
25098 if ((VT.isVector() ||
25099 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
25100 isa<LoadSDNode>(St->getValue()) &&
25101 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
25102 St->getChain().hasOneUse() && !St->isVolatile()) {
25103 SDNode* LdVal = St->getValue().getNode();
25104 LoadSDNode *Ld = nullptr;
25105 int TokenFactorIndex = -1;
25106 SmallVector<SDValue, 8> Ops;
25107 SDNode* ChainVal = St->getChain().getNode();
25108 // Must be a store of a load. We currently handle two cases: the load
25109 // is a direct child, and it's under an intervening TokenFactor. It is
25110 // possible to dig deeper under nested TokenFactors.
25111 if (ChainVal == LdVal)
25112 Ld = cast<LoadSDNode>(St->getChain());
25113 else if (St->getValue().hasOneUse() &&
25114 ChainVal->getOpcode() == ISD::TokenFactor) {
25115 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
25116 if (ChainVal->getOperand(i).getNode() == LdVal) {
25117 TokenFactorIndex = i;
25118 Ld = cast<LoadSDNode>(St->getValue());
25120 Ops.push_back(ChainVal->getOperand(i));
25124 if (!Ld || !ISD::isNormalLoad(Ld))
25127 // If this is not the MMX case, i.e. we are just turning i64 load/store
25128 // into f64 load/store, avoid the transformation if there are multiple
25129 // uses of the loaded value.
25130 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
25135 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
25136 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
25138 if (Subtarget->is64Bit() || F64IsLegal) {
25139 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
25140 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
25141 Ld->getPointerInfo(), Ld->isVolatile(),
25142 Ld->isNonTemporal(), Ld->isInvariant(),
25143 Ld->getAlignment());
25144 SDValue NewChain = NewLd.getValue(1);
25145 if (TokenFactorIndex != -1) {
25146 Ops.push_back(NewChain);
25147 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25149 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
25150 St->getPointerInfo(),
25151 St->isVolatile(), St->isNonTemporal(),
25152 St->getAlignment());
25155 // Otherwise, lower to two pairs of 32-bit loads / stores.
25156 SDValue LoAddr = Ld->getBasePtr();
25157 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
25158 DAG.getConstant(4, LdDL, MVT::i32));
25160 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
25161 Ld->getPointerInfo(),
25162 Ld->isVolatile(), Ld->isNonTemporal(),
25163 Ld->isInvariant(), Ld->getAlignment());
25164 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
25165 Ld->getPointerInfo().getWithOffset(4),
25166 Ld->isVolatile(), Ld->isNonTemporal(),
25168 MinAlign(Ld->getAlignment(), 4));
25170 SDValue NewChain = LoLd.getValue(1);
25171 if (TokenFactorIndex != -1) {
25172 Ops.push_back(LoLd);
25173 Ops.push_back(HiLd);
25174 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25177 LoAddr = St->getBasePtr();
25178 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25179 DAG.getConstant(4, StDL, MVT::i32));
25181 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25182 St->getPointerInfo(),
25183 St->isVolatile(), St->isNonTemporal(),
25184 St->getAlignment());
25185 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25186 St->getPointerInfo().getWithOffset(4),
25188 St->isNonTemporal(),
25189 MinAlign(St->getAlignment(), 4));
25190 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25193 // This is similar to the above case, but here we handle a scalar 64-bit
25194 // integer store that is extracted from a vector on a 32-bit target.
25195 // If we have SSE2, then we can treat it like a floating-point double
25196 // to get past legalization. The execution dependencies fixup pass will
25197 // choose the optimal machine instruction for the store if this really is
25198 // an integer or v2f32 rather than an f64.
25199 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
25200 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25201 SDValue OldExtract = St->getOperand(1);
25202 SDValue ExtOp0 = OldExtract.getOperand(0);
25203 unsigned VecSize = ExtOp0.getValueSizeInBits();
25204 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
25205 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
25206 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
25207 BitCast, OldExtract.getOperand(1));
25208 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
25209 St->getPointerInfo(), St->isVolatile(),
25210 St->isNonTemporal(), St->getAlignment());
25216 /// Return 'true' if this vector operation is "horizontal"
25217 /// and return the operands for the horizontal operation in LHS and RHS. A
25218 /// horizontal operation performs the binary operation on successive elements
25219 /// of its first operand, then on successive elements of its second operand,
25220 /// returning the resulting values in a vector. For example, if
25221 /// A = < float a0, float a1, float a2, float a3 >
25223 /// B = < float b0, float b1, float b2, float b3 >
25224 /// then the result of doing a horizontal operation on A and B is
25225 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25226 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25227 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25228 /// set to A, RHS to B, and the routine returns 'true'.
25229 /// Note that the binary operation should have the property that if one of the
25230 /// operands is UNDEF then the result is UNDEF.
25231 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25232 // Look for the following pattern: if
25233 // A = < float a0, float a1, float a2, float a3 >
25234 // B = < float b0, float b1, float b2, float b3 >
25236 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25237 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25238 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25239 // which is A horizontal-op B.
25241 // At least one of the operands should be a vector shuffle.
25242 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25243 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25246 MVT VT = LHS.getSimpleValueType();
25248 assert((VT.is128BitVector() || VT.is256BitVector()) &&
25249 "Unsupported vector type for horizontal add/sub");
25251 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25252 // operate independently on 128-bit lanes.
25253 unsigned NumElts = VT.getVectorNumElements();
25254 unsigned NumLanes = VT.getSizeInBits()/128;
25255 unsigned NumLaneElts = NumElts / NumLanes;
25256 assert((NumLaneElts % 2 == 0) &&
25257 "Vector type should have an even number of elements in each lane");
25258 unsigned HalfLaneElts = NumLaneElts/2;
25260 // View LHS in the form
25261 // LHS = VECTOR_SHUFFLE A, B, LMask
25262 // If LHS is not a shuffle then pretend it is the shuffle
25263 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25264 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25267 SmallVector<int, 16> LMask(NumElts);
25268 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25269 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25270 A = LHS.getOperand(0);
25271 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25272 B = LHS.getOperand(1);
25273 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25274 std::copy(Mask.begin(), Mask.end(), LMask.begin());
25276 if (LHS.getOpcode() != ISD::UNDEF)
25278 for (unsigned i = 0; i != NumElts; ++i)
25282 // Likewise, view RHS in the form
25283 // RHS = VECTOR_SHUFFLE C, D, RMask
25285 SmallVector<int, 16> RMask(NumElts);
25286 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25287 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25288 C = RHS.getOperand(0);
25289 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25290 D = RHS.getOperand(1);
25291 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25292 std::copy(Mask.begin(), Mask.end(), RMask.begin());
25294 if (RHS.getOpcode() != ISD::UNDEF)
25296 for (unsigned i = 0; i != NumElts; ++i)
25300 // Check that the shuffles are both shuffling the same vectors.
25301 if (!(A == C && B == D) && !(A == D && B == C))
25304 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25305 if (!A.getNode() && !B.getNode())
25308 // If A and B occur in reverse order in RHS, then "swap" them (which means
25309 // rewriting the mask).
25311 ShuffleVectorSDNode::commuteMask(RMask);
25313 // At this point LHS and RHS are equivalent to
25314 // LHS = VECTOR_SHUFFLE A, B, LMask
25315 // RHS = VECTOR_SHUFFLE A, B, RMask
25316 // Check that the masks correspond to performing a horizontal operation.
25317 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25318 for (unsigned i = 0; i != NumLaneElts; ++i) {
25319 int LIdx = LMask[i+l], RIdx = RMask[i+l];
25321 // Ignore any UNDEF components.
25322 if (LIdx < 0 || RIdx < 0 ||
25323 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25324 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25327 // Check that successive elements are being operated on. If not, this is
25328 // not a horizontal operation.
25329 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25330 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25331 if (!(LIdx == Index && RIdx == Index + 1) &&
25332 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25337 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25338 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25342 /// Do target-specific dag combines on floating point adds.
25343 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25344 const X86Subtarget *Subtarget) {
25345 EVT VT = N->getValueType(0);
25346 SDValue LHS = N->getOperand(0);
25347 SDValue RHS = N->getOperand(1);
25349 // Try to synthesize horizontal adds from adds of shuffles.
25350 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25351 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25352 isHorizontalBinOp(LHS, RHS, true))
25353 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25357 /// Do target-specific dag combines on floating point subs.
25358 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25359 const X86Subtarget *Subtarget) {
25360 EVT VT = N->getValueType(0);
25361 SDValue LHS = N->getOperand(0);
25362 SDValue RHS = N->getOperand(1);
25364 // Try to synthesize horizontal subs from subs of shuffles.
25365 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25366 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25367 isHorizontalBinOp(LHS, RHS, false))
25368 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25372 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25373 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
25374 const X86Subtarget *Subtarget) {
25375 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25377 // F[X]OR(0.0, x) -> x
25378 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25379 if (C->getValueAPF().isPosZero())
25380 return N->getOperand(1);
25382 // F[X]OR(x, 0.0) -> x
25383 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25384 if (C->getValueAPF().isPosZero())
25385 return N->getOperand(0);
25387 EVT VT = N->getValueType(0);
25388 if (VT.is512BitVector() && !Subtarget->hasDQI()) {
25390 MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
25391 MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
25393 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
25394 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
25395 unsigned IntOpcode = (N->getOpcode() == X86ISD::FOR) ? ISD::OR : ISD::XOR;
25396 SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
25397 return DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
25402 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25403 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25404 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25406 // Only perform optimizations if UnsafeMath is used.
25407 if (!DAG.getTarget().Options.UnsafeFPMath)
25410 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25411 // into FMINC and FMAXC, which are Commutative operations.
25412 unsigned NewOp = 0;
25413 switch (N->getOpcode()) {
25414 default: llvm_unreachable("unknown opcode");
25415 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
25416 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
25419 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25420 N->getOperand(0), N->getOperand(1));
25423 /// Do target-specific dag combines on X86ISD::FAND nodes.
25424 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25425 // FAND(0.0, x) -> 0.0
25426 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25427 if (C->getValueAPF().isPosZero())
25428 return N->getOperand(0);
25430 // FAND(x, 0.0) -> 0.0
25431 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25432 if (C->getValueAPF().isPosZero())
25433 return N->getOperand(1);
25438 /// Do target-specific dag combines on X86ISD::FANDN nodes
25439 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25440 // FANDN(0.0, x) -> x
25441 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25442 if (C->getValueAPF().isPosZero())
25443 return N->getOperand(1);
25445 // FANDN(x, 0.0) -> 0.0
25446 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25447 if (C->getValueAPF().isPosZero())
25448 return N->getOperand(1);
25453 static SDValue PerformBTCombine(SDNode *N,
25455 TargetLowering::DAGCombinerInfo &DCI) {
25456 // BT ignores high bits in the bit index operand.
25457 SDValue Op1 = N->getOperand(1);
25458 if (Op1.hasOneUse()) {
25459 unsigned BitWidth = Op1.getValueSizeInBits();
25460 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25461 APInt KnownZero, KnownOne;
25462 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25463 !DCI.isBeforeLegalizeOps());
25464 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25465 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25466 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25467 DCI.CommitTargetLoweringOpt(TLO);
25472 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25473 SDValue Op = N->getOperand(0);
25474 if (Op.getOpcode() == ISD::BITCAST)
25475 Op = Op.getOperand(0);
25476 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25477 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25478 VT.getVectorElementType().getSizeInBits() ==
25479 OpVT.getVectorElementType().getSizeInBits()) {
25480 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25485 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25486 const X86Subtarget *Subtarget) {
25487 EVT VT = N->getValueType(0);
25488 if (!VT.isVector())
25491 SDValue N0 = N->getOperand(0);
25492 SDValue N1 = N->getOperand(1);
25493 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25496 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25497 // both SSE and AVX2 since there is no sign-extended shift right
25498 // operation on a vector with 64-bit elements.
25499 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25500 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25501 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25502 N0.getOpcode() == ISD::SIGN_EXTEND)) {
25503 SDValue N00 = N0.getOperand(0);
25505 // EXTLOAD has a better solution on AVX2,
25506 // it may be replaced with X86ISD::VSEXT node.
25507 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25508 if (!ISD::isNormalLoad(N00.getNode()))
25511 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25512 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25514 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25520 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25521 TargetLowering::DAGCombinerInfo &DCI,
25522 const X86Subtarget *Subtarget) {
25523 SDValue N0 = N->getOperand(0);
25524 EVT VT = N->getValueType(0);
25525 EVT SVT = VT.getScalarType();
25526 EVT InVT = N0.getValueType();
25527 EVT InSVT = InVT.getScalarType();
25530 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25531 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25532 // This exposes the sext to the sdivrem lowering, so that it directly extends
25533 // from AH (which we otherwise need to do contortions to access).
25534 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25535 InVT == MVT::i8 && VT == MVT::i32) {
25536 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25537 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25538 N0.getOperand(0), N0.getOperand(1));
25539 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25540 return R.getValue(1);
25543 if (!DCI.isBeforeLegalizeOps()) {
25544 if (InVT == MVT::i1) {
25545 SDValue Zero = DAG.getConstant(0, DL, VT);
25547 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25548 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25553 if (VT.isVector() && Subtarget->hasSSE2()) {
25554 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25555 EVT InVT = N.getValueType();
25556 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25557 Size / InVT.getScalarSizeInBits());
25558 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25559 DAG.getUNDEF(InVT));
25561 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25564 // If target-size is less than 128-bits, extend to a type that would extend
25565 // to 128 bits, extend that and extract the original target vector.
25566 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25567 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25568 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25569 unsigned Scale = 128 / VT.getSizeInBits();
25571 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25572 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25573 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25574 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25575 DAG.getIntPtrConstant(0, DL));
25578 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25579 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25580 if (VT.getSizeInBits() == 128 &&
25581 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25582 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25583 SDValue ExOp = ExtendVecSize(DL, N0, 128);
25584 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25587 // On pre-AVX2 targets, split into 128-bit nodes of
25588 // ISD::SIGN_EXTEND_VECTOR_INREG.
25589 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25590 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25591 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25592 unsigned NumVecs = VT.getSizeInBits() / 128;
25593 unsigned NumSubElts = 128 / SVT.getSizeInBits();
25594 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25595 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25597 SmallVector<SDValue, 8> Opnds;
25598 for (unsigned i = 0, Offset = 0; i != NumVecs;
25599 ++i, Offset += NumSubElts) {
25600 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25601 DAG.getIntPtrConstant(Offset, DL));
25602 SrcVec = ExtendVecSize(DL, SrcVec, 128);
25603 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25604 Opnds.push_back(SrcVec);
25606 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25610 if (!Subtarget->hasFp256())
25613 if (VT.isVector() && VT.getSizeInBits() == 256)
25614 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25620 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25621 const X86Subtarget* Subtarget) {
25623 EVT VT = N->getValueType(0);
25625 // Let legalize expand this if it isn't a legal type yet.
25626 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25629 EVT ScalarVT = VT.getScalarType();
25630 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25631 (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25632 !Subtarget->hasAVX512()))
25635 SDValue A = N->getOperand(0);
25636 SDValue B = N->getOperand(1);
25637 SDValue C = N->getOperand(2);
25639 bool NegA = (A.getOpcode() == ISD::FNEG);
25640 bool NegB = (B.getOpcode() == ISD::FNEG);
25641 bool NegC = (C.getOpcode() == ISD::FNEG);
25643 // Negative multiplication when NegA xor NegB
25644 bool NegMul = (NegA != NegB);
25646 A = A.getOperand(0);
25648 B = B.getOperand(0);
25650 C = C.getOperand(0);
25654 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25656 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25658 return DAG.getNode(Opcode, dl, VT, A, B, C);
25661 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25662 TargetLowering::DAGCombinerInfo &DCI,
25663 const X86Subtarget *Subtarget) {
25664 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
25665 // (and (i32 x86isd::setcc_carry), 1)
25666 // This eliminates the zext. This transformation is necessary because
25667 // ISD::SETCC is always legalized to i8.
25669 SDValue N0 = N->getOperand(0);
25670 EVT VT = N->getValueType(0);
25672 if (N0.getOpcode() == ISD::AND &&
25674 N0.getOperand(0).hasOneUse()) {
25675 SDValue N00 = N0.getOperand(0);
25676 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25677 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25678 if (!C || C->getZExtValue() != 1)
25680 return DAG.getNode(ISD::AND, dl, VT,
25681 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25682 N00.getOperand(0), N00.getOperand(1)),
25683 DAG.getConstant(1, dl, VT));
25687 if (N0.getOpcode() == ISD::TRUNCATE &&
25689 N0.getOperand(0).hasOneUse()) {
25690 SDValue N00 = N0.getOperand(0);
25691 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25692 return DAG.getNode(ISD::AND, dl, VT,
25693 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25694 N00.getOperand(0), N00.getOperand(1)),
25695 DAG.getConstant(1, dl, VT));
25699 if (VT.is256BitVector())
25700 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25703 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25704 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25705 // This exposes the zext to the udivrem lowering, so that it directly extends
25706 // from AH (which we otherwise need to do contortions to access).
25707 if (N0.getOpcode() == ISD::UDIVREM &&
25708 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25709 (VT == MVT::i32 || VT == MVT::i64)) {
25710 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25711 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25712 N0.getOperand(0), N0.getOperand(1));
25713 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25714 return R.getValue(1);
25720 // Optimize x == -y --> x+y == 0
25721 // x != -y --> x+y != 0
25722 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25723 const X86Subtarget* Subtarget) {
25724 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25725 SDValue LHS = N->getOperand(0);
25726 SDValue RHS = N->getOperand(1);
25727 EVT VT = N->getValueType(0);
25730 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25731 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25732 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25733 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25734 LHS.getOperand(1));
25735 return DAG.getSetCC(DL, N->getValueType(0), addV,
25736 DAG.getConstant(0, DL, addV.getValueType()), CC);
25738 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25739 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25740 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25741 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25742 RHS.getOperand(1));
25743 return DAG.getSetCC(DL, N->getValueType(0), addV,
25744 DAG.getConstant(0, DL, addV.getValueType()), CC);
25747 if (VT.getScalarType() == MVT::i1 &&
25748 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25750 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25751 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25752 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25754 if (!IsSEXT0 || !IsVZero1) {
25755 // Swap the operands and update the condition code.
25756 std::swap(LHS, RHS);
25757 CC = ISD::getSetCCSwappedOperands(CC);
25759 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25760 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25761 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25764 if (IsSEXT0 && IsVZero1) {
25765 assert(VT == LHS.getOperand(0).getValueType() &&
25766 "Uexpected operand type");
25767 if (CC == ISD::SETGT)
25768 return DAG.getConstant(0, DL, VT);
25769 if (CC == ISD::SETLE)
25770 return DAG.getConstant(1, DL, VT);
25771 if (CC == ISD::SETEQ || CC == ISD::SETGE)
25772 return DAG.getNOT(DL, LHS.getOperand(0), VT);
25774 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25775 "Unexpected condition code!");
25776 return LHS.getOperand(0);
25783 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25784 SelectionDAG &DAG) {
25786 MVT VT = Load->getSimpleValueType(0);
25787 MVT EVT = VT.getVectorElementType();
25788 SDValue Addr = Load->getOperand(1);
25789 SDValue NewAddr = DAG.getNode(
25790 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25791 DAG.getConstant(Index * EVT.getStoreSize(), dl,
25792 Addr.getSimpleValueType()));
25795 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25796 DAG.getMachineFunction().getMachineMemOperand(
25797 Load->getMemOperand(), 0, EVT.getStoreSize()));
25801 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25802 const X86Subtarget *Subtarget) {
25804 MVT VT = N->getOperand(1)->getSimpleValueType(0);
25805 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25806 "X86insertps is only defined for v4x32");
25808 SDValue Ld = N->getOperand(1);
25809 if (MayFoldLoad(Ld)) {
25810 // Extract the countS bits from the immediate so we can get the proper
25811 // address when narrowing the vector load to a specific element.
25812 // When the second source op is a memory address, insertps doesn't use
25813 // countS and just gets an f32 from that address.
25814 unsigned DestIndex =
25815 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25817 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25819 // Create this as a scalar to vector to match the instruction pattern.
25820 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25821 // countS bits are ignored when loading from memory on insertps, which
25822 // means we don't need to explicitly set them to 0.
25823 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25824 LoadScalarToVector, N->getOperand(2));
25829 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25830 SDValue V0 = N->getOperand(0);
25831 SDValue V1 = N->getOperand(1);
25833 EVT VT = N->getValueType(0);
25835 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25836 // operands and changing the mask to 1. This saves us a bunch of
25837 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25838 // x86InstrInfo knows how to commute this back after instruction selection
25839 // if it would help register allocation.
25841 // TODO: If optimizing for size or a processor that doesn't suffer from
25842 // partial register update stalls, this should be transformed into a MOVSD
25843 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25845 if (VT == MVT::v2f64)
25846 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25847 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25848 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25849 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25855 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25856 // as "sbb reg,reg", since it can be extended without zext and produces
25857 // an all-ones bit which is more useful than 0/1 in some cases.
25858 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25861 return DAG.getNode(ISD::AND, DL, VT,
25862 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25863 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25865 DAG.getConstant(1, DL, VT));
25866 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25867 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25868 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25869 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25873 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25874 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25875 TargetLowering::DAGCombinerInfo &DCI,
25876 const X86Subtarget *Subtarget) {
25878 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25879 SDValue EFLAGS = N->getOperand(1);
25881 if (CC == X86::COND_A) {
25882 // Try to convert COND_A into COND_B in an attempt to facilitate
25883 // materializing "setb reg".
25885 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25886 // cannot take an immediate as its first operand.
25888 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25889 EFLAGS.getValueType().isInteger() &&
25890 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25891 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25892 EFLAGS.getNode()->getVTList(),
25893 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25894 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25895 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25899 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25900 // a zext and produces an all-ones bit which is more useful than 0/1 in some
25902 if (CC == X86::COND_B)
25903 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25905 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25906 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25907 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25913 // Optimize branch condition evaluation.
25915 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25916 TargetLowering::DAGCombinerInfo &DCI,
25917 const X86Subtarget *Subtarget) {
25919 SDValue Chain = N->getOperand(0);
25920 SDValue Dest = N->getOperand(1);
25921 SDValue EFLAGS = N->getOperand(3);
25922 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25924 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25925 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25926 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25933 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25934 SelectionDAG &DAG) {
25935 // Take advantage of vector comparisons producing 0 or -1 in each lane to
25936 // optimize away operation when it's from a constant.
25938 // The general transformation is:
25939 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25940 // AND(VECTOR_CMP(x,y), constant2)
25941 // constant2 = UNARYOP(constant)
25943 // Early exit if this isn't a vector operation, the operand of the
25944 // unary operation isn't a bitwise AND, or if the sizes of the operations
25945 // aren't the same.
25946 EVT VT = N->getValueType(0);
25947 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25948 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25949 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25952 // Now check that the other operand of the AND is a constant. We could
25953 // make the transformation for non-constant splats as well, but it's unclear
25954 // that would be a benefit as it would not eliminate any operations, just
25955 // perform one more step in scalar code before moving to the vector unit.
25956 if (BuildVectorSDNode *BV =
25957 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25958 // Bail out if the vector isn't a constant.
25959 if (!BV->isConstant())
25962 // Everything checks out. Build up the new and improved node.
25964 EVT IntVT = BV->getValueType(0);
25965 // Create a new constant of the appropriate type for the transformed
25967 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25968 // The AND node needs bitcasts to/from an integer vector type around it.
25969 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25970 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25971 N->getOperand(0)->getOperand(0), MaskConst);
25972 SDValue Res = DAG.getBitcast(VT, NewAnd);
25979 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25980 const X86Subtarget *Subtarget) {
25981 SDValue Op0 = N->getOperand(0);
25982 EVT VT = N->getValueType(0);
25983 EVT InVT = Op0.getValueType();
25984 EVT InSVT = InVT.getScalarType();
25985 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25987 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25988 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25989 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25991 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25992 InVT.getVectorNumElements());
25993 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25995 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25996 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25998 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26004 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
26005 const X86Subtarget *Subtarget) {
26006 // First try to optimize away the conversion entirely when it's
26007 // conditionally from a constant. Vectors only.
26008 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
26011 // Now move on to more general possibilities.
26012 SDValue Op0 = N->getOperand(0);
26013 EVT VT = N->getValueType(0);
26014 EVT InVT = Op0.getValueType();
26015 EVT InSVT = InVT.getScalarType();
26017 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
26018 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
26019 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26021 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26022 InVT.getVectorNumElements());
26023 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
26024 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26027 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
26028 // a 32-bit target where SSE doesn't support i64->FP operations.
26029 if (Op0.getOpcode() == ISD::LOAD) {
26030 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
26031 EVT LdVT = Ld->getValueType(0);
26033 // This transformation is not supported if the result type is f16
26034 if (VT == MVT::f16)
26037 if (!Ld->isVolatile() && !VT.isVector() &&
26038 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
26039 !Subtarget->is64Bit() && LdVT == MVT::i64) {
26040 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
26041 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
26042 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
26049 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
26050 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
26051 X86TargetLowering::DAGCombinerInfo &DCI) {
26052 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
26053 // the result is either zero or one (depending on the input carry bit).
26054 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
26055 if (X86::isZeroNode(N->getOperand(0)) &&
26056 X86::isZeroNode(N->getOperand(1)) &&
26057 // We don't have a good way to replace an EFLAGS use, so only do this when
26059 SDValue(N, 1).use_empty()) {
26061 EVT VT = N->getValueType(0);
26062 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
26063 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
26064 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
26065 DAG.getConstant(X86::COND_B, DL,
26068 DAG.getConstant(1, DL, VT));
26069 return DCI.CombineTo(N, Res1, CarryOut);
26075 // fold (add Y, (sete X, 0)) -> adc 0, Y
26076 // (add Y, (setne X, 0)) -> sbb -1, Y
26077 // (sub (sete X, 0), Y) -> sbb 0, Y
26078 // (sub (setne X, 0), Y) -> adc -1, Y
26079 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
26082 // Look through ZExts.
26083 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
26084 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
26087 SDValue SetCC = Ext.getOperand(0);
26088 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
26091 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
26092 if (CC != X86::COND_E && CC != X86::COND_NE)
26095 SDValue Cmp = SetCC.getOperand(1);
26096 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
26097 !X86::isZeroNode(Cmp.getOperand(1)) ||
26098 !Cmp.getOperand(0).getValueType().isInteger())
26101 SDValue CmpOp0 = Cmp.getOperand(0);
26102 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
26103 DAG.getConstant(1, DL, CmpOp0.getValueType()));
26105 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
26106 if (CC == X86::COND_NE)
26107 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
26108 DL, OtherVal.getValueType(), OtherVal,
26109 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
26111 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
26112 DL, OtherVal.getValueType(), OtherVal,
26113 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
26116 /// PerformADDCombine - Do target-specific dag combines on integer adds.
26117 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
26118 const X86Subtarget *Subtarget) {
26119 EVT VT = N->getValueType(0);
26120 SDValue Op0 = N->getOperand(0);
26121 SDValue Op1 = N->getOperand(1);
26123 // Try to synthesize horizontal adds from adds of shuffles.
26124 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26125 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26126 isHorizontalBinOp(Op0, Op1, true))
26127 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
26129 return OptimizeConditionalInDecrement(N, DAG);
26132 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
26133 const X86Subtarget *Subtarget) {
26134 SDValue Op0 = N->getOperand(0);
26135 SDValue Op1 = N->getOperand(1);
26137 // X86 can't encode an immediate LHS of a sub. See if we can push the
26138 // negation into a preceding instruction.
26139 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
26140 // If the RHS of the sub is a XOR with one use and a constant, invert the
26141 // immediate. Then add one to the LHS of the sub so we can turn
26142 // X-Y -> X+~Y+1, saving one register.
26143 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
26144 isa<ConstantSDNode>(Op1.getOperand(1))) {
26145 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
26146 EVT VT = Op0.getValueType();
26147 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
26149 DAG.getConstant(~XorC, SDLoc(Op1), VT));
26150 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
26151 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
26155 // Try to synthesize horizontal adds from adds of shuffles.
26156 EVT VT = N->getValueType(0);
26157 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26158 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26159 isHorizontalBinOp(Op0, Op1, true))
26160 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
26162 return OptimizeConditionalInDecrement(N, DAG);
26165 /// performVZEXTCombine - Performs build vector combines
26166 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
26167 TargetLowering::DAGCombinerInfo &DCI,
26168 const X86Subtarget *Subtarget) {
26170 MVT VT = N->getSimpleValueType(0);
26171 SDValue Op = N->getOperand(0);
26172 MVT OpVT = Op.getSimpleValueType();
26173 MVT OpEltVT = OpVT.getVectorElementType();
26174 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
26176 // (vzext (bitcast (vzext (x)) -> (vzext x)
26178 while (V.getOpcode() == ISD::BITCAST)
26179 V = V.getOperand(0);
26181 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
26182 MVT InnerVT = V.getSimpleValueType();
26183 MVT InnerEltVT = InnerVT.getVectorElementType();
26185 // If the element sizes match exactly, we can just do one larger vzext. This
26186 // is always an exact type match as vzext operates on integer types.
26187 if (OpEltVT == InnerEltVT) {
26188 assert(OpVT == InnerVT && "Types must match for vzext!");
26189 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
26192 // The only other way we can combine them is if only a single element of the
26193 // inner vzext is used in the input to the outer vzext.
26194 if (InnerEltVT.getSizeInBits() < InputBits)
26197 // In this case, the inner vzext is completely dead because we're going to
26198 // only look at bits inside of the low element. Just do the outer vzext on
26199 // a bitcast of the input to the inner.
26200 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
26203 // Check if we can bypass extracting and re-inserting an element of an input
26204 // vector. Essentially:
26205 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
26206 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
26207 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
26208 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
26209 SDValue ExtractedV = V.getOperand(0);
26210 SDValue OrigV = ExtractedV.getOperand(0);
26211 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
26212 if (ExtractIdx->getZExtValue() == 0) {
26213 MVT OrigVT = OrigV.getSimpleValueType();
26214 // Extract a subvector if necessary...
26215 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
26216 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
26217 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
26218 OrigVT.getVectorNumElements() / Ratio);
26219 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
26220 DAG.getIntPtrConstant(0, DL));
26222 Op = DAG.getBitcast(OpVT, OrigV);
26223 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
26230 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26231 DAGCombinerInfo &DCI) const {
26232 SelectionDAG &DAG = DCI.DAG;
26233 switch (N->getOpcode()) {
26235 case ISD::EXTRACT_VECTOR_ELT:
26236 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26239 case X86ISD::SHRUNKBLEND:
26240 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26241 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
26242 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26243 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
26244 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
26245 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
26246 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
26249 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
26250 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
26251 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
26252 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
26253 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
26254 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26255 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
26256 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
26257 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26258 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26259 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
26260 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
26262 case X86ISD::FOR: return PerformFORCombine(N, DAG, Subtarget);
26264 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
26265 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
26266 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
26267 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
26268 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
26269 case ISD::ANY_EXTEND:
26270 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
26271 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
26272 case ISD::SIGN_EXTEND_INREG:
26273 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26274 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
26275 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26276 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26277 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
26278 case X86ISD::SHUFP: // Handle all target specific shuffles
26279 case X86ISD::PALIGNR:
26280 case X86ISD::UNPCKH:
26281 case X86ISD::UNPCKL:
26282 case X86ISD::MOVHLPS:
26283 case X86ISD::MOVLHPS:
26284 case X86ISD::PSHUFB:
26285 case X86ISD::PSHUFD:
26286 case X86ISD::PSHUFHW:
26287 case X86ISD::PSHUFLW:
26288 case X86ISD::MOVSS:
26289 case X86ISD::MOVSD:
26290 case X86ISD::VPERMILPI:
26291 case X86ISD::VPERM2X128:
26292 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26293 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
26294 case X86ISD::INSERTPS: {
26295 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
26296 return PerformINSERTPSCombine(N, DAG, Subtarget);
26299 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
26305 /// isTypeDesirableForOp - Return true if the target has native support for
26306 /// the specified value type and it is 'desirable' to use the type for the
26307 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26308 /// instruction encodings are longer and some i16 instructions are slow.
26309 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26310 if (!isTypeLegal(VT))
26312 if (VT != MVT::i16)
26319 case ISD::SIGN_EXTEND:
26320 case ISD::ZERO_EXTEND:
26321 case ISD::ANY_EXTEND:
26334 /// IsDesirableToPromoteOp - This method query the target whether it is
26335 /// beneficial for dag combiner to promote the specified node. If true, it
26336 /// should return the desired promotion type by reference.
26337 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26338 EVT VT = Op.getValueType();
26339 if (VT != MVT::i16)
26342 bool Promote = false;
26343 bool Commute = false;
26344 switch (Op.getOpcode()) {
26347 LoadSDNode *LD = cast<LoadSDNode>(Op);
26348 // If the non-extending load has a single use and it's not live out, then it
26349 // might be folded.
26350 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26351 Op.hasOneUse()*/) {
26352 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26353 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26354 // The only case where we'd want to promote LOAD (rather then it being
26355 // promoted as an operand is when it's only use is liveout.
26356 if (UI->getOpcode() != ISD::CopyToReg)
26363 case ISD::SIGN_EXTEND:
26364 case ISD::ZERO_EXTEND:
26365 case ISD::ANY_EXTEND:
26370 SDValue N0 = Op.getOperand(0);
26371 // Look out for (store (shl (load), x)).
26372 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26385 SDValue N0 = Op.getOperand(0);
26386 SDValue N1 = Op.getOperand(1);
26387 if (!Commute && MayFoldLoad(N1))
26389 // Avoid disabling potential load folding opportunities.
26390 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26392 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26402 //===----------------------------------------------------------------------===//
26403 // X86 Inline Assembly Support
26404 //===----------------------------------------------------------------------===//
26406 // Helper to match a string separated by whitespace.
26407 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26408 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26410 for (StringRef Piece : Pieces) {
26411 if (!S.startswith(Piece)) // Check if the piece matches.
26414 S = S.substr(Piece.size());
26415 StringRef::size_type Pos = S.find_first_not_of(" \t");
26416 if (Pos == 0) // We matched a prefix.
26425 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26427 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26428 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26429 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26430 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26432 if (AsmPieces.size() == 3)
26434 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26441 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26442 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26444 std::string AsmStr = IA->getAsmString();
26446 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26447 if (!Ty || Ty->getBitWidth() % 16 != 0)
26450 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26451 SmallVector<StringRef, 4> AsmPieces;
26452 SplitString(AsmStr, AsmPieces, ";\n");
26454 switch (AsmPieces.size()) {
26455 default: return false;
26457 // FIXME: this should verify that we are targeting a 486 or better. If not,
26458 // we will turn this bswap into something that will be lowered to logical
26459 // ops instead of emitting the bswap asm. For now, we don't support 486 or
26460 // lower so don't worry about this.
26462 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26463 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26464 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26465 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26466 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26467 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26468 // No need to check constraints, nothing other than the equivalent of
26469 // "=r,0" would be valid here.
26470 return IntrinsicLowering::LowerToByteSwap(CI);
26473 // rorw $$8, ${0:w} --> llvm.bswap.i16
26474 if (CI->getType()->isIntegerTy(16) &&
26475 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26476 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26477 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26479 StringRef ConstraintsStr = IA->getConstraintString();
26480 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26481 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26482 if (clobbersFlagRegisters(AsmPieces))
26483 return IntrinsicLowering::LowerToByteSwap(CI);
26487 if (CI->getType()->isIntegerTy(32) &&
26488 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26489 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26490 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26491 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26493 StringRef ConstraintsStr = IA->getConstraintString();
26494 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26495 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26496 if (clobbersFlagRegisters(AsmPieces))
26497 return IntrinsicLowering::LowerToByteSwap(CI);
26500 if (CI->getType()->isIntegerTy(64)) {
26501 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26502 if (Constraints.size() >= 2 &&
26503 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26504 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26505 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
26506 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26507 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26508 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26509 return IntrinsicLowering::LowerToByteSwap(CI);
26517 /// getConstraintType - Given a constraint letter, return the type of
26518 /// constraint it is for this target.
26519 X86TargetLowering::ConstraintType
26520 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26521 if (Constraint.size() == 1) {
26522 switch (Constraint[0]) {
26533 return C_RegisterClass;
26557 return TargetLowering::getConstraintType(Constraint);
26560 /// Examine constraint type and operand type and determine a weight value.
26561 /// This object must already have been set up with the operand type
26562 /// and the current alternative constraint selected.
26563 TargetLowering::ConstraintWeight
26564 X86TargetLowering::getSingleConstraintMatchWeight(
26565 AsmOperandInfo &info, const char *constraint) const {
26566 ConstraintWeight weight = CW_Invalid;
26567 Value *CallOperandVal = info.CallOperandVal;
26568 // If we don't have a value, we can't do a match,
26569 // but allow it at the lowest weight.
26570 if (!CallOperandVal)
26572 Type *type = CallOperandVal->getType();
26573 // Look at the constraint type.
26574 switch (*constraint) {
26576 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26587 if (CallOperandVal->getType()->isIntegerTy())
26588 weight = CW_SpecificReg;
26593 if (type->isFloatingPointTy())
26594 weight = CW_SpecificReg;
26597 if (type->isX86_MMXTy() && Subtarget->hasMMX())
26598 weight = CW_SpecificReg;
26602 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26603 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26604 weight = CW_Register;
26607 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26608 if (C->getZExtValue() <= 31)
26609 weight = CW_Constant;
26613 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26614 if (C->getZExtValue() <= 63)
26615 weight = CW_Constant;
26619 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26620 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26621 weight = CW_Constant;
26625 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26626 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26627 weight = CW_Constant;
26631 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26632 if (C->getZExtValue() <= 3)
26633 weight = CW_Constant;
26637 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26638 if (C->getZExtValue() <= 0xff)
26639 weight = CW_Constant;
26644 if (isa<ConstantFP>(CallOperandVal)) {
26645 weight = CW_Constant;
26649 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26650 if ((C->getSExtValue() >= -0x80000000LL) &&
26651 (C->getSExtValue() <= 0x7fffffffLL))
26652 weight = CW_Constant;
26656 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26657 if (C->getZExtValue() <= 0xffffffff)
26658 weight = CW_Constant;
26665 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26666 /// with another that has more specific requirements based on the type of the
26667 /// corresponding operand.
26668 const char *X86TargetLowering::
26669 LowerXConstraint(EVT ConstraintVT) const {
26670 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26671 // 'f' like normal targets.
26672 if (ConstraintVT.isFloatingPoint()) {
26673 if (Subtarget->hasSSE2())
26675 if (Subtarget->hasSSE1())
26679 return TargetLowering::LowerXConstraint(ConstraintVT);
26682 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26683 /// vector. If it is invalid, don't add anything to Ops.
26684 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26685 std::string &Constraint,
26686 std::vector<SDValue>&Ops,
26687 SelectionDAG &DAG) const {
26690 // Only support length 1 constraints for now.
26691 if (Constraint.length() > 1) return;
26693 char ConstraintLetter = Constraint[0];
26694 switch (ConstraintLetter) {
26697 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26698 if (C->getZExtValue() <= 31) {
26699 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26700 Op.getValueType());
26706 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26707 if (C->getZExtValue() <= 63) {
26708 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26709 Op.getValueType());
26715 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26716 if (isInt<8>(C->getSExtValue())) {
26717 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26718 Op.getValueType());
26724 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26725 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26726 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26727 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26728 Op.getValueType());
26734 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26735 if (C->getZExtValue() <= 3) {
26736 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26737 Op.getValueType());
26743 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26744 if (C->getZExtValue() <= 255) {
26745 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26746 Op.getValueType());
26752 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26753 if (C->getZExtValue() <= 127) {
26754 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26755 Op.getValueType());
26761 // 32-bit signed value
26762 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26763 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26764 C->getSExtValue())) {
26765 // Widen to 64 bits here to get it sign extended.
26766 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26769 // FIXME gcc accepts some relocatable values here too, but only in certain
26770 // memory models; it's complicated.
26775 // 32-bit unsigned value
26776 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26777 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26778 C->getZExtValue())) {
26779 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26780 Op.getValueType());
26784 // FIXME gcc accepts some relocatable values here too, but only in certain
26785 // memory models; it's complicated.
26789 // Literal immediates are always ok.
26790 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26791 // Widen to 64 bits here to get it sign extended.
26792 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26796 // In any sort of PIC mode addresses need to be computed at runtime by
26797 // adding in a register or some sort of table lookup. These can't
26798 // be used as immediates.
26799 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26802 // If we are in non-pic codegen mode, we allow the address of a global (with
26803 // an optional displacement) to be used with 'i'.
26804 GlobalAddressSDNode *GA = nullptr;
26805 int64_t Offset = 0;
26807 // Match either (GA), (GA+C), (GA+C1+C2), etc.
26809 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26810 Offset += GA->getOffset();
26812 } else if (Op.getOpcode() == ISD::ADD) {
26813 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26814 Offset += C->getZExtValue();
26815 Op = Op.getOperand(0);
26818 } else if (Op.getOpcode() == ISD::SUB) {
26819 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26820 Offset += -C->getZExtValue();
26821 Op = Op.getOperand(0);
26826 // Otherwise, this isn't something we can handle, reject it.
26830 const GlobalValue *GV = GA->getGlobal();
26831 // If we require an extra load to get this address, as in PIC mode, we
26832 // can't accept it.
26833 if (isGlobalStubReference(
26834 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26837 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26838 GA->getValueType(0), Offset);
26843 if (Result.getNode()) {
26844 Ops.push_back(Result);
26847 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26850 std::pair<unsigned, const TargetRegisterClass *>
26851 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26852 StringRef Constraint,
26854 // First, see if this is a constraint that directly corresponds to an LLVM
26856 if (Constraint.size() == 1) {
26857 // GCC Constraint Letters
26858 switch (Constraint[0]) {
26860 // TODO: Slight differences here in allocation order and leaving
26861 // RIP in the class. Do they matter any more here than they do
26862 // in the normal allocation?
26863 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26864 if (Subtarget->is64Bit()) {
26865 if (VT == MVT::i32 || VT == MVT::f32)
26866 return std::make_pair(0U, &X86::GR32RegClass);
26867 if (VT == MVT::i16)
26868 return std::make_pair(0U, &X86::GR16RegClass);
26869 if (VT == MVT::i8 || VT == MVT::i1)
26870 return std::make_pair(0U, &X86::GR8RegClass);
26871 if (VT == MVT::i64 || VT == MVT::f64)
26872 return std::make_pair(0U, &X86::GR64RegClass);
26875 // 32-bit fallthrough
26876 case 'Q': // Q_REGS
26877 if (VT == MVT::i32 || VT == MVT::f32)
26878 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26879 if (VT == MVT::i16)
26880 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26881 if (VT == MVT::i8 || VT == MVT::i1)
26882 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26883 if (VT == MVT::i64)
26884 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26886 case 'r': // GENERAL_REGS
26887 case 'l': // INDEX_REGS
26888 if (VT == MVT::i8 || VT == MVT::i1)
26889 return std::make_pair(0U, &X86::GR8RegClass);
26890 if (VT == MVT::i16)
26891 return std::make_pair(0U, &X86::GR16RegClass);
26892 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26893 return std::make_pair(0U, &X86::GR32RegClass);
26894 return std::make_pair(0U, &X86::GR64RegClass);
26895 case 'R': // LEGACY_REGS
26896 if (VT == MVT::i8 || VT == MVT::i1)
26897 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26898 if (VT == MVT::i16)
26899 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26900 if (VT == MVT::i32 || !Subtarget->is64Bit())
26901 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26902 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26903 case 'f': // FP Stack registers.
26904 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26905 // value to the correct fpstack register class.
26906 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26907 return std::make_pair(0U, &X86::RFP32RegClass);
26908 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26909 return std::make_pair(0U, &X86::RFP64RegClass);
26910 return std::make_pair(0U, &X86::RFP80RegClass);
26911 case 'y': // MMX_REGS if MMX allowed.
26912 if (!Subtarget->hasMMX()) break;
26913 return std::make_pair(0U, &X86::VR64RegClass);
26914 case 'Y': // SSE_REGS if SSE2 allowed
26915 if (!Subtarget->hasSSE2()) break;
26917 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26918 if (!Subtarget->hasSSE1()) break;
26920 switch (VT.SimpleTy) {
26922 // Scalar SSE types.
26925 return std::make_pair(0U, &X86::FR32RegClass);
26928 return std::make_pair(0U, &X86::FR64RegClass);
26936 return std::make_pair(0U, &X86::VR128RegClass);
26944 return std::make_pair(0U, &X86::VR256RegClass);
26949 return std::make_pair(0U, &X86::VR512RegClass);
26955 // Use the default implementation in TargetLowering to convert the register
26956 // constraint into a member of a register class.
26957 std::pair<unsigned, const TargetRegisterClass*> Res;
26958 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26960 // Not found as a standard register?
26962 // Map st(0) -> st(7) -> ST0
26963 if (Constraint.size() == 7 && Constraint[0] == '{' &&
26964 tolower(Constraint[1]) == 's' &&
26965 tolower(Constraint[2]) == 't' &&
26966 Constraint[3] == '(' &&
26967 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26968 Constraint[5] == ')' &&
26969 Constraint[6] == '}') {
26971 Res.first = X86::FP0+Constraint[4]-'0';
26972 Res.second = &X86::RFP80RegClass;
26976 // GCC allows "st(0)" to be called just plain "st".
26977 if (StringRef("{st}").equals_lower(Constraint)) {
26978 Res.first = X86::FP0;
26979 Res.second = &X86::RFP80RegClass;
26984 if (StringRef("{flags}").equals_lower(Constraint)) {
26985 Res.first = X86::EFLAGS;
26986 Res.second = &X86::CCRRegClass;
26990 // 'A' means EAX + EDX.
26991 if (Constraint == "A") {
26992 Res.first = X86::EAX;
26993 Res.second = &X86::GR32_ADRegClass;
26999 // Otherwise, check to see if this is a register class of the wrong value
27000 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
27001 // turn into {ax},{dx}.
27002 // MVT::Other is used to specify clobber names.
27003 if (Res.second->hasType(VT) || VT == MVT::Other)
27004 return Res; // Correct type already, nothing to do.
27006 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
27007 // return "eax". This should even work for things like getting 64bit integer
27008 // registers when given an f64 type.
27009 const TargetRegisterClass *Class = Res.second;
27010 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
27011 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
27012 unsigned Size = VT.getSizeInBits();
27013 MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
27014 : Size == 16 ? MVT::i16
27015 : Size == 32 ? MVT::i32
27016 : Size == 64 ? MVT::i64
27018 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
27020 Res.first = DestReg;
27021 Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
27022 : SimpleTy == MVT::i16 ? &X86::GR16RegClass
27023 : SimpleTy == MVT::i32 ? &X86::GR32RegClass
27024 : &X86::GR64RegClass;
27025 assert(Res.second->contains(Res.first) && "Register in register class");
27027 // No register found/type mismatch.
27029 Res.second = nullptr;
27031 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
27032 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
27033 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
27034 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
27035 Class == &X86::VR512RegClass) {
27036 // Handle references to XMM physical registers that got mapped into the
27037 // wrong class. This can happen with constraints like {xmm0} where the
27038 // target independent register mapper will just pick the first match it can
27039 // find, ignoring the required type.
27041 if (VT == MVT::f32 || VT == MVT::i32)
27042 Res.second = &X86::FR32RegClass;
27043 else if (VT == MVT::f64 || VT == MVT::i64)
27044 Res.second = &X86::FR64RegClass;
27045 else if (X86::VR128RegClass.hasType(VT))
27046 Res.second = &X86::VR128RegClass;
27047 else if (X86::VR256RegClass.hasType(VT))
27048 Res.second = &X86::VR256RegClass;
27049 else if (X86::VR512RegClass.hasType(VT))
27050 Res.second = &X86::VR512RegClass;
27052 // Type mismatch and not a clobber: Return an error;
27054 Res.second = nullptr;
27061 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
27062 const AddrMode &AM, Type *Ty,
27063 unsigned AS) const {
27064 // Scaling factors are not free at all.
27065 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
27066 // will take 2 allocations in the out of order engine instead of 1
27067 // for plain addressing mode, i.e. inst (reg1).
27069 // vaddps (%rsi,%drx), %ymm0, %ymm1
27070 // Requires two allocations (one for the load, one for the computation)
27072 // vaddps (%rsi), %ymm0, %ymm1
27073 // Requires just 1 allocation, i.e., freeing allocations for other operations
27074 // and having less micro operations to execute.
27076 // For some X86 architectures, this is even worse because for instance for
27077 // stores, the complex addressing mode forces the instruction to use the
27078 // "load" ports instead of the dedicated "store" port.
27079 // E.g., on Haswell:
27080 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
27081 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
27082 if (isLegalAddressingMode(DL, AM, Ty, AS))
27083 // Scale represents reg2 * scale, thus account for 1
27084 // as soon as we use a second register.
27085 return AM.Scale != 0;
27089 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
27090 // Integer division on x86 is expensive. However, when aggressively optimizing
27091 // for code size, we prefer to use a div instruction, as it is usually smaller
27092 // than the alternative sequence.
27093 // The exception to this is vector division. Since x86 doesn't have vector
27094 // integer division, leaving the division as-is is a loss even in terms of
27095 // size, because it will have to be scalarized, while the alternative code
27096 // sequence can be performed in vector form.
27097 bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
27098 Attribute::MinSize);
27099 return OptSize && !VT.isVector();