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);
1282 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1283 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1284 MVT VT = (MVT::SimpleValueType)i;
1286 // Do not attempt to promote non-256-bit vectors
1287 if (!VT.is256BitVector())
1290 setOperationAction(ISD::AND, VT, Promote);
1291 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1292 setOperationAction(ISD::OR, VT, Promote);
1293 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1294 setOperationAction(ISD::XOR, VT, Promote);
1295 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1296 setOperationAction(ISD::LOAD, VT, Promote);
1297 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1298 setOperationAction(ISD::SELECT, VT, Promote);
1299 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1303 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1304 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1305 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1306 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1307 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1309 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1310 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1311 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1313 for (MVT VT : MVT::fp_vector_valuetypes())
1314 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1316 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1317 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1318 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1319 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1320 setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1321 setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1322 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1323 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1324 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1325 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1326 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1327 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1329 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1330 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1331 setOperationAction(ISD::XOR, MVT::i1, Legal);
1332 setOperationAction(ISD::OR, MVT::i1, Legal);
1333 setOperationAction(ISD::AND, MVT::i1, Legal);
1334 setOperationAction(ISD::SUB, MVT::i1, Custom);
1335 setOperationAction(ISD::ADD, MVT::i1, Custom);
1336 setOperationAction(ISD::MUL, MVT::i1, Custom);
1337 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1338 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1339 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1340 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1341 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1343 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1344 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1345 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1346 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1347 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1348 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1350 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1351 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1352 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1353 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1354 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1355 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1356 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1357 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1359 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1360 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1361 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1362 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1363 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1364 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1365 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1366 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1367 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1368 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1369 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1370 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1371 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1372 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1373 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1374 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1376 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1377 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1378 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1379 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1380 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1381 if (Subtarget->hasVLX()){
1382 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1383 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1384 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1385 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1386 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1388 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1389 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1390 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1391 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1392 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1394 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1395 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1396 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1397 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i1, Custom);
1398 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i1, Custom);
1399 if (Subtarget->hasDQI()) {
1400 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1401 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1403 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1404 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1405 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1406 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1407 if (Subtarget->hasVLX()) {
1408 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1409 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1410 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1411 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1412 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1413 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1414 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1415 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1418 if (Subtarget->hasVLX()) {
1419 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1420 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1421 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1422 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1423 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1424 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1425 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1426 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1428 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1429 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1430 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1431 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1432 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1433 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1434 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1435 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1436 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1437 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1438 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1439 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1440 if (Subtarget->hasDQI()) {
1441 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1442 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1444 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1445 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1446 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1447 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1448 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1449 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1450 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1451 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1452 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1453 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1455 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1456 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1457 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1458 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1459 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1461 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1462 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1464 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1466 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1467 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1468 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1469 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1470 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1471 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1472 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1473 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1474 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1475 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1476 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1478 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1479 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1480 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1481 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1482 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1483 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1484 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1485 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1487 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1488 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1490 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1491 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1493 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1495 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1496 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1498 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1499 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1501 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1502 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1504 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1505 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1506 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1507 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1508 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1509 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1511 if (Subtarget->hasCDI()) {
1512 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1513 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1514 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i64, Legal);
1515 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i32, Legal);
1517 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i64, Custom);
1518 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i32, Custom);
1520 if (Subtarget->hasVLX() && Subtarget->hasCDI()) {
1521 setOperationAction(ISD::CTLZ, MVT::v4i64, Legal);
1522 setOperationAction(ISD::CTLZ, MVT::v8i32, Legal);
1523 setOperationAction(ISD::CTLZ, MVT::v2i64, Legal);
1524 setOperationAction(ISD::CTLZ, MVT::v4i32, Legal);
1525 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i64, Legal);
1526 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i32, Legal);
1527 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v2i64, Legal);
1528 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i32, Legal);
1530 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i64, Custom);
1531 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i32, Custom);
1532 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
1533 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
1535 if (Subtarget->hasDQI()) {
1536 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1537 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1538 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1540 // Custom lower several nodes.
1541 for (MVT VT : MVT::vector_valuetypes()) {
1542 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1544 setOperationAction(ISD::AND, VT, Legal);
1545 setOperationAction(ISD::OR, VT, Legal);
1546 setOperationAction(ISD::XOR, VT, Legal);
1548 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1549 setOperationAction(ISD::MGATHER, VT, Custom);
1550 setOperationAction(ISD::MSCATTER, VT, Custom);
1552 // Extract subvector is special because the value type
1553 // (result) is 256/128-bit but the source is 512-bit wide.
1554 if (VT.is128BitVector() || VT.is256BitVector()) {
1555 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1557 if (VT.getVectorElementType() == MVT::i1)
1558 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1560 // Do not attempt to custom lower other non-512-bit vectors
1561 if (!VT.is512BitVector())
1564 if (EltSize >= 32) {
1565 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1566 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1567 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1568 setOperationAction(ISD::VSELECT, VT, Legal);
1569 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1570 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1571 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1572 setOperationAction(ISD::MLOAD, VT, Legal);
1573 setOperationAction(ISD::MSTORE, VT, Legal);
1576 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1577 MVT VT = (MVT::SimpleValueType)i;
1579 // Do not attempt to promote non-512-bit vectors.
1580 if (!VT.is512BitVector())
1583 setOperationAction(ISD::SELECT, VT, Promote);
1584 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1588 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1589 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1590 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1592 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1593 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1595 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1596 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1597 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1598 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1599 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1600 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1601 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1602 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1603 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1604 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1605 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1606 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Legal);
1607 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Legal);
1608 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1609 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1610 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1611 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1612 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1613 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1614 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1615 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1616 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i16, Custom);
1617 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1618 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1619 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1620 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1621 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1622 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1623 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1624 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1625 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1626 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i1, Custom);
1627 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i1, Custom);
1629 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1630 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1631 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1632 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1633 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1634 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1635 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1636 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1638 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1639 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1640 if (Subtarget->hasVLX())
1641 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1643 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1644 const MVT VT = (MVT::SimpleValueType)i;
1646 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1648 // Do not attempt to promote non-512-bit vectors.
1649 if (!VT.is512BitVector())
1653 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1654 setOperationAction(ISD::VSELECT, VT, Legal);
1659 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1660 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1661 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1663 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1664 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1665 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1666 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1667 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1668 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1669 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1670 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1671 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1672 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1673 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i1, Custom);
1674 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i1, Custom);
1676 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1677 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1678 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1679 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1680 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1681 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1682 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1683 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1685 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1686 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1687 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1688 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1689 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1690 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1691 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1692 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1695 // We want to custom lower some of our intrinsics.
1696 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1697 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1698 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1699 if (!Subtarget->is64Bit())
1700 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1702 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1703 // handle type legalization for these operations here.
1705 // FIXME: We really should do custom legalization for addition and
1706 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1707 // than generic legalization for 64-bit multiplication-with-overflow, though.
1708 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1709 // Add/Sub/Mul with overflow operations are custom lowered.
1711 setOperationAction(ISD::SADDO, VT, Custom);
1712 setOperationAction(ISD::UADDO, VT, Custom);
1713 setOperationAction(ISD::SSUBO, VT, Custom);
1714 setOperationAction(ISD::USUBO, VT, Custom);
1715 setOperationAction(ISD::SMULO, VT, Custom);
1716 setOperationAction(ISD::UMULO, VT, Custom);
1719 if (!Subtarget->is64Bit()) {
1720 // These libcalls are not available in 32-bit.
1721 setLibcallName(RTLIB::SHL_I128, nullptr);
1722 setLibcallName(RTLIB::SRL_I128, nullptr);
1723 setLibcallName(RTLIB::SRA_I128, nullptr);
1726 // Combine sin / cos into one node or libcall if possible.
1727 if (Subtarget->hasSinCos()) {
1728 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1729 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1730 if (Subtarget->isTargetDarwin()) {
1731 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1732 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1733 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1734 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1738 if (Subtarget->isTargetWin64()) {
1739 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1740 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1741 setOperationAction(ISD::SREM, MVT::i128, Custom);
1742 setOperationAction(ISD::UREM, MVT::i128, Custom);
1743 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1744 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1747 // We have target-specific dag combine patterns for the following nodes:
1748 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1749 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1750 setTargetDAGCombine(ISD::BITCAST);
1751 setTargetDAGCombine(ISD::VSELECT);
1752 setTargetDAGCombine(ISD::SELECT);
1753 setTargetDAGCombine(ISD::SHL);
1754 setTargetDAGCombine(ISD::SRA);
1755 setTargetDAGCombine(ISD::SRL);
1756 setTargetDAGCombine(ISD::OR);
1757 setTargetDAGCombine(ISD::AND);
1758 setTargetDAGCombine(ISD::ADD);
1759 setTargetDAGCombine(ISD::FADD);
1760 setTargetDAGCombine(ISD::FSUB);
1761 setTargetDAGCombine(ISD::FMA);
1762 setTargetDAGCombine(ISD::SUB);
1763 setTargetDAGCombine(ISD::LOAD);
1764 setTargetDAGCombine(ISD::MLOAD);
1765 setTargetDAGCombine(ISD::STORE);
1766 setTargetDAGCombine(ISD::MSTORE);
1767 setTargetDAGCombine(ISD::ZERO_EXTEND);
1768 setTargetDAGCombine(ISD::ANY_EXTEND);
1769 setTargetDAGCombine(ISD::SIGN_EXTEND);
1770 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1771 setTargetDAGCombine(ISD::SINT_TO_FP);
1772 setTargetDAGCombine(ISD::UINT_TO_FP);
1773 setTargetDAGCombine(ISD::SETCC);
1774 setTargetDAGCombine(ISD::BUILD_VECTOR);
1775 setTargetDAGCombine(ISD::MUL);
1776 setTargetDAGCombine(ISD::XOR);
1778 computeRegisterProperties(Subtarget->getRegisterInfo());
1780 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1781 MaxStoresPerMemsetOptSize = 8;
1782 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1783 MaxStoresPerMemcpyOptSize = 4;
1784 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1785 MaxStoresPerMemmoveOptSize = 4;
1786 setPrefLoopAlignment(4); // 2^4 bytes.
1788 // Predictable cmov don't hurt on atom because it's in-order.
1789 PredictableSelectIsExpensive = !Subtarget->isAtom();
1790 EnableExtLdPromotion = true;
1791 setPrefFunctionAlignment(4); // 2^4 bytes.
1793 verifyIntrinsicTables();
1796 // This has so far only been implemented for 64-bit MachO.
1797 bool X86TargetLowering::useLoadStackGuardNode() const {
1798 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1801 TargetLoweringBase::LegalizeTypeAction
1802 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1803 if (ExperimentalVectorWideningLegalization &&
1804 VT.getVectorNumElements() != 1 &&
1805 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1806 return TypeWidenVector;
1808 return TargetLoweringBase::getPreferredVectorAction(VT);
1811 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1814 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1816 const unsigned NumElts = VT.getVectorNumElements();
1817 const EVT EltVT = VT.getVectorElementType();
1818 if (VT.is512BitVector()) {
1819 if (Subtarget->hasAVX512())
1820 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1821 EltVT == MVT::f32 || EltVT == MVT::f64)
1823 case 8: return MVT::v8i1;
1824 case 16: return MVT::v16i1;
1826 if (Subtarget->hasBWI())
1827 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1829 case 32: return MVT::v32i1;
1830 case 64: return MVT::v64i1;
1834 if (VT.is256BitVector() || VT.is128BitVector()) {
1835 if (Subtarget->hasVLX())
1836 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1837 EltVT == MVT::f32 || EltVT == MVT::f64)
1839 case 2: return MVT::v2i1;
1840 case 4: return MVT::v4i1;
1841 case 8: return MVT::v8i1;
1843 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1844 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1846 case 8: return MVT::v8i1;
1847 case 16: return MVT::v16i1;
1848 case 32: return MVT::v32i1;
1852 return VT.changeVectorElementTypeToInteger();
1855 /// Helper for getByValTypeAlignment to determine
1856 /// the desired ByVal argument alignment.
1857 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1860 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1861 if (VTy->getBitWidth() == 128)
1863 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1864 unsigned EltAlign = 0;
1865 getMaxByValAlign(ATy->getElementType(), EltAlign);
1866 if (EltAlign > MaxAlign)
1867 MaxAlign = EltAlign;
1868 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1869 for (auto *EltTy : STy->elements()) {
1870 unsigned EltAlign = 0;
1871 getMaxByValAlign(EltTy, EltAlign);
1872 if (EltAlign > MaxAlign)
1873 MaxAlign = EltAlign;
1880 /// Return the desired alignment for ByVal aggregate
1881 /// function arguments in the caller parameter area. For X86, aggregates
1882 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1883 /// are at 4-byte boundaries.
1884 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1885 const DataLayout &DL) const {
1886 if (Subtarget->is64Bit()) {
1887 // Max of 8 and alignment of type.
1888 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1895 if (Subtarget->hasSSE1())
1896 getMaxByValAlign(Ty, Align);
1900 /// Returns the target specific optimal type for load
1901 /// and store operations as a result of memset, memcpy, and memmove
1902 /// lowering. If DstAlign is zero that means it's safe to destination
1903 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1904 /// means there isn't a need to check it against alignment requirement,
1905 /// probably because the source does not need to be loaded. If 'IsMemset' is
1906 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1907 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1908 /// source is constant so it does not need to be loaded.
1909 /// It returns EVT::Other if the type should be determined using generic
1910 /// target-independent logic.
1912 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1913 unsigned DstAlign, unsigned SrcAlign,
1914 bool IsMemset, bool ZeroMemset,
1916 MachineFunction &MF) const {
1917 const Function *F = MF.getFunction();
1918 if ((!IsMemset || ZeroMemset) &&
1919 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1921 (!Subtarget->isUnalignedMem16Slow() ||
1922 ((DstAlign == 0 || DstAlign >= 16) &&
1923 (SrcAlign == 0 || SrcAlign >= 16)))) {
1925 // FIXME: Check if unaligned 32-byte accesses are slow.
1926 if (Subtarget->hasInt256())
1928 if (Subtarget->hasFp256())
1931 if (Subtarget->hasSSE2())
1933 if (Subtarget->hasSSE1())
1935 } else if (!MemcpyStrSrc && Size >= 8 &&
1936 !Subtarget->is64Bit() &&
1937 Subtarget->hasSSE2()) {
1938 // Do not use f64 to lower memcpy if source is string constant. It's
1939 // better to use i32 to avoid the loads.
1943 // This is a compromise. If we reach here, unaligned accesses may be slow on
1944 // this target. However, creating smaller, aligned accesses could be even
1945 // slower and would certainly be a lot more code.
1946 if (Subtarget->is64Bit() && Size >= 8)
1951 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1953 return X86ScalarSSEf32;
1954 else if (VT == MVT::f64)
1955 return X86ScalarSSEf64;
1960 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1965 switch (VT.getSizeInBits()) {
1967 // 8-byte and under are always assumed to be fast.
1971 *Fast = !Subtarget->isUnalignedMem16Slow();
1974 *Fast = !Subtarget->isUnalignedMem32Slow();
1976 // TODO: What about AVX-512 (512-bit) accesses?
1979 // Misaligned accesses of any size are always allowed.
1983 /// Return the entry encoding for a jump table in the
1984 /// current function. The returned value is a member of the
1985 /// MachineJumpTableInfo::JTEntryKind enum.
1986 unsigned X86TargetLowering::getJumpTableEncoding() const {
1987 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1989 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1990 Subtarget->isPICStyleGOT())
1991 return MachineJumpTableInfo::EK_Custom32;
1993 // Otherwise, use the normal jump table encoding heuristics.
1994 return TargetLowering::getJumpTableEncoding();
1997 bool X86TargetLowering::useSoftFloat() const {
1998 return Subtarget->useSoftFloat();
2002 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2003 const MachineBasicBlock *MBB,
2004 unsigned uid,MCContext &Ctx) const{
2005 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2006 Subtarget->isPICStyleGOT());
2007 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2009 return MCSymbolRefExpr::create(MBB->getSymbol(),
2010 MCSymbolRefExpr::VK_GOTOFF, Ctx);
2013 /// Returns relocation base for the given PIC jumptable.
2014 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2015 SelectionDAG &DAG) const {
2016 if (!Subtarget->is64Bit())
2017 // This doesn't have SDLoc associated with it, but is not really the
2018 // same as a Register.
2019 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2020 getPointerTy(DAG.getDataLayout()));
2024 /// This returns the relocation base for the given PIC jumptable,
2025 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2026 const MCExpr *X86TargetLowering::
2027 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2028 MCContext &Ctx) const {
2029 // X86-64 uses RIP relative addressing based on the jump table label.
2030 if (Subtarget->isPICStyleRIPRel())
2031 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2033 // Otherwise, the reference is relative to the PIC base.
2034 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2037 std::pair<const TargetRegisterClass *, uint8_t>
2038 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2040 const TargetRegisterClass *RRC = nullptr;
2042 switch (VT.SimpleTy) {
2044 return TargetLowering::findRepresentativeClass(TRI, VT);
2045 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2046 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2049 RRC = &X86::VR64RegClass;
2051 case MVT::f32: case MVT::f64:
2052 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2053 case MVT::v4f32: case MVT::v2f64:
2054 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2056 RRC = &X86::VR128RegClass;
2059 return std::make_pair(RRC, Cost);
2062 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2063 unsigned &Offset) const {
2064 if (!Subtarget->isTargetLinux())
2067 if (Subtarget->is64Bit()) {
2068 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2070 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2082 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2083 unsigned DestAS) const {
2084 assert(SrcAS != DestAS && "Expected different address spaces!");
2086 return SrcAS < 256 && DestAS < 256;
2089 //===----------------------------------------------------------------------===//
2090 // Return Value Calling Convention Implementation
2091 //===----------------------------------------------------------------------===//
2093 #include "X86GenCallingConv.inc"
2095 bool X86TargetLowering::CanLowerReturn(
2096 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2097 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2098 SmallVector<CCValAssign, 16> RVLocs;
2099 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2100 return CCInfo.CheckReturn(Outs, RetCC_X86);
2103 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2104 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2109 X86TargetLowering::LowerReturn(SDValue Chain,
2110 CallingConv::ID CallConv, bool isVarArg,
2111 const SmallVectorImpl<ISD::OutputArg> &Outs,
2112 const SmallVectorImpl<SDValue> &OutVals,
2113 SDLoc dl, SelectionDAG &DAG) const {
2114 MachineFunction &MF = DAG.getMachineFunction();
2115 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2117 SmallVector<CCValAssign, 16> RVLocs;
2118 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2119 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2122 SmallVector<SDValue, 6> RetOps;
2123 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2124 // Operand #1 = Bytes To Pop
2125 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2128 // Copy the result values into the output registers.
2129 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2130 CCValAssign &VA = RVLocs[i];
2131 assert(VA.isRegLoc() && "Can only return in registers!");
2132 SDValue ValToCopy = OutVals[i];
2133 EVT ValVT = ValToCopy.getValueType();
2135 // Promote values to the appropriate types.
2136 if (VA.getLocInfo() == CCValAssign::SExt)
2137 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2138 else if (VA.getLocInfo() == CCValAssign::ZExt)
2139 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2140 else if (VA.getLocInfo() == CCValAssign::AExt) {
2141 if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2142 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2144 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2146 else if (VA.getLocInfo() == CCValAssign::BCvt)
2147 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2149 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2150 "Unexpected FP-extend for return value.");
2152 // If this is x86-64, and we disabled SSE, we can't return FP values,
2153 // or SSE or MMX vectors.
2154 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2155 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2156 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2157 report_fatal_error("SSE register return with SSE disabled");
2159 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2160 // llvm-gcc has never done it right and no one has noticed, so this
2161 // should be OK for now.
2162 if (ValVT == MVT::f64 &&
2163 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2164 report_fatal_error("SSE2 register return with SSE2 disabled");
2166 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2167 // the RET instruction and handled by the FP Stackifier.
2168 if (VA.getLocReg() == X86::FP0 ||
2169 VA.getLocReg() == X86::FP1) {
2170 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2171 // change the value to the FP stack register class.
2172 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2173 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2174 RetOps.push_back(ValToCopy);
2175 // Don't emit a copytoreg.
2179 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2180 // which is returned in RAX / RDX.
2181 if (Subtarget->is64Bit()) {
2182 if (ValVT == MVT::x86mmx) {
2183 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2184 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2185 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2187 // If we don't have SSE2 available, convert to v4f32 so the generated
2188 // register is legal.
2189 if (!Subtarget->hasSSE2())
2190 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2195 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2196 Flag = Chain.getValue(1);
2197 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2200 // All x86 ABIs require that for returning structs by value we copy
2201 // the sret argument into %rax/%eax (depending on ABI) for the return.
2202 // We saved the argument into a virtual register in the entry block,
2203 // so now we copy the value out and into %rax/%eax.
2205 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2206 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2207 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2208 // either case FuncInfo->setSRetReturnReg() will have been called.
2209 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2210 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2211 getPointerTy(MF.getDataLayout()));
2214 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2215 X86::RAX : X86::EAX;
2216 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2217 Flag = Chain.getValue(1);
2219 // RAX/EAX now acts like a return value.
2221 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2224 RetOps[0] = Chain; // Update chain.
2226 // Add the flag if we have it.
2228 RetOps.push_back(Flag);
2230 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2233 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2234 if (N->getNumValues() != 1)
2236 if (!N->hasNUsesOfValue(1, 0))
2239 SDValue TCChain = Chain;
2240 SDNode *Copy = *N->use_begin();
2241 if (Copy->getOpcode() == ISD::CopyToReg) {
2242 // If the copy has a glue operand, we conservatively assume it isn't safe to
2243 // perform a tail call.
2244 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2246 TCChain = Copy->getOperand(0);
2247 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2250 bool HasRet = false;
2251 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2253 if (UI->getOpcode() != X86ISD::RET_FLAG)
2255 // If we are returning more than one value, we can definitely
2256 // not make a tail call see PR19530
2257 if (UI->getNumOperands() > 4)
2259 if (UI->getNumOperands() == 4 &&
2260 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2273 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2274 ISD::NodeType ExtendKind) const {
2276 // TODO: Is this also valid on 32-bit?
2277 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2278 ReturnMVT = MVT::i8;
2280 ReturnMVT = MVT::i32;
2282 EVT MinVT = getRegisterType(Context, ReturnMVT);
2283 return VT.bitsLT(MinVT) ? MinVT : VT;
2286 /// Lower the result values of a call into the
2287 /// appropriate copies out of appropriate physical registers.
2290 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2291 CallingConv::ID CallConv, bool isVarArg,
2292 const SmallVectorImpl<ISD::InputArg> &Ins,
2293 SDLoc dl, SelectionDAG &DAG,
2294 SmallVectorImpl<SDValue> &InVals) const {
2296 // Assign locations to each value returned by this call.
2297 SmallVector<CCValAssign, 16> RVLocs;
2298 bool Is64Bit = Subtarget->is64Bit();
2299 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2301 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2303 // Copy all of the result registers out of their specified physreg.
2304 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2305 CCValAssign &VA = RVLocs[i];
2306 EVT CopyVT = VA.getLocVT();
2308 // If this is x86-64, and we disabled SSE, we can't return FP values
2309 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2310 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2311 report_fatal_error("SSE register return with SSE disabled");
2314 // If we prefer to use the value in xmm registers, copy it out as f80 and
2315 // use a truncate to move it from fp stack reg to xmm reg.
2316 bool RoundAfterCopy = false;
2317 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2318 isScalarFPTypeInSSEReg(VA.getValVT())) {
2320 RoundAfterCopy = (CopyVT != VA.getLocVT());
2323 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2324 CopyVT, InFlag).getValue(1);
2325 SDValue Val = Chain.getValue(0);
2328 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2329 // This truncation won't change the value.
2330 DAG.getIntPtrConstant(1, dl));
2332 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2333 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2335 InFlag = Chain.getValue(2);
2336 InVals.push_back(Val);
2342 //===----------------------------------------------------------------------===//
2343 // C & StdCall & Fast Calling Convention implementation
2344 //===----------------------------------------------------------------------===//
2345 // StdCall calling convention seems to be standard for many Windows' API
2346 // routines and around. It differs from C calling convention just a little:
2347 // callee should clean up the stack, not caller. Symbols should be also
2348 // decorated in some fancy way :) It doesn't support any vector arguments.
2349 // For info on fast calling convention see Fast Calling Convention (tail call)
2350 // implementation LowerX86_32FastCCCallTo.
2352 /// CallIsStructReturn - Determines whether a call uses struct return
2354 enum StructReturnType {
2359 static StructReturnType
2360 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2362 return NotStructReturn;
2364 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2365 if (!Flags.isSRet())
2366 return NotStructReturn;
2367 if (Flags.isInReg())
2368 return RegStructReturn;
2369 return StackStructReturn;
2372 /// Determines whether a function uses struct return semantics.
2373 static StructReturnType
2374 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2376 return NotStructReturn;
2378 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2379 if (!Flags.isSRet())
2380 return NotStructReturn;
2381 if (Flags.isInReg())
2382 return RegStructReturn;
2383 return StackStructReturn;
2386 /// Make a copy of an aggregate at address specified by "Src" to address
2387 /// "Dst" with size and alignment information specified by the specific
2388 /// parameter attribute. The copy will be passed as a byval function parameter.
2390 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2391 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2393 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2395 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2396 /*isVolatile*/false, /*AlwaysInline=*/true,
2397 /*isTailCall*/false,
2398 MachinePointerInfo(), MachinePointerInfo());
2401 /// Return true if the calling convention is one that
2402 /// supports tail call optimization.
2403 static bool IsTailCallConvention(CallingConv::ID CC) {
2404 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2405 CC == CallingConv::HiPE);
2408 /// \brief Return true if the calling convention is a C calling convention.
2409 static bool IsCCallConvention(CallingConv::ID CC) {
2410 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2411 CC == CallingConv::X86_64_SysV);
2414 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2416 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2417 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2421 CallingConv::ID CalleeCC = CS.getCallingConv();
2422 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2428 /// Return true if the function is being made into
2429 /// a tailcall target by changing its ABI.
2430 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2431 bool GuaranteedTailCallOpt) {
2432 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2436 X86TargetLowering::LowerMemArgument(SDValue Chain,
2437 CallingConv::ID CallConv,
2438 const SmallVectorImpl<ISD::InputArg> &Ins,
2439 SDLoc dl, SelectionDAG &DAG,
2440 const CCValAssign &VA,
2441 MachineFrameInfo *MFI,
2443 // Create the nodes corresponding to a load from this parameter slot.
2444 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2445 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2446 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2447 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2450 // If value is passed by pointer we have address passed instead of the value
2452 bool ExtendedInMem = VA.isExtInLoc() &&
2453 VA.getValVT().getScalarType() == MVT::i1;
2455 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2456 ValVT = VA.getLocVT();
2458 ValVT = VA.getValVT();
2460 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2461 // changed with more analysis.
2462 // In case of tail call optimization mark all arguments mutable. Since they
2463 // could be overwritten by lowering of arguments in case of a tail call.
2464 if (Flags.isByVal()) {
2465 unsigned Bytes = Flags.getByValSize();
2466 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2467 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2468 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2470 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2471 VA.getLocMemOffset(), isImmutable);
2472 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2473 SDValue Val = DAG.getLoad(
2474 ValVT, dl, Chain, FIN,
2475 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2477 return ExtendedInMem ?
2478 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2482 // FIXME: Get this from tablegen.
2483 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2484 const X86Subtarget *Subtarget) {
2485 assert(Subtarget->is64Bit());
2487 if (Subtarget->isCallingConvWin64(CallConv)) {
2488 static const MCPhysReg GPR64ArgRegsWin64[] = {
2489 X86::RCX, X86::RDX, X86::R8, X86::R9
2491 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2494 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2495 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2497 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2500 // FIXME: Get this from tablegen.
2501 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2502 CallingConv::ID CallConv,
2503 const X86Subtarget *Subtarget) {
2504 assert(Subtarget->is64Bit());
2505 if (Subtarget->isCallingConvWin64(CallConv)) {
2506 // The XMM registers which might contain var arg parameters are shadowed
2507 // in their paired GPR. So we only need to save the GPR to their home
2509 // TODO: __vectorcall will change this.
2513 const Function *Fn = MF.getFunction();
2514 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2515 bool isSoftFloat = Subtarget->useSoftFloat();
2516 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2517 "SSE register cannot be used when SSE is disabled!");
2518 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2519 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2523 static const MCPhysReg XMMArgRegs64Bit[] = {
2524 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2525 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2527 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2530 SDValue X86TargetLowering::LowerFormalArguments(
2531 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2532 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2533 SmallVectorImpl<SDValue> &InVals) const {
2534 MachineFunction &MF = DAG.getMachineFunction();
2535 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2536 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2538 const Function* Fn = MF.getFunction();
2539 if (Fn->hasExternalLinkage() &&
2540 Subtarget->isTargetCygMing() &&
2541 Fn->getName() == "main")
2542 FuncInfo->setForceFramePointer(true);
2544 MachineFrameInfo *MFI = MF.getFrameInfo();
2545 bool Is64Bit = Subtarget->is64Bit();
2546 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2548 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2549 "Var args not supported with calling convention fastcc, ghc or hipe");
2551 // Assign locations to all of the incoming arguments.
2552 SmallVector<CCValAssign, 16> ArgLocs;
2553 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2555 // Allocate shadow area for Win64
2557 CCInfo.AllocateStack(32, 8);
2559 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2561 unsigned LastVal = ~0U;
2563 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2564 CCValAssign &VA = ArgLocs[i];
2565 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2567 assert(VA.getValNo() != LastVal &&
2568 "Don't support value assigned to multiple locs yet");
2570 LastVal = VA.getValNo();
2572 if (VA.isRegLoc()) {
2573 EVT RegVT = VA.getLocVT();
2574 const TargetRegisterClass *RC;
2575 if (RegVT == MVT::i32)
2576 RC = &X86::GR32RegClass;
2577 else if (Is64Bit && RegVT == MVT::i64)
2578 RC = &X86::GR64RegClass;
2579 else if (RegVT == MVT::f32)
2580 RC = &X86::FR32RegClass;
2581 else if (RegVT == MVT::f64)
2582 RC = &X86::FR64RegClass;
2583 else if (RegVT.is512BitVector())
2584 RC = &X86::VR512RegClass;
2585 else if (RegVT.is256BitVector())
2586 RC = &X86::VR256RegClass;
2587 else if (RegVT.is128BitVector())
2588 RC = &X86::VR128RegClass;
2589 else if (RegVT == MVT::x86mmx)
2590 RC = &X86::VR64RegClass;
2591 else if (RegVT == MVT::i1)
2592 RC = &X86::VK1RegClass;
2593 else if (RegVT == MVT::v8i1)
2594 RC = &X86::VK8RegClass;
2595 else if (RegVT == MVT::v16i1)
2596 RC = &X86::VK16RegClass;
2597 else if (RegVT == MVT::v32i1)
2598 RC = &X86::VK32RegClass;
2599 else if (RegVT == MVT::v64i1)
2600 RC = &X86::VK64RegClass;
2602 llvm_unreachable("Unknown argument type!");
2604 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2605 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2607 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2608 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2610 if (VA.getLocInfo() == CCValAssign::SExt)
2611 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2612 DAG.getValueType(VA.getValVT()));
2613 else if (VA.getLocInfo() == CCValAssign::ZExt)
2614 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2615 DAG.getValueType(VA.getValVT()));
2616 else if (VA.getLocInfo() == CCValAssign::BCvt)
2617 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2619 if (VA.isExtInLoc()) {
2620 // Handle MMX values passed in XMM regs.
2621 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2622 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2624 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2627 assert(VA.isMemLoc());
2628 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2631 // If value is passed via pointer - do a load.
2632 if (VA.getLocInfo() == CCValAssign::Indirect)
2633 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2634 MachinePointerInfo(), false, false, false, 0);
2636 InVals.push_back(ArgValue);
2639 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2640 // All x86 ABIs require that for returning structs by value we copy the
2641 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2642 // the argument into a virtual register so that we can access it from the
2644 if (Ins[i].Flags.isSRet()) {
2645 unsigned Reg = FuncInfo->getSRetReturnReg();
2647 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2648 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2649 FuncInfo->setSRetReturnReg(Reg);
2651 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2652 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2657 unsigned StackSize = CCInfo.getNextStackOffset();
2658 // Align stack specially for tail calls.
2659 if (FuncIsMadeTailCallSafe(CallConv,
2660 MF.getTarget().Options.GuaranteedTailCallOpt))
2661 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2663 // If the function takes variable number of arguments, make a frame index for
2664 // the start of the first vararg value... for expansion of llvm.va_start. We
2665 // can skip this if there are no va_start calls.
2666 if (MFI->hasVAStart() &&
2667 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2668 CallConv != CallingConv::X86_ThisCall))) {
2669 FuncInfo->setVarArgsFrameIndex(
2670 MFI->CreateFixedObject(1, StackSize, true));
2673 MachineModuleInfo &MMI = MF.getMMI();
2674 const Function *WinEHParent = nullptr;
2675 if (MMI.hasWinEHFuncInfo(Fn))
2676 WinEHParent = MMI.getWinEHParent(Fn);
2677 bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2679 // Figure out if XMM registers are in use.
2680 assert(!(Subtarget->useSoftFloat() &&
2681 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2682 "SSE register cannot be used when SSE is disabled!");
2684 // 64-bit calling conventions support varargs and register parameters, so we
2685 // have to do extra work to spill them in the prologue.
2686 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2687 // Find the first unallocated argument registers.
2688 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2689 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2690 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2691 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2692 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2693 "SSE register cannot be used when SSE is disabled!");
2695 // Gather all the live in physical registers.
2696 SmallVector<SDValue, 6> LiveGPRs;
2697 SmallVector<SDValue, 8> LiveXMMRegs;
2699 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2700 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2702 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2704 if (!ArgXMMs.empty()) {
2705 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2706 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2707 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2708 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2709 LiveXMMRegs.push_back(
2710 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2715 // Get to the caller-allocated home save location. Add 8 to account
2716 // for the return address.
2717 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2718 FuncInfo->setRegSaveFrameIndex(
2719 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2720 // Fixup to set vararg frame on shadow area (4 x i64).
2722 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2724 // For X86-64, if there are vararg parameters that are passed via
2725 // registers, then we must store them to their spots on the stack so
2726 // they may be loaded by deferencing the result of va_next.
2727 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2728 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2729 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2730 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2733 // Store the integer parameter registers.
2734 SmallVector<SDValue, 8> MemOps;
2735 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2736 getPointerTy(DAG.getDataLayout()));
2737 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2738 for (SDValue Val : LiveGPRs) {
2739 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2740 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2742 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2743 MachinePointerInfo::getFixedStack(
2744 DAG.getMachineFunction(),
2745 FuncInfo->getRegSaveFrameIndex(), Offset),
2747 MemOps.push_back(Store);
2751 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2752 // Now store the XMM (fp + vector) parameter registers.
2753 SmallVector<SDValue, 12> SaveXMMOps;
2754 SaveXMMOps.push_back(Chain);
2755 SaveXMMOps.push_back(ALVal);
2756 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2757 FuncInfo->getRegSaveFrameIndex(), dl));
2758 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2759 FuncInfo->getVarArgsFPOffset(), dl));
2760 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2762 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2763 MVT::Other, SaveXMMOps));
2766 if (!MemOps.empty())
2767 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2770 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2771 // Find the largest legal vector type.
2772 MVT VecVT = MVT::Other;
2773 // FIXME: Only some x86_32 calling conventions support AVX512.
2774 if (Subtarget->hasAVX512() &&
2775 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2776 CallConv == CallingConv::Intel_OCL_BI)))
2777 VecVT = MVT::v16f32;
2778 else if (Subtarget->hasAVX())
2780 else if (Subtarget->hasSSE2())
2783 // We forward some GPRs and some vector types.
2784 SmallVector<MVT, 2> RegParmTypes;
2785 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2786 RegParmTypes.push_back(IntVT);
2787 if (VecVT != MVT::Other)
2788 RegParmTypes.push_back(VecVT);
2790 // Compute the set of forwarded registers. The rest are scratch.
2791 SmallVectorImpl<ForwardedRegister> &Forwards =
2792 FuncInfo->getForwardedMustTailRegParms();
2793 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2795 // Conservatively forward AL on x86_64, since it might be used for varargs.
2796 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2797 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2798 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2801 // Copy all forwards from physical to virtual registers.
2802 for (ForwardedRegister &F : Forwards) {
2803 // FIXME: Can we use a less constrained schedule?
2804 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2805 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2806 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2810 // Some CCs need callee pop.
2811 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2812 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2813 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2815 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2816 // If this is an sret function, the return should pop the hidden pointer.
2817 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2818 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2819 argsAreStructReturn(Ins) == StackStructReturn)
2820 FuncInfo->setBytesToPopOnReturn(4);
2824 // RegSaveFrameIndex is X86-64 only.
2825 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2826 if (CallConv == CallingConv::X86_FastCall ||
2827 CallConv == CallingConv::X86_ThisCall)
2828 // fastcc functions can't have varargs.
2829 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2832 FuncInfo->setArgumentStackSize(StackSize);
2834 if (IsWinEHParent) {
2836 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2837 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2838 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2839 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2840 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2841 MachinePointerInfo::getFixedStack(
2842 DAG.getMachineFunction(), UnwindHelpFI),
2843 /*isVolatile=*/true,
2844 /*isNonTemporal=*/false, /*Alignment=*/0);
2846 // Functions using Win32 EH are considered to have opaque SP adjustments
2847 // to force local variables to be addressed from the frame or base
2849 MFI->setHasOpaqueSPAdjustment(true);
2857 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2858 SDValue StackPtr, SDValue Arg,
2859 SDLoc dl, SelectionDAG &DAG,
2860 const CCValAssign &VA,
2861 ISD::ArgFlagsTy Flags) const {
2862 unsigned LocMemOffset = VA.getLocMemOffset();
2863 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2864 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2866 if (Flags.isByVal())
2867 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2869 return DAG.getStore(
2870 Chain, dl, Arg, PtrOff,
2871 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2875 /// Emit a load of return address if tail call
2876 /// optimization is performed and it is required.
2878 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2879 SDValue &OutRetAddr, SDValue Chain,
2880 bool IsTailCall, bool Is64Bit,
2881 int FPDiff, SDLoc dl) const {
2882 // Adjust the Return address stack slot.
2883 EVT VT = getPointerTy(DAG.getDataLayout());
2884 OutRetAddr = getReturnAddressFrameIndex(DAG);
2886 // Load the "old" Return address.
2887 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2888 false, false, false, 0);
2889 return SDValue(OutRetAddr.getNode(), 1);
2892 /// Emit a store of the return address if tail call
2893 /// optimization is performed and it is required (FPDiff!=0).
2894 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2895 SDValue Chain, SDValue RetAddrFrIdx,
2896 EVT PtrVT, unsigned SlotSize,
2897 int FPDiff, SDLoc dl) {
2898 // Store the return address to the appropriate stack slot.
2899 if (!FPDiff) return Chain;
2900 // Calculate the new stack slot for the return address.
2901 int NewReturnAddrFI =
2902 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2904 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2905 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2906 MachinePointerInfo::getFixedStack(
2907 DAG.getMachineFunction(), NewReturnAddrFI),
2912 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2913 /// operation of specified width.
2914 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2916 unsigned NumElems = VT.getVectorNumElements();
2917 SmallVector<int, 8> Mask;
2918 Mask.push_back(NumElems);
2919 for (unsigned i = 1; i != NumElems; ++i)
2921 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2925 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2926 SmallVectorImpl<SDValue> &InVals) const {
2927 SelectionDAG &DAG = CLI.DAG;
2929 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2930 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2931 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2932 SDValue Chain = CLI.Chain;
2933 SDValue Callee = CLI.Callee;
2934 CallingConv::ID CallConv = CLI.CallConv;
2935 bool &isTailCall = CLI.IsTailCall;
2936 bool isVarArg = CLI.IsVarArg;
2938 MachineFunction &MF = DAG.getMachineFunction();
2939 bool Is64Bit = Subtarget->is64Bit();
2940 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2941 StructReturnType SR = callIsStructReturn(Outs);
2942 bool IsSibcall = false;
2943 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2944 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2946 if (Attr.getValueAsString() == "true")
2949 if (Subtarget->isPICStyleGOT() &&
2950 !MF.getTarget().Options.GuaranteedTailCallOpt) {
2951 // If we are using a GOT, disable tail calls to external symbols with
2952 // default visibility. Tail calling such a symbol requires using a GOT
2953 // relocation, which forces early binding of the symbol. This breaks code
2954 // that require lazy function symbol resolution. Using musttail or
2955 // GuaranteedTailCallOpt will override this.
2956 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2957 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2958 G->getGlobal()->hasDefaultVisibility()))
2962 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2964 // Force this to be a tail call. The verifier rules are enough to ensure
2965 // that we can lower this successfully without moving the return address
2968 } else if (isTailCall) {
2969 // Check if it's really possible to do a tail call.
2970 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2971 isVarArg, SR != NotStructReturn,
2972 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2973 Outs, OutVals, Ins, DAG);
2975 // Sibcalls are automatically detected tailcalls which do not require
2977 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2984 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2985 "Var args not supported with calling convention fastcc, ghc or hipe");
2987 // Analyze operands of the call, assigning locations to each operand.
2988 SmallVector<CCValAssign, 16> ArgLocs;
2989 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2991 // Allocate shadow area for Win64
2993 CCInfo.AllocateStack(32, 8);
2995 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2997 // Get a count of how many bytes are to be pushed on the stack.
2998 unsigned NumBytes = CCInfo.getNextStackOffset();
3000 // This is a sibcall. The memory operands are available in caller's
3001 // own caller's stack.
3003 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3004 IsTailCallConvention(CallConv))
3005 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3008 if (isTailCall && !IsSibcall && !IsMustTail) {
3009 // Lower arguments at fp - stackoffset + fpdiff.
3010 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3012 FPDiff = NumBytesCallerPushed - NumBytes;
3014 // Set the delta of movement of the returnaddr stackslot.
3015 // But only set if delta is greater than previous delta.
3016 if (FPDiff < X86Info->getTCReturnAddrDelta())
3017 X86Info->setTCReturnAddrDelta(FPDiff);
3020 unsigned NumBytesToPush = NumBytes;
3021 unsigned NumBytesToPop = NumBytes;
3023 // If we have an inalloca argument, all stack space has already been allocated
3024 // for us and be right at the top of the stack. We don't support multiple
3025 // arguments passed in memory when using inalloca.
3026 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3028 if (!ArgLocs.back().isMemLoc())
3029 report_fatal_error("cannot use inalloca attribute on a register "
3031 if (ArgLocs.back().getLocMemOffset() != 0)
3032 report_fatal_error("any parameter with the inalloca attribute must be "
3033 "the only memory argument");
3037 Chain = DAG.getCALLSEQ_START(
3038 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3040 SDValue RetAddrFrIdx;
3041 // Load return address for tail calls.
3042 if (isTailCall && FPDiff)
3043 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3044 Is64Bit, FPDiff, dl);
3046 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3047 SmallVector<SDValue, 8> MemOpChains;
3050 // Walk the register/memloc assignments, inserting copies/loads. In the case
3051 // of tail call optimization arguments are handle later.
3052 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3053 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3054 // Skip inalloca arguments, they have already been written.
3055 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3056 if (Flags.isInAlloca())
3059 CCValAssign &VA = ArgLocs[i];
3060 EVT RegVT = VA.getLocVT();
3061 SDValue Arg = OutVals[i];
3062 bool isByVal = Flags.isByVal();
3064 // Promote the value if needed.
3065 switch (VA.getLocInfo()) {
3066 default: llvm_unreachable("Unknown loc info!");
3067 case CCValAssign::Full: break;
3068 case CCValAssign::SExt:
3069 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3071 case CCValAssign::ZExt:
3072 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3074 case CCValAssign::AExt:
3075 if (Arg.getValueType().isVector() &&
3076 Arg.getValueType().getScalarType() == MVT::i1)
3077 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3078 else if (RegVT.is128BitVector()) {
3079 // Special case: passing MMX values in XMM registers.
3080 Arg = DAG.getBitcast(MVT::i64, Arg);
3081 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3082 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3084 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3086 case CCValAssign::BCvt:
3087 Arg = DAG.getBitcast(RegVT, Arg);
3089 case CCValAssign::Indirect: {
3090 // Store the argument.
3091 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3092 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3093 Chain = DAG.getStore(
3094 Chain, dl, Arg, SpillSlot,
3095 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3102 if (VA.isRegLoc()) {
3103 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3104 if (isVarArg && IsWin64) {
3105 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3106 // shadow reg if callee is a varargs function.
3107 unsigned ShadowReg = 0;
3108 switch (VA.getLocReg()) {
3109 case X86::XMM0: ShadowReg = X86::RCX; break;
3110 case X86::XMM1: ShadowReg = X86::RDX; break;
3111 case X86::XMM2: ShadowReg = X86::R8; break;
3112 case X86::XMM3: ShadowReg = X86::R9; break;
3115 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3117 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3118 assert(VA.isMemLoc());
3119 if (!StackPtr.getNode())
3120 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3121 getPointerTy(DAG.getDataLayout()));
3122 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3123 dl, DAG, VA, Flags));
3127 if (!MemOpChains.empty())
3128 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3130 if (Subtarget->isPICStyleGOT()) {
3131 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3134 RegsToPass.push_back(std::make_pair(
3135 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3136 getPointerTy(DAG.getDataLayout()))));
3138 // If we are tail calling and generating PIC/GOT style code load the
3139 // address of the callee into ECX. The value in ecx is used as target of
3140 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3141 // for tail calls on PIC/GOT architectures. Normally we would just put the
3142 // address of GOT into ebx and then call target@PLT. But for tail calls
3143 // ebx would be restored (since ebx is callee saved) before jumping to the
3146 // Note: The actual moving to ECX is done further down.
3147 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3148 if (G && !G->getGlobal()->hasLocalLinkage() &&
3149 G->getGlobal()->hasDefaultVisibility())
3150 Callee = LowerGlobalAddress(Callee, DAG);
3151 else if (isa<ExternalSymbolSDNode>(Callee))
3152 Callee = LowerExternalSymbol(Callee, DAG);
3156 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3157 // From AMD64 ABI document:
3158 // For calls that may call functions that use varargs or stdargs
3159 // (prototype-less calls or calls to functions containing ellipsis (...) in
3160 // the declaration) %al is used as hidden argument to specify the number
3161 // of SSE registers used. The contents of %al do not need to match exactly
3162 // the number of registers, but must be an ubound on the number of SSE
3163 // registers used and is in the range 0 - 8 inclusive.
3165 // Count the number of XMM registers allocated.
3166 static const MCPhysReg XMMArgRegs[] = {
3167 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3168 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3170 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3171 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3172 && "SSE registers cannot be used when SSE is disabled");
3174 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3175 DAG.getConstant(NumXMMRegs, dl,
3179 if (isVarArg && IsMustTail) {
3180 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3181 for (const auto &F : Forwards) {
3182 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3183 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3187 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3188 // don't need this because the eligibility check rejects calls that require
3189 // shuffling arguments passed in memory.
3190 if (!IsSibcall && isTailCall) {
3191 // Force all the incoming stack arguments to be loaded from the stack
3192 // before any new outgoing arguments are stored to the stack, because the
3193 // outgoing stack slots may alias the incoming argument stack slots, and
3194 // the alias isn't otherwise explicit. This is slightly more conservative
3195 // than necessary, because it means that each store effectively depends
3196 // on every argument instead of just those arguments it would clobber.
3197 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3199 SmallVector<SDValue, 8> MemOpChains2;
3202 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3203 CCValAssign &VA = ArgLocs[i];
3206 assert(VA.isMemLoc());
3207 SDValue Arg = OutVals[i];
3208 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3209 // Skip inalloca arguments. They don't require any work.
3210 if (Flags.isInAlloca())
3212 // Create frame index.
3213 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3214 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3215 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3216 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3218 if (Flags.isByVal()) {
3219 // Copy relative to framepointer.
3220 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3221 if (!StackPtr.getNode())
3222 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3223 getPointerTy(DAG.getDataLayout()));
3224 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3227 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3231 // Store relative to framepointer.
3232 MemOpChains2.push_back(DAG.getStore(
3233 ArgChain, dl, Arg, FIN,
3234 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3239 if (!MemOpChains2.empty())
3240 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3242 // Store the return address to the appropriate stack slot.
3243 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3244 getPointerTy(DAG.getDataLayout()),
3245 RegInfo->getSlotSize(), FPDiff, dl);
3248 // Build a sequence of copy-to-reg nodes chained together with token chain
3249 // and flag operands which copy the outgoing args into registers.
3251 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3252 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3253 RegsToPass[i].second, InFlag);
3254 InFlag = Chain.getValue(1);
3257 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3258 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3259 // In the 64-bit large code model, we have to make all calls
3260 // through a register, since the call instruction's 32-bit
3261 // pc-relative offset may not be large enough to hold the whole
3263 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3264 // If the callee is a GlobalAddress node (quite common, every direct call
3265 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3267 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3269 // We should use extra load for direct calls to dllimported functions in
3271 const GlobalValue *GV = G->getGlobal();
3272 if (!GV->hasDLLImportStorageClass()) {
3273 unsigned char OpFlags = 0;
3274 bool ExtraLoad = false;
3275 unsigned WrapperKind = ISD::DELETED_NODE;
3277 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3278 // external symbols most go through the PLT in PIC mode. If the symbol
3279 // has hidden or protected visibility, or if it is static or local, then
3280 // we don't need to use the PLT - we can directly call it.
3281 if (Subtarget->isTargetELF() &&
3282 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3283 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3284 OpFlags = X86II::MO_PLT;
3285 } else if (Subtarget->isPICStyleStubAny() &&
3286 !GV->isStrongDefinitionForLinker() &&
3287 (!Subtarget->getTargetTriple().isMacOSX() ||
3288 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3289 // PC-relative references to external symbols should go through $stub,
3290 // unless we're building with the leopard linker or later, which
3291 // automatically synthesizes these stubs.
3292 OpFlags = X86II::MO_DARWIN_STUB;
3293 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3294 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3295 // If the function is marked as non-lazy, generate an indirect call
3296 // which loads from the GOT directly. This avoids runtime overhead
3297 // at the cost of eager binding (and one extra byte of encoding).
3298 OpFlags = X86II::MO_GOTPCREL;
3299 WrapperKind = X86ISD::WrapperRIP;
3303 Callee = DAG.getTargetGlobalAddress(
3304 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3306 // Add a wrapper if needed.
3307 if (WrapperKind != ISD::DELETED_NODE)
3308 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3309 getPointerTy(DAG.getDataLayout()), Callee);
3310 // Add extra indirection if needed.
3312 Callee = DAG.getLoad(
3313 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3314 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3317 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3318 unsigned char OpFlags = 0;
3320 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3321 // external symbols should go through the PLT.
3322 if (Subtarget->isTargetELF() &&
3323 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3324 OpFlags = X86II::MO_PLT;
3325 } else if (Subtarget->isPICStyleStubAny() &&
3326 (!Subtarget->getTargetTriple().isMacOSX() ||
3327 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3328 // PC-relative references to external symbols should go through $stub,
3329 // unless we're building with the leopard linker or later, which
3330 // automatically synthesizes these stubs.
3331 OpFlags = X86II::MO_DARWIN_STUB;
3334 Callee = DAG.getTargetExternalSymbol(
3335 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3336 } else if (Subtarget->isTarget64BitILP32() &&
3337 Callee->getValueType(0) == MVT::i32) {
3338 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3339 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3342 // Returns a chain & a flag for retval copy to use.
3343 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3344 SmallVector<SDValue, 8> Ops;
3346 if (!IsSibcall && isTailCall) {
3347 Chain = DAG.getCALLSEQ_END(Chain,
3348 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3349 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3350 InFlag = Chain.getValue(1);
3353 Ops.push_back(Chain);
3354 Ops.push_back(Callee);
3357 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3359 // Add argument registers to the end of the list so that they are known live
3361 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3362 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3363 RegsToPass[i].second.getValueType()));
3365 // Add a register mask operand representing the call-preserved registers.
3366 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3367 assert(Mask && "Missing call preserved mask for calling convention");
3369 // If this is an invoke in a 32-bit function using an MSVC personality, assume
3370 // the function clobbers all registers. If an exception is thrown, the runtime
3371 // will not restore CSRs.
3372 // FIXME: Model this more precisely so that we can register allocate across
3373 // the normal edge and spill and fill across the exceptional edge.
3374 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3375 const Function *CallerFn = MF.getFunction();
3376 EHPersonality Pers =
3377 CallerFn->hasPersonalityFn()
3378 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3379 : EHPersonality::Unknown;
3380 if (isMSVCEHPersonality(Pers))
3381 Mask = RegInfo->getNoPreservedMask();
3384 Ops.push_back(DAG.getRegisterMask(Mask));
3386 if (InFlag.getNode())
3387 Ops.push_back(InFlag);
3391 //// If this is the first return lowered for this function, add the regs
3392 //// to the liveout set for the function.
3393 // This isn't right, although it's probably harmless on x86; liveouts
3394 // should be computed from returns not tail calls. Consider a void
3395 // function making a tail call to a function returning int.
3396 MF.getFrameInfo()->setHasTailCall();
3397 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3400 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3401 InFlag = Chain.getValue(1);
3403 // Create the CALLSEQ_END node.
3404 unsigned NumBytesForCalleeToPop;
3405 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3406 DAG.getTarget().Options.GuaranteedTailCallOpt))
3407 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3408 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3409 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3410 SR == StackStructReturn)
3411 // If this is a call to a struct-return function, the callee
3412 // pops the hidden struct pointer, so we have to push it back.
3413 // This is common for Darwin/X86, Linux & Mingw32 targets.
3414 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3415 NumBytesForCalleeToPop = 4;
3417 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3419 // Returns a flag for retval copy to use.
3421 Chain = DAG.getCALLSEQ_END(Chain,
3422 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3423 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3426 InFlag = Chain.getValue(1);
3429 // Handle result values, copying them out of physregs into vregs that we
3431 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3432 Ins, dl, DAG, InVals);
3435 //===----------------------------------------------------------------------===//
3436 // Fast Calling Convention (tail call) implementation
3437 //===----------------------------------------------------------------------===//
3439 // Like std call, callee cleans arguments, convention except that ECX is
3440 // reserved for storing the tail called function address. Only 2 registers are
3441 // free for argument passing (inreg). Tail call optimization is performed
3443 // * tailcallopt is enabled
3444 // * caller/callee are fastcc
3445 // On X86_64 architecture with GOT-style position independent code only local
3446 // (within module) calls are supported at the moment.
3447 // To keep the stack aligned according to platform abi the function
3448 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3449 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3450 // If a tail called function callee has more arguments than the caller the
3451 // caller needs to make sure that there is room to move the RETADDR to. This is
3452 // achieved by reserving an area the size of the argument delta right after the
3453 // original RETADDR, but before the saved framepointer or the spilled registers
3454 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3466 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3469 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3470 SelectionDAG& DAG) const {
3471 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3472 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3473 unsigned StackAlignment = TFI.getStackAlignment();
3474 uint64_t AlignMask = StackAlignment - 1;
3475 int64_t Offset = StackSize;
3476 unsigned SlotSize = RegInfo->getSlotSize();
3477 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3478 // Number smaller than 12 so just add the difference.
3479 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3481 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3482 Offset = ((~AlignMask) & Offset) + StackAlignment +
3483 (StackAlignment-SlotSize);
3488 /// Return true if the given stack call argument is already available in the
3489 /// same position (relatively) of the caller's incoming argument stack.
3491 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3492 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3493 const X86InstrInfo *TII) {
3494 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3496 if (Arg.getOpcode() == ISD::CopyFromReg) {
3497 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3498 if (!TargetRegisterInfo::isVirtualRegister(VR))
3500 MachineInstr *Def = MRI->getVRegDef(VR);
3503 if (!Flags.isByVal()) {
3504 if (!TII->isLoadFromStackSlot(Def, FI))
3507 unsigned Opcode = Def->getOpcode();
3508 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3509 Opcode == X86::LEA64_32r) &&
3510 Def->getOperand(1).isFI()) {
3511 FI = Def->getOperand(1).getIndex();
3512 Bytes = Flags.getByValSize();
3516 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3517 if (Flags.isByVal())
3518 // ByVal argument is passed in as a pointer but it's now being
3519 // dereferenced. e.g.
3520 // define @foo(%struct.X* %A) {
3521 // tail call @bar(%struct.X* byval %A)
3524 SDValue Ptr = Ld->getBasePtr();
3525 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3528 FI = FINode->getIndex();
3529 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3530 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3531 FI = FINode->getIndex();
3532 Bytes = Flags.getByValSize();
3536 assert(FI != INT_MAX);
3537 if (!MFI->isFixedObjectIndex(FI))
3539 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3542 /// Check whether the call is eligible for tail call optimization. Targets
3543 /// that want to do tail call optimization should implement this function.
3544 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3545 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3546 bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3547 const SmallVectorImpl<ISD::OutputArg> &Outs,
3548 const SmallVectorImpl<SDValue> &OutVals,
3549 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3550 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3553 // If -tailcallopt is specified, make fastcc functions tail-callable.
3554 const MachineFunction &MF = DAG.getMachineFunction();
3555 const Function *CallerF = MF.getFunction();
3557 // If the function return type is x86_fp80 and the callee return type is not,
3558 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3559 // perform a tailcall optimization here.
3560 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3563 CallingConv::ID CallerCC = CallerF->getCallingConv();
3564 bool CCMatch = CallerCC == CalleeCC;
3565 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3566 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3568 // Win64 functions have extra shadow space for argument homing. Don't do the
3569 // sibcall if the caller and callee have mismatched expectations for this
3571 if (IsCalleeWin64 != IsCallerWin64)
3574 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3575 if (IsTailCallConvention(CalleeCC) && CCMatch)
3580 // Look for obvious safe cases to perform tail call optimization that do not
3581 // require ABI changes. This is what gcc calls sibcall.
3583 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3584 // emit a special epilogue.
3585 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3586 if (RegInfo->needsStackRealignment(MF))
3589 // Also avoid sibcall optimization if either caller or callee uses struct
3590 // return semantics.
3591 if (isCalleeStructRet || isCallerStructRet)
3594 // An stdcall/thiscall caller is expected to clean up its arguments; the
3595 // callee isn't going to do that.
3596 // FIXME: this is more restrictive than needed. We could produce a tailcall
3597 // when the stack adjustment matches. For example, with a thiscall that takes
3598 // only one argument.
3599 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3600 CallerCC == CallingConv::X86_ThisCall))
3603 // Do not sibcall optimize vararg calls unless all arguments are passed via
3605 if (isVarArg && !Outs.empty()) {
3607 // Optimizing for varargs on Win64 is unlikely to be safe without
3608 // additional testing.
3609 if (IsCalleeWin64 || IsCallerWin64)
3612 SmallVector<CCValAssign, 16> ArgLocs;
3613 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3616 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3617 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3618 if (!ArgLocs[i].isRegLoc())
3622 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3623 // stack. Therefore, if it's not used by the call it is not safe to optimize
3624 // this into a sibcall.
3625 bool Unused = false;
3626 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3633 SmallVector<CCValAssign, 16> RVLocs;
3634 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3636 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3637 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3638 CCValAssign &VA = RVLocs[i];
3639 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3644 // If the calling conventions do not match, then we'd better make sure the
3645 // results are returned in the same way as what the caller expects.
3647 SmallVector<CCValAssign, 16> RVLocs1;
3648 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3650 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3652 SmallVector<CCValAssign, 16> RVLocs2;
3653 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3655 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3657 if (RVLocs1.size() != RVLocs2.size())
3659 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3660 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3662 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3664 if (RVLocs1[i].isRegLoc()) {
3665 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3668 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3674 // If the callee takes no arguments then go on to check the results of the
3676 if (!Outs.empty()) {
3677 // Check if stack adjustment is needed. For now, do not do this if any
3678 // argument is passed on the stack.
3679 SmallVector<CCValAssign, 16> ArgLocs;
3680 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3683 // Allocate shadow area for Win64
3685 CCInfo.AllocateStack(32, 8);
3687 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3688 if (CCInfo.getNextStackOffset()) {
3689 MachineFunction &MF = DAG.getMachineFunction();
3690 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3693 // Check if the arguments are already laid out in the right way as
3694 // the caller's fixed stack objects.
3695 MachineFrameInfo *MFI = MF.getFrameInfo();
3696 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3697 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3698 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3699 CCValAssign &VA = ArgLocs[i];
3700 SDValue Arg = OutVals[i];
3701 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3702 if (VA.getLocInfo() == CCValAssign::Indirect)
3704 if (!VA.isRegLoc()) {
3705 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3712 // If the tailcall address may be in a register, then make sure it's
3713 // possible to register allocate for it. In 32-bit, the call address can
3714 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3715 // callee-saved registers are restored. These happen to be the same
3716 // registers used to pass 'inreg' arguments so watch out for those.
3717 if (!Subtarget->is64Bit() &&
3718 ((!isa<GlobalAddressSDNode>(Callee) &&
3719 !isa<ExternalSymbolSDNode>(Callee)) ||
3720 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3721 unsigned NumInRegs = 0;
3722 // In PIC we need an extra register to formulate the address computation
3724 unsigned MaxInRegs =
3725 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3727 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3728 CCValAssign &VA = ArgLocs[i];
3731 unsigned Reg = VA.getLocReg();
3734 case X86::EAX: case X86::EDX: case X86::ECX:
3735 if (++NumInRegs == MaxInRegs)
3747 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3748 const TargetLibraryInfo *libInfo) const {
3749 return X86::createFastISel(funcInfo, libInfo);
3752 //===----------------------------------------------------------------------===//
3753 // Other Lowering Hooks
3754 //===----------------------------------------------------------------------===//
3756 static bool MayFoldLoad(SDValue Op) {
3757 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3760 static bool MayFoldIntoStore(SDValue Op) {
3761 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3764 static bool isTargetShuffle(unsigned Opcode) {
3766 default: return false;
3767 case X86ISD::BLENDI:
3768 case X86ISD::PSHUFB:
3769 case X86ISD::PSHUFD:
3770 case X86ISD::PSHUFHW:
3771 case X86ISD::PSHUFLW:
3773 case X86ISD::PALIGNR:
3774 case X86ISD::MOVLHPS:
3775 case X86ISD::MOVLHPD:
3776 case X86ISD::MOVHLPS:
3777 case X86ISD::MOVLPS:
3778 case X86ISD::MOVLPD:
3779 case X86ISD::MOVSHDUP:
3780 case X86ISD::MOVSLDUP:
3781 case X86ISD::MOVDDUP:
3784 case X86ISD::UNPCKL:
3785 case X86ISD::UNPCKH:
3786 case X86ISD::VPERMILPI:
3787 case X86ISD::VPERM2X128:
3788 case X86ISD::VPERMI:
3789 case X86ISD::VPERMV:
3790 case X86ISD::VPERMV3:
3795 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3796 SDValue V1, unsigned TargetMask,
3797 SelectionDAG &DAG) {
3799 default: llvm_unreachable("Unknown x86 shuffle node");
3800 case X86ISD::PSHUFD:
3801 case X86ISD::PSHUFHW:
3802 case X86ISD::PSHUFLW:
3803 case X86ISD::VPERMILPI:
3804 case X86ISD::VPERMI:
3805 return DAG.getNode(Opc, dl, VT, V1,
3806 DAG.getConstant(TargetMask, dl, MVT::i8));
3810 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3811 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3813 default: llvm_unreachable("Unknown x86 shuffle node");
3814 case X86ISD::MOVLHPS:
3815 case X86ISD::MOVLHPD:
3816 case X86ISD::MOVHLPS:
3817 case X86ISD::MOVLPS:
3818 case X86ISD::MOVLPD:
3821 case X86ISD::UNPCKL:
3822 case X86ISD::UNPCKH:
3823 return DAG.getNode(Opc, dl, VT, V1, V2);
3827 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3828 MachineFunction &MF = DAG.getMachineFunction();
3829 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3830 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3831 int ReturnAddrIndex = FuncInfo->getRAIndex();
3833 if (ReturnAddrIndex == 0) {
3834 // Set up a frame object for the return address.
3835 unsigned SlotSize = RegInfo->getSlotSize();
3836 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3839 FuncInfo->setRAIndex(ReturnAddrIndex);
3842 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3845 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3846 bool hasSymbolicDisplacement) {
3847 // Offset should fit into 32 bit immediate field.
3848 if (!isInt<32>(Offset))
3851 // If we don't have a symbolic displacement - we don't have any extra
3853 if (!hasSymbolicDisplacement)
3856 // FIXME: Some tweaks might be needed for medium code model.
3857 if (M != CodeModel::Small && M != CodeModel::Kernel)
3860 // For small code model we assume that latest object is 16MB before end of 31
3861 // bits boundary. We may also accept pretty large negative constants knowing
3862 // that all objects are in the positive half of address space.
3863 if (M == CodeModel::Small && Offset < 16*1024*1024)
3866 // For kernel code model we know that all object resist in the negative half
3867 // of 32bits address space. We may not accept negative offsets, since they may
3868 // be just off and we may accept pretty large positive ones.
3869 if (M == CodeModel::Kernel && Offset >= 0)
3875 /// Determines whether the callee is required to pop its own arguments.
3876 /// Callee pop is necessary to support tail calls.
3877 bool X86::isCalleePop(CallingConv::ID CallingConv,
3878 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3879 switch (CallingConv) {
3882 case CallingConv::X86_StdCall:
3883 case CallingConv::X86_FastCall:
3884 case CallingConv::X86_ThisCall:
3886 case CallingConv::Fast:
3887 case CallingConv::GHC:
3888 case CallingConv::HiPE:
3895 /// \brief Return true if the condition is an unsigned comparison operation.
3896 static bool isX86CCUnsigned(unsigned X86CC) {
3898 default: llvm_unreachable("Invalid integer condition!");
3899 case X86::COND_E: return true;
3900 case X86::COND_G: return false;
3901 case X86::COND_GE: return false;
3902 case X86::COND_L: return false;
3903 case X86::COND_LE: return false;
3904 case X86::COND_NE: return true;
3905 case X86::COND_B: return true;
3906 case X86::COND_A: return true;
3907 case X86::COND_BE: return true;
3908 case X86::COND_AE: return true;
3910 llvm_unreachable("covered switch fell through?!");
3913 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3914 /// condition code, returning the condition code and the LHS/RHS of the
3915 /// comparison to make.
3916 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3917 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3919 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3920 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3921 // X > -1 -> X == 0, jump !sign.
3922 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3923 return X86::COND_NS;
3925 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3926 // X < 0 -> X == 0, jump on sign.
3929 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3931 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3932 return X86::COND_LE;
3936 switch (SetCCOpcode) {
3937 default: llvm_unreachable("Invalid integer condition!");
3938 case ISD::SETEQ: return X86::COND_E;
3939 case ISD::SETGT: return X86::COND_G;
3940 case ISD::SETGE: return X86::COND_GE;
3941 case ISD::SETLT: return X86::COND_L;
3942 case ISD::SETLE: return X86::COND_LE;
3943 case ISD::SETNE: return X86::COND_NE;
3944 case ISD::SETULT: return X86::COND_B;
3945 case ISD::SETUGT: return X86::COND_A;
3946 case ISD::SETULE: return X86::COND_BE;
3947 case ISD::SETUGE: return X86::COND_AE;
3951 // First determine if it is required or is profitable to flip the operands.
3953 // If LHS is a foldable load, but RHS is not, flip the condition.
3954 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3955 !ISD::isNON_EXTLoad(RHS.getNode())) {
3956 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3957 std::swap(LHS, RHS);
3960 switch (SetCCOpcode) {
3966 std::swap(LHS, RHS);
3970 // On a floating point condition, the flags are set as follows:
3972 // 0 | 0 | 0 | X > Y
3973 // 0 | 0 | 1 | X < Y
3974 // 1 | 0 | 0 | X == Y
3975 // 1 | 1 | 1 | unordered
3976 switch (SetCCOpcode) {
3977 default: llvm_unreachable("Condcode should be pre-legalized away");
3979 case ISD::SETEQ: return X86::COND_E;
3980 case ISD::SETOLT: // flipped
3982 case ISD::SETGT: return X86::COND_A;
3983 case ISD::SETOLE: // flipped
3985 case ISD::SETGE: return X86::COND_AE;
3986 case ISD::SETUGT: // flipped
3988 case ISD::SETLT: return X86::COND_B;
3989 case ISD::SETUGE: // flipped
3991 case ISD::SETLE: return X86::COND_BE;
3993 case ISD::SETNE: return X86::COND_NE;
3994 case ISD::SETUO: return X86::COND_P;
3995 case ISD::SETO: return X86::COND_NP;
3997 case ISD::SETUNE: return X86::COND_INVALID;
4001 /// Is there a floating point cmov for the specific X86 condition code?
4002 /// Current x86 isa includes the following FP cmov instructions:
4003 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4004 static bool hasFPCMov(unsigned X86CC) {
4020 /// Returns true if the target can instruction select the
4021 /// specified FP immediate natively. If false, the legalizer will
4022 /// materialize the FP immediate as a load from a constant pool.
4023 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4024 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4025 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4031 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4032 ISD::LoadExtType ExtTy,
4034 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4035 // relocation target a movq or addq instruction: don't let the load shrink.
4036 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4037 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4038 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4039 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4043 /// \brief Returns true if it is beneficial to convert a load of a constant
4044 /// to just the constant itself.
4045 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4047 assert(Ty->isIntegerTy());
4049 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4050 if (BitSize == 0 || BitSize > 64)
4055 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4056 unsigned Index) const {
4057 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4060 return (Index == 0 || Index == ResVT.getVectorNumElements());
4063 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4064 // Speculate cttz only if we can directly use TZCNT.
4065 return Subtarget->hasBMI();
4068 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4069 // Speculate ctlz only if we can directly use LZCNT.
4070 return Subtarget->hasLZCNT();
4073 /// Return true if every element in Mask, beginning
4074 /// from position Pos and ending in Pos+Size is undef.
4075 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4076 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4082 /// Return true if Val is undef or if its value falls within the
4083 /// specified range (L, H].
4084 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4085 return (Val < 0) || (Val >= Low && Val < Hi);
4088 /// Val is either less than zero (undef) or equal to the specified value.
4089 static bool isUndefOrEqual(int Val, int CmpVal) {
4090 return (Val < 0 || Val == CmpVal);
4093 /// Return true if every element in Mask, beginning
4094 /// from position Pos and ending in Pos+Size, falls within the specified
4095 /// sequential range (Low, Low+Size]. or is undef.
4096 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4097 unsigned Pos, unsigned Size, int Low) {
4098 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4099 if (!isUndefOrEqual(Mask[i], Low))
4104 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4105 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4106 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4107 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4108 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4111 // The index should be aligned on a vecWidth-bit boundary.
4113 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4115 MVT VT = N->getSimpleValueType(0);
4116 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4117 bool Result = (Index * ElSize) % vecWidth == 0;
4122 /// Return true if the specified INSERT_SUBVECTOR
4123 /// operand specifies a subvector insert that is suitable for input to
4124 /// insertion of 128 or 256-bit subvectors
4125 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4126 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4127 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4129 // The index should be aligned on a vecWidth-bit boundary.
4131 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4133 MVT VT = N->getSimpleValueType(0);
4134 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4135 bool Result = (Index * ElSize) % vecWidth == 0;
4140 bool X86::isVINSERT128Index(SDNode *N) {
4141 return isVINSERTIndex(N, 128);
4144 bool X86::isVINSERT256Index(SDNode *N) {
4145 return isVINSERTIndex(N, 256);
4148 bool X86::isVEXTRACT128Index(SDNode *N) {
4149 return isVEXTRACTIndex(N, 128);
4152 bool X86::isVEXTRACT256Index(SDNode *N) {
4153 return isVEXTRACTIndex(N, 256);
4156 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4157 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4158 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4159 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4162 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4164 MVT VecVT = N->getOperand(0).getSimpleValueType();
4165 MVT ElVT = VecVT.getVectorElementType();
4167 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4168 return Index / NumElemsPerChunk;
4171 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4172 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4173 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4174 llvm_unreachable("Illegal insert subvector for VINSERT");
4177 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4179 MVT VecVT = N->getSimpleValueType(0);
4180 MVT ElVT = VecVT.getVectorElementType();
4182 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4183 return Index / NumElemsPerChunk;
4186 /// Return the appropriate immediate to extract the specified
4187 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4188 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4189 return getExtractVEXTRACTImmediate(N, 128);
4192 /// Return the appropriate immediate to extract the specified
4193 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4194 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4195 return getExtractVEXTRACTImmediate(N, 256);
4198 /// Return the appropriate immediate to insert at the specified
4199 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4200 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4201 return getInsertVINSERTImmediate(N, 128);
4204 /// Return the appropriate immediate to insert at the specified
4205 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4206 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4207 return getInsertVINSERTImmediate(N, 256);
4210 /// Returns true if Elt is a constant integer zero
4211 static bool isZero(SDValue V) {
4212 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4213 return C && C->isNullValue();
4216 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4217 bool X86::isZeroNode(SDValue Elt) {
4220 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4221 return CFP->getValueAPF().isPosZero();
4225 /// Returns a vector of specified type with all zero elements.
4226 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4227 SelectionDAG &DAG, SDLoc dl) {
4228 assert(VT.isVector() && "Expected a vector type");
4230 // Always build SSE zero vectors as <4 x i32> bitcasted
4231 // to their dest type. This ensures they get CSE'd.
4233 if (VT.is128BitVector()) { // SSE
4234 if (Subtarget->hasSSE2()) { // SSE2
4235 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4236 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4238 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4239 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4241 } else if (VT.is256BitVector()) { // AVX
4242 if (Subtarget->hasInt256()) { // AVX2
4243 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4244 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4245 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4247 // 256-bit logic and arithmetic instructions in AVX are all
4248 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4249 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4250 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4251 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4253 } else if (VT.is512BitVector()) { // AVX-512
4254 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4255 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4256 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4257 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4258 } else if (VT.getScalarType() == MVT::i1) {
4260 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4261 && "Unexpected vector type");
4262 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4263 && "Unexpected vector type");
4264 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4265 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4266 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4268 llvm_unreachable("Unexpected vector type");
4270 return DAG.getBitcast(VT, Vec);
4273 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4274 SelectionDAG &DAG, SDLoc dl,
4275 unsigned vectorWidth) {
4276 assert((vectorWidth == 128 || vectorWidth == 256) &&
4277 "Unsupported vector width");
4278 EVT VT = Vec.getValueType();
4279 EVT ElVT = VT.getVectorElementType();
4280 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4281 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4282 VT.getVectorNumElements()/Factor);
4284 // Extract from UNDEF is UNDEF.
4285 if (Vec.getOpcode() == ISD::UNDEF)
4286 return DAG.getUNDEF(ResultVT);
4288 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4289 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4291 // This is the index of the first element of the vectorWidth-bit chunk
4293 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4296 // If the input is a buildvector just emit a smaller one.
4297 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4298 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4299 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4302 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4303 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4306 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4307 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4308 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4309 /// instructions or a simple subregister reference. Idx is an index in the
4310 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4311 /// lowering EXTRACT_VECTOR_ELT operations easier.
4312 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4313 SelectionDAG &DAG, SDLoc dl) {
4314 assert((Vec.getValueType().is256BitVector() ||
4315 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4316 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4319 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4320 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4321 SelectionDAG &DAG, SDLoc dl) {
4322 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4323 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4326 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4327 unsigned IdxVal, SelectionDAG &DAG,
4328 SDLoc dl, unsigned vectorWidth) {
4329 assert((vectorWidth == 128 || vectorWidth == 256) &&
4330 "Unsupported vector width");
4331 // Inserting UNDEF is Result
4332 if (Vec.getOpcode() == ISD::UNDEF)
4334 EVT VT = Vec.getValueType();
4335 EVT ElVT = VT.getVectorElementType();
4336 EVT ResultVT = Result.getValueType();
4338 // Insert the relevant vectorWidth bits.
4339 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4341 // This is the index of the first element of the vectorWidth-bit chunk
4343 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4346 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4347 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4350 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4351 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4352 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4353 /// simple superregister reference. Idx is an index in the 128 bits
4354 /// we want. It need not be aligned to a 128-bit boundary. That makes
4355 /// lowering INSERT_VECTOR_ELT operations easier.
4356 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4357 SelectionDAG &DAG, SDLoc dl) {
4358 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4360 // For insertion into the zero index (low half) of a 256-bit vector, it is
4361 // more efficient to generate a blend with immediate instead of an insert*128.
4362 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4363 // extend the subvector to the size of the result vector. Make sure that
4364 // we are not recursing on that node by checking for undef here.
4365 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4366 Result.getOpcode() != ISD::UNDEF) {
4367 EVT ResultVT = Result.getValueType();
4368 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4369 SDValue Undef = DAG.getUNDEF(ResultVT);
4370 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4373 // The blend instruction, and therefore its mask, depend on the data type.
4374 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4375 if (ScalarType.isFloatingPoint()) {
4376 // Choose either vblendps (float) or vblendpd (double).
4377 unsigned ScalarSize = ScalarType.getSizeInBits();
4378 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4379 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4380 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4381 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4384 const X86Subtarget &Subtarget =
4385 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4387 // AVX2 is needed for 256-bit integer blend support.
4388 // Integers must be cast to 32-bit because there is only vpblendd;
4389 // vpblendw can't be used for this because it has a handicapped mask.
4391 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4392 // is still more efficient than using the wrong domain vinsertf128 that
4393 // will be created by InsertSubVector().
4394 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4396 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4397 Vec256 = DAG.getBitcast(CastVT, Vec256);
4398 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4399 return DAG.getBitcast(ResultVT, Vec256);
4402 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4405 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4406 SelectionDAG &DAG, SDLoc dl) {
4407 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4408 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4411 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4412 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4413 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4414 /// large BUILD_VECTORS.
4415 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4416 unsigned NumElems, SelectionDAG &DAG,
4418 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4419 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4422 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4423 unsigned NumElems, SelectionDAG &DAG,
4425 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4426 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4429 /// Returns a vector of specified type with all bits set.
4430 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4431 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4432 /// Then bitcast to their original type, ensuring they get CSE'd.
4433 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4434 SelectionDAG &DAG, SDLoc dl) {
4435 assert(VT.isVector() && "Expected a vector type");
4437 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4439 if (VT.is512BitVector()) {
4440 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4441 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4442 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4443 } else if (VT.is256BitVector()) {
4444 if (Subtarget->hasInt256()) { // AVX2
4445 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4446 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4448 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4449 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4451 } else if (VT.is128BitVector()) {
4452 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4454 llvm_unreachable("Unexpected vector type");
4456 return DAG.getBitcast(VT, Vec);
4459 /// Returns a vector_shuffle node for an unpackl operation.
4460 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4462 unsigned NumElems = VT.getVectorNumElements();
4463 SmallVector<int, 8> Mask;
4464 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4466 Mask.push_back(i + NumElems);
4468 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4471 /// Returns a vector_shuffle node for an unpackh operation.
4472 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4474 unsigned NumElems = VT.getVectorNumElements();
4475 SmallVector<int, 8> Mask;
4476 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4477 Mask.push_back(i + Half);
4478 Mask.push_back(i + NumElems + Half);
4480 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4483 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4484 /// This produces a shuffle where the low element of V2 is swizzled into the
4485 /// zero/undef vector, landing at element Idx.
4486 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4487 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4489 const X86Subtarget *Subtarget,
4490 SelectionDAG &DAG) {
4491 MVT VT = V2.getSimpleValueType();
4493 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4494 unsigned NumElems = VT.getVectorNumElements();
4495 SmallVector<int, 16> MaskVec;
4496 for (unsigned i = 0; i != NumElems; ++i)
4497 // If this is the insertion idx, put the low elt of V2 here.
4498 MaskVec.push_back(i == Idx ? NumElems : i);
4499 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4502 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4503 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4504 /// uses one source. Note that this will set IsUnary for shuffles which use a
4505 /// single input multiple times, and in those cases it will
4506 /// adjust the mask to only have indices within that single input.
4507 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4508 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4509 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4510 unsigned NumElems = VT.getVectorNumElements();
4514 bool IsFakeUnary = false;
4515 switch(N->getOpcode()) {
4516 case X86ISD::BLENDI:
4517 ImmN = N->getOperand(N->getNumOperands()-1);
4518 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4521 ImmN = N->getOperand(N->getNumOperands()-1);
4522 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4523 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4525 case X86ISD::UNPCKH:
4526 DecodeUNPCKHMask(VT, Mask);
4527 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4529 case X86ISD::UNPCKL:
4530 DecodeUNPCKLMask(VT, Mask);
4531 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4533 case X86ISD::MOVHLPS:
4534 DecodeMOVHLPSMask(NumElems, Mask);
4535 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4537 case X86ISD::MOVLHPS:
4538 DecodeMOVLHPSMask(NumElems, Mask);
4539 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4541 case X86ISD::PALIGNR:
4542 ImmN = N->getOperand(N->getNumOperands()-1);
4543 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4545 case X86ISD::PSHUFD:
4546 case X86ISD::VPERMILPI:
4547 ImmN = N->getOperand(N->getNumOperands()-1);
4548 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4551 case X86ISD::PSHUFHW:
4552 ImmN = N->getOperand(N->getNumOperands()-1);
4553 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4556 case X86ISD::PSHUFLW:
4557 ImmN = N->getOperand(N->getNumOperands()-1);
4558 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4561 case X86ISD::PSHUFB: {
4563 SDValue MaskNode = N->getOperand(1);
4564 while (MaskNode->getOpcode() == ISD::BITCAST)
4565 MaskNode = MaskNode->getOperand(0);
4567 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4568 // If we have a build-vector, then things are easy.
4569 EVT VT = MaskNode.getValueType();
4570 assert(VT.isVector() &&
4571 "Can't produce a non-vector with a build_vector!");
4572 if (!VT.isInteger())
4575 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4577 SmallVector<uint64_t, 32> RawMask;
4578 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4579 SDValue Op = MaskNode->getOperand(i);
4580 if (Op->getOpcode() == ISD::UNDEF) {
4581 RawMask.push_back((uint64_t)SM_SentinelUndef);
4584 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4587 APInt MaskElement = CN->getAPIntValue();
4589 // We now have to decode the element which could be any integer size and
4590 // extract each byte of it.
4591 for (int j = 0; j < NumBytesPerElement; ++j) {
4592 // Note that this is x86 and so always little endian: the low byte is
4593 // the first byte of the mask.
4594 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4595 MaskElement = MaskElement.lshr(8);
4598 DecodePSHUFBMask(RawMask, Mask);
4602 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4606 SDValue Ptr = MaskLoad->getBasePtr();
4607 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4608 Ptr->getOpcode() == X86ISD::WrapperRIP)
4609 Ptr = Ptr->getOperand(0);
4611 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4612 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4615 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4616 DecodePSHUFBMask(C, Mask);
4624 case X86ISD::VPERMI:
4625 ImmN = N->getOperand(N->getNumOperands()-1);
4626 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4631 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4633 case X86ISD::VPERM2X128:
4634 ImmN = N->getOperand(N->getNumOperands()-1);
4635 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4636 if (Mask.empty()) return false;
4637 // Mask only contains negative index if an element is zero.
4638 if (std::any_of(Mask.begin(), Mask.end(),
4639 [](int M){ return M == SM_SentinelZero; }))
4642 case X86ISD::MOVSLDUP:
4643 DecodeMOVSLDUPMask(VT, Mask);
4646 case X86ISD::MOVSHDUP:
4647 DecodeMOVSHDUPMask(VT, Mask);
4650 case X86ISD::MOVDDUP:
4651 DecodeMOVDDUPMask(VT, Mask);
4654 case X86ISD::MOVLHPD:
4655 case X86ISD::MOVLPD:
4656 case X86ISD::MOVLPS:
4657 // Not yet implemented
4659 case X86ISD::VPERMV: {
4661 SDValue MaskNode = N->getOperand(0);
4662 while (MaskNode->getOpcode() == ISD::BITCAST)
4663 MaskNode = MaskNode->getOperand(0);
4665 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4666 SmallVector<uint64_t, 32> RawMask;
4667 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4668 // If we have a build-vector, then things are easy.
4669 assert(MaskNode.getValueType().isInteger() &&
4670 MaskNode.getValueType().getVectorNumElements() ==
4671 VT.getVectorNumElements());
4673 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4674 SDValue Op = MaskNode->getOperand(i);
4675 if (Op->getOpcode() == ISD::UNDEF)
4676 RawMask.push_back((uint64_t)SM_SentinelUndef);
4677 else if (isa<ConstantSDNode>(Op)) {
4678 APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4679 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4683 DecodeVPERMVMask(RawMask, Mask);
4686 if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4687 unsigned NumEltsInMask = MaskNode->getNumOperands();
4688 MaskNode = MaskNode->getOperand(0);
4689 auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4691 APInt MaskEltValue = CN->getAPIntValue();
4692 for (unsigned i = 0; i < NumEltsInMask; ++i)
4693 RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4694 DecodeVPERMVMask(RawMask, Mask);
4697 // It may be a scalar load
4700 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4704 SDValue Ptr = MaskLoad->getBasePtr();
4705 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4706 Ptr->getOpcode() == X86ISD::WrapperRIP)
4707 Ptr = Ptr->getOperand(0);
4709 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4710 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4713 auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4715 DecodeVPERMVMask(C, VT, Mask);
4722 case X86ISD::VPERMV3: {
4724 SDValue MaskNode = N->getOperand(1);
4725 while (MaskNode->getOpcode() == ISD::BITCAST)
4726 MaskNode = MaskNode->getOperand(1);
4728 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4729 // If we have a build-vector, then things are easy.
4730 assert(MaskNode.getValueType().isInteger() &&
4731 MaskNode.getValueType().getVectorNumElements() ==
4732 VT.getVectorNumElements());
4734 SmallVector<uint64_t, 32> RawMask;
4735 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4737 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4738 SDValue Op = MaskNode->getOperand(i);
4739 if (Op->getOpcode() == ISD::UNDEF)
4740 RawMask.push_back((uint64_t)SM_SentinelUndef);
4742 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4745 APInt MaskElement = CN->getAPIntValue();
4746 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4749 DecodeVPERMV3Mask(RawMask, Mask);
4753 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4757 SDValue Ptr = MaskLoad->getBasePtr();
4758 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4759 Ptr->getOpcode() == X86ISD::WrapperRIP)
4760 Ptr = Ptr->getOperand(0);
4762 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4763 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4766 auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4768 DecodeVPERMV3Mask(C, VT, Mask);
4775 default: llvm_unreachable("unknown target shuffle node");
4778 // If we have a fake unary shuffle, the shuffle mask is spread across two
4779 // inputs that are actually the same node. Re-map the mask to always point
4780 // into the first input.
4783 if (M >= (int)Mask.size())
4789 /// Returns the scalar element that will make up the ith
4790 /// element of the result of the vector shuffle.
4791 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4794 return SDValue(); // Limit search depth.
4796 SDValue V = SDValue(N, 0);
4797 EVT VT = V.getValueType();
4798 unsigned Opcode = V.getOpcode();
4800 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4801 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4802 int Elt = SV->getMaskElt(Index);
4805 return DAG.getUNDEF(VT.getVectorElementType());
4807 unsigned NumElems = VT.getVectorNumElements();
4808 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4809 : SV->getOperand(1);
4810 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4813 // Recurse into target specific vector shuffles to find scalars.
4814 if (isTargetShuffle(Opcode)) {
4815 MVT ShufVT = V.getSimpleValueType();
4816 unsigned NumElems = ShufVT.getVectorNumElements();
4817 SmallVector<int, 16> ShuffleMask;
4820 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4823 int Elt = ShuffleMask[Index];
4825 return DAG.getUNDEF(ShufVT.getVectorElementType());
4827 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4829 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4833 // Actual nodes that may contain scalar elements
4834 if (Opcode == ISD::BITCAST) {
4835 V = V.getOperand(0);
4836 EVT SrcVT = V.getValueType();
4837 unsigned NumElems = VT.getVectorNumElements();
4839 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4843 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4844 return (Index == 0) ? V.getOperand(0)
4845 : DAG.getUNDEF(VT.getVectorElementType());
4847 if (V.getOpcode() == ISD::BUILD_VECTOR)
4848 return V.getOperand(Index);
4853 /// Custom lower build_vector of v16i8.
4854 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4855 unsigned NumNonZero, unsigned NumZero,
4857 const X86Subtarget* Subtarget,
4858 const TargetLowering &TLI) {
4866 // SSE4.1 - use PINSRB to insert each byte directly.
4867 if (Subtarget->hasSSE41()) {
4868 for (unsigned i = 0; i < 16; ++i) {
4869 bool isNonZero = (NonZeros & (1 << i)) != 0;
4873 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4875 V = DAG.getUNDEF(MVT::v16i8);
4878 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4879 MVT::v16i8, V, Op.getOperand(i),
4880 DAG.getIntPtrConstant(i, dl));
4887 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4888 for (unsigned i = 0; i < 16; ++i) {
4889 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4890 if (ThisIsNonZero && First) {
4892 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4894 V = DAG.getUNDEF(MVT::v8i16);
4899 SDValue ThisElt, LastElt;
4900 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4901 if (LastIsNonZero) {
4902 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4903 MVT::i16, Op.getOperand(i-1));
4905 if (ThisIsNonZero) {
4906 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4907 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4908 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4910 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4914 if (ThisElt.getNode())
4915 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4916 DAG.getIntPtrConstant(i/2, dl));
4920 return DAG.getBitcast(MVT::v16i8, V);
4923 /// Custom lower build_vector of v8i16.
4924 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4925 unsigned NumNonZero, unsigned NumZero,
4927 const X86Subtarget* Subtarget,
4928 const TargetLowering &TLI) {
4935 for (unsigned i = 0; i < 8; ++i) {
4936 bool isNonZero = (NonZeros & (1 << i)) != 0;
4940 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4942 V = DAG.getUNDEF(MVT::v8i16);
4945 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4946 MVT::v8i16, V, Op.getOperand(i),
4947 DAG.getIntPtrConstant(i, dl));
4954 /// Custom lower build_vector of v4i32 or v4f32.
4955 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4956 const X86Subtarget *Subtarget,
4957 const TargetLowering &TLI) {
4958 // Find all zeroable elements.
4959 std::bitset<4> Zeroable;
4960 for (int i=0; i < 4; ++i) {
4961 SDValue Elt = Op->getOperand(i);
4962 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4964 assert(Zeroable.size() - Zeroable.count() > 1 &&
4965 "We expect at least two non-zero elements!");
4967 // We only know how to deal with build_vector nodes where elements are either
4968 // zeroable or extract_vector_elt with constant index.
4969 SDValue FirstNonZero;
4970 unsigned FirstNonZeroIdx;
4971 for (unsigned i=0; i < 4; ++i) {
4974 SDValue Elt = Op->getOperand(i);
4975 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4976 !isa<ConstantSDNode>(Elt.getOperand(1)))
4978 // Make sure that this node is extracting from a 128-bit vector.
4979 MVT VT = Elt.getOperand(0).getSimpleValueType();
4980 if (!VT.is128BitVector())
4982 if (!FirstNonZero.getNode()) {
4984 FirstNonZeroIdx = i;
4988 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4989 SDValue V1 = FirstNonZero.getOperand(0);
4990 MVT VT = V1.getSimpleValueType();
4992 // See if this build_vector can be lowered as a blend with zero.
4994 unsigned EltMaskIdx, EltIdx;
4996 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4997 if (Zeroable[EltIdx]) {
4998 // The zero vector will be on the right hand side.
4999 Mask[EltIdx] = EltIdx+4;
5003 Elt = Op->getOperand(EltIdx);
5004 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5005 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5006 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5008 Mask[EltIdx] = EltIdx;
5012 // Let the shuffle legalizer deal with blend operations.
5013 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5014 if (V1.getSimpleValueType() != VT)
5015 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5016 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5019 // See if we can lower this build_vector to a INSERTPS.
5020 if (!Subtarget->hasSSE41())
5023 SDValue V2 = Elt.getOperand(0);
5024 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5027 bool CanFold = true;
5028 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5032 SDValue Current = Op->getOperand(i);
5033 SDValue SrcVector = Current->getOperand(0);
5036 CanFold = SrcVector == V1 &&
5037 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5043 assert(V1.getNode() && "Expected at least two non-zero elements!");
5044 if (V1.getSimpleValueType() != MVT::v4f32)
5045 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5046 if (V2.getSimpleValueType() != MVT::v4f32)
5047 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5049 // Ok, we can emit an INSERTPS instruction.
5050 unsigned ZMask = Zeroable.to_ulong();
5052 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5053 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5055 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5056 DAG.getIntPtrConstant(InsertPSMask, DL));
5057 return DAG.getBitcast(VT, Result);
5060 /// Return a vector logical shift node.
5061 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5062 unsigned NumBits, SelectionDAG &DAG,
5063 const TargetLowering &TLI, SDLoc dl) {
5064 assert(VT.is128BitVector() && "Unknown type for VShift");
5065 MVT ShVT = MVT::v2i64;
5066 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5067 SrcOp = DAG.getBitcast(ShVT, SrcOp);
5068 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5069 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5070 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5071 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5075 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5077 // Check if the scalar load can be widened into a vector load. And if
5078 // the address is "base + cst" see if the cst can be "absorbed" into
5079 // the shuffle mask.
5080 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5081 SDValue Ptr = LD->getBasePtr();
5082 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5084 EVT PVT = LD->getValueType(0);
5085 if (PVT != MVT::i32 && PVT != MVT::f32)
5090 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5091 FI = FINode->getIndex();
5093 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5094 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5095 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5096 Offset = Ptr.getConstantOperandVal(1);
5097 Ptr = Ptr.getOperand(0);
5102 // FIXME: 256-bit vector instructions don't require a strict alignment,
5103 // improve this code to support it better.
5104 unsigned RequiredAlign = VT.getSizeInBits()/8;
5105 SDValue Chain = LD->getChain();
5106 // Make sure the stack object alignment is at least 16 or 32.
5107 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5108 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5109 if (MFI->isFixedObjectIndex(FI)) {
5110 // Can't change the alignment. FIXME: It's possible to compute
5111 // the exact stack offset and reference FI + adjust offset instead.
5112 // If someone *really* cares about this. That's the way to implement it.
5115 MFI->setObjectAlignment(FI, RequiredAlign);
5119 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5120 // Ptr + (Offset & ~15).
5123 if ((Offset % RequiredAlign) & 3)
5125 int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5128 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5129 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5132 int EltNo = (Offset - StartOffset) >> 2;
5133 unsigned NumElems = VT.getVectorNumElements();
5135 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5136 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5137 LD->getPointerInfo().getWithOffset(StartOffset),
5138 false, false, false, 0);
5140 SmallVector<int, 8> Mask(NumElems, EltNo);
5142 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5148 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5149 /// elements can be replaced by a single large load which has the same value as
5150 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5152 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5154 /// FIXME: we'd also like to handle the case where the last elements are zero
5155 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5156 /// There's even a handy isZeroNode for that purpose.
5157 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5158 SDLoc &DL, SelectionDAG &DAG,
5159 bool isAfterLegalize) {
5160 unsigned NumElems = Elts.size();
5162 LoadSDNode *LDBase = nullptr;
5163 unsigned LastLoadedElt = -1U;
5165 // For each element in the initializer, see if we've found a load or an undef.
5166 // If we don't find an initial load element, or later load elements are
5167 // non-consecutive, bail out.
5168 for (unsigned i = 0; i < NumElems; ++i) {
5169 SDValue Elt = Elts[i];
5170 // Look through a bitcast.
5171 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5172 Elt = Elt.getOperand(0);
5173 if (!Elt.getNode() ||
5174 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5177 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5179 LDBase = cast<LoadSDNode>(Elt.getNode());
5183 if (Elt.getOpcode() == ISD::UNDEF)
5186 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5187 EVT LdVT = Elt.getValueType();
5188 // Each loaded element must be the correct fractional portion of the
5189 // requested vector load.
5190 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5192 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5197 // If we have found an entire vector of loads and undefs, then return a large
5198 // load of the entire vector width starting at the base pointer. If we found
5199 // consecutive loads for the low half, generate a vzext_load node.
5200 if (LastLoadedElt == NumElems - 1) {
5201 assert(LDBase && "Did not find base load for merging consecutive loads");
5202 EVT EltVT = LDBase->getValueType(0);
5203 // Ensure that the input vector size for the merged loads matches the
5204 // cumulative size of the input elements.
5205 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5208 if (isAfterLegalize &&
5209 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5212 SDValue NewLd = SDValue();
5214 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5215 LDBase->getPointerInfo(), LDBase->isVolatile(),
5216 LDBase->isNonTemporal(), LDBase->isInvariant(),
5217 LDBase->getAlignment());
5219 if (LDBase->hasAnyUseOfValue(1)) {
5220 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5222 SDValue(NewLd.getNode(), 1));
5223 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5224 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5225 SDValue(NewLd.getNode(), 1));
5231 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5232 //of a v4i32 / v4f32. It's probably worth generalizing.
5233 EVT EltVT = VT.getVectorElementType();
5234 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5235 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5236 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5237 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5239 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5240 LDBase->getPointerInfo(),
5241 LDBase->getAlignment(),
5242 false/*isVolatile*/, true/*ReadMem*/,
5245 // Make sure the newly-created LOAD is in the same position as LDBase in
5246 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5247 // update uses of LDBase's output chain to use the TokenFactor.
5248 if (LDBase->hasAnyUseOfValue(1)) {
5249 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5250 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5251 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5252 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5253 SDValue(ResNode.getNode(), 1));
5256 return DAG.getBitcast(VT, ResNode);
5261 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5262 /// to generate a splat value for the following cases:
5263 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5264 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5265 /// a scalar load, or a constant.
5266 /// The VBROADCAST node is returned when a pattern is found,
5267 /// or SDValue() otherwise.
5268 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5269 SelectionDAG &DAG) {
5270 // VBROADCAST requires AVX.
5271 // TODO: Splats could be generated for non-AVX CPUs using SSE
5272 // instructions, but there's less potential gain for only 128-bit vectors.
5273 if (!Subtarget->hasAVX())
5276 MVT VT = Op.getSimpleValueType();
5279 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5280 "Unsupported vector type for broadcast.");
5285 switch (Op.getOpcode()) {
5287 // Unknown pattern found.
5290 case ISD::BUILD_VECTOR: {
5291 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5292 BitVector UndefElements;
5293 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5295 // We need a splat of a single value to use broadcast, and it doesn't
5296 // make any sense if the value is only in one element of the vector.
5297 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5301 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5302 Ld.getOpcode() == ISD::ConstantFP);
5304 // Make sure that all of the users of a non-constant load are from the
5305 // BUILD_VECTOR node.
5306 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5311 case ISD::VECTOR_SHUFFLE: {
5312 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5314 // Shuffles must have a splat mask where the first element is
5316 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5319 SDValue Sc = Op.getOperand(0);
5320 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5321 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5323 if (!Subtarget->hasInt256())
5326 // Use the register form of the broadcast instruction available on AVX2.
5327 if (VT.getSizeInBits() >= 256)
5328 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5329 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5332 Ld = Sc.getOperand(0);
5333 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5334 Ld.getOpcode() == ISD::ConstantFP);
5336 // The scalar_to_vector node and the suspected
5337 // load node must have exactly one user.
5338 // Constants may have multiple users.
5340 // AVX-512 has register version of the broadcast
5341 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5342 Ld.getValueType().getSizeInBits() >= 32;
5343 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5350 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5351 bool IsGE256 = (VT.getSizeInBits() >= 256);
5353 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5354 // instruction to save 8 or more bytes of constant pool data.
5355 // TODO: If multiple splats are generated to load the same constant,
5356 // it may be detrimental to overall size. There needs to be a way to detect
5357 // that condition to know if this is truly a size win.
5358 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5360 // Handle broadcasting a single constant scalar from the constant pool
5362 // On Sandybridge (no AVX2), it is still better to load a constant vector
5363 // from the constant pool and not to broadcast it from a scalar.
5364 // But override that restriction when optimizing for size.
5365 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5366 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5367 EVT CVT = Ld.getValueType();
5368 assert(!CVT.isVector() && "Must not broadcast a vector type");
5370 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5371 // For size optimization, also splat v2f64 and v2i64, and for size opt
5372 // with AVX2, also splat i8 and i16.
5373 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5374 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5375 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5376 const Constant *C = nullptr;
5377 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5378 C = CI->getConstantIntValue();
5379 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5380 C = CF->getConstantFPValue();
5382 assert(C && "Invalid constant type");
5384 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5386 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5387 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5389 CVT, dl, DAG.getEntryNode(), CP,
5390 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5391 false, false, Alignment);
5393 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5397 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5399 // Handle AVX2 in-register broadcasts.
5400 if (!IsLoad && Subtarget->hasInt256() &&
5401 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5402 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5404 // The scalar source must be a normal load.
5408 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5409 (Subtarget->hasVLX() && ScalarSize == 64))
5410 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5412 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5413 // double since there is no vbroadcastsd xmm
5414 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5415 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5416 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5419 // Unsupported broadcast.
5423 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5424 /// underlying vector and index.
5426 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5428 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5430 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5431 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5434 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5436 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5438 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5439 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5442 // In this case the vector is the extract_subvector expression and the index
5443 // is 2, as specified by the shuffle.
5444 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5445 SDValue ShuffleVec = SVOp->getOperand(0);
5446 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5447 assert(ShuffleVecVT.getVectorElementType() ==
5448 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5450 int ShuffleIdx = SVOp->getMaskElt(Idx);
5451 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5452 ExtractedFromVec = ShuffleVec;
5458 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5459 MVT VT = Op.getSimpleValueType();
5461 // Skip if insert_vec_elt is not supported.
5462 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5463 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5467 unsigned NumElems = Op.getNumOperands();
5471 SmallVector<unsigned, 4> InsertIndices;
5472 SmallVector<int, 8> Mask(NumElems, -1);
5474 for (unsigned i = 0; i != NumElems; ++i) {
5475 unsigned Opc = Op.getOperand(i).getOpcode();
5477 if (Opc == ISD::UNDEF)
5480 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5481 // Quit if more than 1 elements need inserting.
5482 if (InsertIndices.size() > 1)
5485 InsertIndices.push_back(i);
5489 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5490 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5491 // Quit if non-constant index.
5492 if (!isa<ConstantSDNode>(ExtIdx))
5494 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5496 // Quit if extracted from vector of different type.
5497 if (ExtractedFromVec.getValueType() != VT)
5500 if (!VecIn1.getNode())
5501 VecIn1 = ExtractedFromVec;
5502 else if (VecIn1 != ExtractedFromVec) {
5503 if (!VecIn2.getNode())
5504 VecIn2 = ExtractedFromVec;
5505 else if (VecIn2 != ExtractedFromVec)
5506 // Quit if more than 2 vectors to shuffle
5510 if (ExtractedFromVec == VecIn1)
5512 else if (ExtractedFromVec == VecIn2)
5513 Mask[i] = Idx + NumElems;
5516 if (!VecIn1.getNode())
5519 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5520 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5521 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5522 unsigned Idx = InsertIndices[i];
5523 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5524 DAG.getIntPtrConstant(Idx, DL));
5530 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5531 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5532 Op.getScalarValueSizeInBits() == 1 &&
5533 "Can not convert non-constant vector");
5534 uint64_t Immediate = 0;
5535 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5536 SDValue In = Op.getOperand(idx);
5537 if (In.getOpcode() != ISD::UNDEF)
5538 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5542 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5543 return DAG.getConstant(Immediate, dl, VT);
5545 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5547 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5549 MVT VT = Op.getSimpleValueType();
5550 assert((VT.getVectorElementType() == MVT::i1) &&
5551 "Unexpected type in LowerBUILD_VECTORvXi1!");
5554 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5555 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5556 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5557 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5560 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5561 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5562 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5563 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5566 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5567 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5568 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5569 return DAG.getBitcast(VT, Imm);
5570 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5571 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5572 DAG.getIntPtrConstant(0, dl));
5575 // Vector has one or more non-const elements
5576 uint64_t Immediate = 0;
5577 SmallVector<unsigned, 16> NonConstIdx;
5578 bool IsSplat = true;
5579 bool HasConstElts = false;
5581 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5582 SDValue In = Op.getOperand(idx);
5583 if (In.getOpcode() == ISD::UNDEF)
5585 if (!isa<ConstantSDNode>(In))
5586 NonConstIdx.push_back(idx);
5588 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5589 HasConstElts = true;
5593 else if (In != Op.getOperand(SplatIdx))
5597 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5599 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5600 DAG.getConstant(1, dl, VT),
5601 DAG.getConstant(0, dl, VT));
5603 // insert elements one by one
5607 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5608 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5610 else if (HasConstElts)
5611 Imm = DAG.getConstant(0, dl, VT);
5613 Imm = DAG.getUNDEF(VT);
5614 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5615 DstVec = DAG.getBitcast(VT, Imm);
5617 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5618 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5619 DAG.getIntPtrConstant(0, dl));
5622 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5623 unsigned InsertIdx = NonConstIdx[i];
5624 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5625 Op.getOperand(InsertIdx),
5626 DAG.getIntPtrConstant(InsertIdx, dl));
5631 /// \brief Return true if \p N implements a horizontal binop and return the
5632 /// operands for the horizontal binop into V0 and V1.
5634 /// This is a helper function of LowerToHorizontalOp().
5635 /// This function checks that the build_vector \p N in input implements a
5636 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5637 /// operation to match.
5638 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5639 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5640 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5643 /// This function only analyzes elements of \p N whose indices are
5644 /// in range [BaseIdx, LastIdx).
5645 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5647 unsigned BaseIdx, unsigned LastIdx,
5648 SDValue &V0, SDValue &V1) {
5649 EVT VT = N->getValueType(0);
5651 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5652 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5653 "Invalid Vector in input!");
5655 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5656 bool CanFold = true;
5657 unsigned ExpectedVExtractIdx = BaseIdx;
5658 unsigned NumElts = LastIdx - BaseIdx;
5659 V0 = DAG.getUNDEF(VT);
5660 V1 = DAG.getUNDEF(VT);
5662 // Check if N implements a horizontal binop.
5663 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5664 SDValue Op = N->getOperand(i + BaseIdx);
5667 if (Op->getOpcode() == ISD::UNDEF) {
5668 // Update the expected vector extract index.
5669 if (i * 2 == NumElts)
5670 ExpectedVExtractIdx = BaseIdx;
5671 ExpectedVExtractIdx += 2;
5675 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5680 SDValue Op0 = Op.getOperand(0);
5681 SDValue Op1 = Op.getOperand(1);
5683 // Try to match the following pattern:
5684 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5685 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5686 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5687 Op0.getOperand(0) == Op1.getOperand(0) &&
5688 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5689 isa<ConstantSDNode>(Op1.getOperand(1)));
5693 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5694 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5696 if (i * 2 < NumElts) {
5697 if (V0.getOpcode() == ISD::UNDEF) {
5698 V0 = Op0.getOperand(0);
5699 if (V0.getValueType() != VT)
5703 if (V1.getOpcode() == ISD::UNDEF) {
5704 V1 = Op0.getOperand(0);
5705 if (V1.getValueType() != VT)
5708 if (i * 2 == NumElts)
5709 ExpectedVExtractIdx = BaseIdx;
5712 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5713 if (I0 == ExpectedVExtractIdx)
5714 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5715 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5716 // Try to match the following dag sequence:
5717 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5718 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5722 ExpectedVExtractIdx += 2;
5728 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5729 /// a concat_vector.
5731 /// This is a helper function of LowerToHorizontalOp().
5732 /// This function expects two 256-bit vectors called V0 and V1.
5733 /// At first, each vector is split into two separate 128-bit vectors.
5734 /// Then, the resulting 128-bit vectors are used to implement two
5735 /// horizontal binary operations.
5737 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5739 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5740 /// the two new horizontal binop.
5741 /// When Mode is set, the first horizontal binop dag node would take as input
5742 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5743 /// horizontal binop dag node would take as input the lower 128-bit of V1
5744 /// and the upper 128-bit of V1.
5746 /// HADD V0_LO, V0_HI
5747 /// HADD V1_LO, V1_HI
5749 /// Otherwise, the first horizontal binop dag node takes as input the lower
5750 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5751 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5753 /// HADD V0_LO, V1_LO
5754 /// HADD V0_HI, V1_HI
5756 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5757 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5758 /// the upper 128-bits of the result.
5759 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5760 SDLoc DL, SelectionDAG &DAG,
5761 unsigned X86Opcode, bool Mode,
5762 bool isUndefLO, bool isUndefHI) {
5763 EVT VT = V0.getValueType();
5764 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5765 "Invalid nodes in input!");
5767 unsigned NumElts = VT.getVectorNumElements();
5768 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5769 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5770 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5771 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5772 EVT NewVT = V0_LO.getValueType();
5774 SDValue LO = DAG.getUNDEF(NewVT);
5775 SDValue HI = DAG.getUNDEF(NewVT);
5778 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5779 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5780 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5781 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5782 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5784 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5785 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5786 V1_LO->getOpcode() != ISD::UNDEF))
5787 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5789 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5790 V1_HI->getOpcode() != ISD::UNDEF))
5791 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5794 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5797 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5799 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5800 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5801 EVT VT = BV->getValueType(0);
5802 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5803 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5807 unsigned NumElts = VT.getVectorNumElements();
5808 SDValue InVec0 = DAG.getUNDEF(VT);
5809 SDValue InVec1 = DAG.getUNDEF(VT);
5811 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5812 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5814 // Odd-numbered elements in the input build vector are obtained from
5815 // adding two integer/float elements.
5816 // Even-numbered elements in the input build vector are obtained from
5817 // subtracting two integer/float elements.
5818 unsigned ExpectedOpcode = ISD::FSUB;
5819 unsigned NextExpectedOpcode = ISD::FADD;
5820 bool AddFound = false;
5821 bool SubFound = false;
5823 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5824 SDValue Op = BV->getOperand(i);
5826 // Skip 'undef' values.
5827 unsigned Opcode = Op.getOpcode();
5828 if (Opcode == ISD::UNDEF) {
5829 std::swap(ExpectedOpcode, NextExpectedOpcode);
5833 // Early exit if we found an unexpected opcode.
5834 if (Opcode != ExpectedOpcode)
5837 SDValue Op0 = Op.getOperand(0);
5838 SDValue Op1 = Op.getOperand(1);
5840 // Try to match the following pattern:
5841 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5842 // Early exit if we cannot match that sequence.
5843 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5844 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5845 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5846 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5847 Op0.getOperand(1) != Op1.getOperand(1))
5850 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5854 // We found a valid add/sub node. Update the information accordingly.
5860 // Update InVec0 and InVec1.
5861 if (InVec0.getOpcode() == ISD::UNDEF) {
5862 InVec0 = Op0.getOperand(0);
5863 if (InVec0.getValueType() != VT)
5866 if (InVec1.getOpcode() == ISD::UNDEF) {
5867 InVec1 = Op1.getOperand(0);
5868 if (InVec1.getValueType() != VT)
5872 // Make sure that operands in input to each add/sub node always
5873 // come from a same pair of vectors.
5874 if (InVec0 != Op0.getOperand(0)) {
5875 if (ExpectedOpcode == ISD::FSUB)
5878 // FADD is commutable. Try to commute the operands
5879 // and then test again.
5880 std::swap(Op0, Op1);
5881 if (InVec0 != Op0.getOperand(0))
5885 if (InVec1 != Op1.getOperand(0))
5888 // Update the pair of expected opcodes.
5889 std::swap(ExpectedOpcode, NextExpectedOpcode);
5892 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5893 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5894 InVec1.getOpcode() != ISD::UNDEF)
5895 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5900 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5901 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5902 const X86Subtarget *Subtarget,
5903 SelectionDAG &DAG) {
5904 EVT VT = BV->getValueType(0);
5905 unsigned NumElts = VT.getVectorNumElements();
5906 unsigned NumUndefsLO = 0;
5907 unsigned NumUndefsHI = 0;
5908 unsigned Half = NumElts/2;
5910 // Count the number of UNDEF operands in the build_vector in input.
5911 for (unsigned i = 0, e = Half; i != e; ++i)
5912 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5915 for (unsigned i = Half, e = NumElts; i != e; ++i)
5916 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5919 // Early exit if this is either a build_vector of all UNDEFs or all the
5920 // operands but one are UNDEF.
5921 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5925 SDValue InVec0, InVec1;
5926 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5927 // Try to match an SSE3 float HADD/HSUB.
5928 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5929 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5931 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5932 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5933 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5934 // Try to match an SSSE3 integer HADD/HSUB.
5935 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5936 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5938 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5939 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5942 if (!Subtarget->hasAVX())
5945 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5946 // Try to match an AVX horizontal add/sub of packed single/double
5947 // precision floating point values from 256-bit vectors.
5948 SDValue InVec2, InVec3;
5949 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5950 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5951 ((InVec0.getOpcode() == ISD::UNDEF ||
5952 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5953 ((InVec1.getOpcode() == ISD::UNDEF ||
5954 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5955 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5957 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5958 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5959 ((InVec0.getOpcode() == ISD::UNDEF ||
5960 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5961 ((InVec1.getOpcode() == ISD::UNDEF ||
5962 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5963 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5964 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5965 // Try to match an AVX2 horizontal add/sub of signed integers.
5966 SDValue InVec2, InVec3;
5968 bool CanFold = true;
5970 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5971 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5972 ((InVec0.getOpcode() == ISD::UNDEF ||
5973 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5974 ((InVec1.getOpcode() == ISD::UNDEF ||
5975 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5976 X86Opcode = X86ISD::HADD;
5977 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5978 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5979 ((InVec0.getOpcode() == ISD::UNDEF ||
5980 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5981 ((InVec1.getOpcode() == ISD::UNDEF ||
5982 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5983 X86Opcode = X86ISD::HSUB;
5988 // Fold this build_vector into a single horizontal add/sub.
5989 // Do this only if the target has AVX2.
5990 if (Subtarget->hasAVX2())
5991 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5993 // Do not try to expand this build_vector into a pair of horizontal
5994 // add/sub if we can emit a pair of scalar add/sub.
5995 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5998 // Convert this build_vector into a pair of horizontal binop followed by
6000 bool isUndefLO = NumUndefsLO == Half;
6001 bool isUndefHI = NumUndefsHI == Half;
6002 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6003 isUndefLO, isUndefHI);
6007 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6008 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6010 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6011 X86Opcode = X86ISD::HADD;
6012 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6013 X86Opcode = X86ISD::HSUB;
6014 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6015 X86Opcode = X86ISD::FHADD;
6016 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6017 X86Opcode = X86ISD::FHSUB;
6021 // Don't try to expand this build_vector into a pair of horizontal add/sub
6022 // if we can simply emit a pair of scalar add/sub.
6023 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6026 // Convert this build_vector into two horizontal add/sub followed by
6028 bool isUndefLO = NumUndefsLO == Half;
6029 bool isUndefHI = NumUndefsHI == Half;
6030 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6031 isUndefLO, isUndefHI);
6038 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6041 MVT VT = Op.getSimpleValueType();
6042 MVT ExtVT = VT.getVectorElementType();
6043 unsigned NumElems = Op.getNumOperands();
6045 // Generate vectors for predicate vectors.
6046 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6047 return LowerBUILD_VECTORvXi1(Op, DAG);
6049 // Vectors containing all zeros can be matched by pxor and xorps later
6050 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6051 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6052 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6053 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6056 return getZeroVector(VT, Subtarget, DAG, dl);
6059 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6060 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6061 // vpcmpeqd on 256-bit vectors.
6062 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6063 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6066 if (!VT.is512BitVector())
6067 return getOnesVector(VT, Subtarget, DAG, dl);
6070 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6071 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6073 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6074 return HorizontalOp;
6075 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6078 unsigned EVTBits = ExtVT.getSizeInBits();
6080 unsigned NumZero = 0;
6081 unsigned NumNonZero = 0;
6082 unsigned NonZeros = 0;
6083 bool IsAllConstants = true;
6084 SmallSet<SDValue, 8> Values;
6085 for (unsigned i = 0; i < NumElems; ++i) {
6086 SDValue Elt = Op.getOperand(i);
6087 if (Elt.getOpcode() == ISD::UNDEF)
6090 if (Elt.getOpcode() != ISD::Constant &&
6091 Elt.getOpcode() != ISD::ConstantFP)
6092 IsAllConstants = false;
6093 if (X86::isZeroNode(Elt))
6096 NonZeros |= (1 << i);
6101 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6102 if (NumNonZero == 0)
6103 return DAG.getUNDEF(VT);
6105 // Special case for single non-zero, non-undef, element.
6106 if (NumNonZero == 1) {
6107 unsigned Idx = countTrailingZeros(NonZeros);
6108 SDValue Item = Op.getOperand(Idx);
6110 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6111 // the value are obviously zero, truncate the value to i32 and do the
6112 // insertion that way. Only do this if the value is non-constant or if the
6113 // value is a constant being inserted into element 0. It is cheaper to do
6114 // a constant pool load than it is to do a movd + shuffle.
6115 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6116 (!IsAllConstants || Idx == 0)) {
6117 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6119 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6120 EVT VecVT = MVT::v4i32;
6122 // Truncate the value (which may itself be a constant) to i32, and
6123 // convert it to a vector with movd (S2V+shuffle to zero extend).
6124 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6125 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6126 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6127 Item, Idx * 2, true, Subtarget, DAG));
6131 // If we have a constant or non-constant insertion into the low element of
6132 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6133 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6134 // depending on what the source datatype is.
6137 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6139 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6140 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6141 if (VT.is512BitVector()) {
6142 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6143 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6144 Item, DAG.getIntPtrConstant(0, dl));
6146 assert((VT.is128BitVector() || VT.is256BitVector()) &&
6147 "Expected an SSE value type!");
6148 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6149 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6150 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6153 // We can't directly insert an i8 or i16 into a vector, so zero extend
6155 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6156 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6157 if (VT.is256BitVector()) {
6158 if (Subtarget->hasAVX()) {
6159 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6160 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6162 // Without AVX, we need to extend to a 128-bit vector and then
6163 // insert into the 256-bit vector.
6164 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6165 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6166 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6169 assert(VT.is128BitVector() && "Expected an SSE value type!");
6170 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6171 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6173 return DAG.getBitcast(VT, Item);
6177 // Is it a vector logical left shift?
6178 if (NumElems == 2 && Idx == 1 &&
6179 X86::isZeroNode(Op.getOperand(0)) &&
6180 !X86::isZeroNode(Op.getOperand(1))) {
6181 unsigned NumBits = VT.getSizeInBits();
6182 return getVShift(true, VT,
6183 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6184 VT, Op.getOperand(1)),
6185 NumBits/2, DAG, *this, dl);
6188 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6191 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6192 // is a non-constant being inserted into an element other than the low one,
6193 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6194 // movd/movss) to move this into the low element, then shuffle it into
6196 if (EVTBits == 32) {
6197 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6198 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6202 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6203 if (Values.size() == 1) {
6204 if (EVTBits == 32) {
6205 // Instead of a shuffle like this:
6206 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6207 // Check if it's possible to issue this instead.
6208 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6209 unsigned Idx = countTrailingZeros(NonZeros);
6210 SDValue Item = Op.getOperand(Idx);
6211 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6212 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6217 // A vector full of immediates; various special cases are already
6218 // handled, so this is best done with a single constant-pool load.
6222 // For AVX-length vectors, see if we can use a vector load to get all of the
6223 // elements, otherwise build the individual 128-bit pieces and use
6224 // shuffles to put them in place.
6225 if (VT.is256BitVector() || VT.is512BitVector()) {
6226 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6228 // Check for a build vector of consecutive loads.
6229 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6232 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6234 // Build both the lower and upper subvector.
6235 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6236 makeArrayRef(&V[0], NumElems/2));
6237 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6238 makeArrayRef(&V[NumElems / 2], NumElems/2));
6240 // Recreate the wider vector with the lower and upper part.
6241 if (VT.is256BitVector())
6242 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6243 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6246 // Let legalizer expand 2-wide build_vectors.
6247 if (EVTBits == 64) {
6248 if (NumNonZero == 1) {
6249 // One half is zero or undef.
6250 unsigned Idx = countTrailingZeros(NonZeros);
6251 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6252 Op.getOperand(Idx));
6253 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6258 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6259 if (EVTBits == 8 && NumElems == 16)
6260 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6264 if (EVTBits == 16 && NumElems == 8)
6265 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6269 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6270 if (EVTBits == 32 && NumElems == 4)
6271 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6274 // If element VT is == 32 bits, turn it into a number of shuffles.
6275 SmallVector<SDValue, 8> V(NumElems);
6276 if (NumElems == 4 && NumZero > 0) {
6277 for (unsigned i = 0; i < 4; ++i) {
6278 bool isZero = !(NonZeros & (1 << i));
6280 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6282 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6285 for (unsigned i = 0; i < 2; ++i) {
6286 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6289 V[i] = V[i*2]; // Must be a zero vector.
6292 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6295 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6298 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6303 bool Reverse1 = (NonZeros & 0x3) == 2;
6304 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6308 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6309 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6311 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6314 if (Values.size() > 1 && VT.is128BitVector()) {
6315 // Check for a build vector of consecutive loads.
6316 for (unsigned i = 0; i < NumElems; ++i)
6317 V[i] = Op.getOperand(i);
6319 // Check for elements which are consecutive loads.
6320 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6323 // Check for a build vector from mostly shuffle plus few inserting.
6324 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6327 // For SSE 4.1, use insertps to put the high elements into the low element.
6328 if (Subtarget->hasSSE41()) {
6330 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6331 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6333 Result = DAG.getUNDEF(VT);
6335 for (unsigned i = 1; i < NumElems; ++i) {
6336 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6337 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6338 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6343 // Otherwise, expand into a number of unpckl*, start by extending each of
6344 // our (non-undef) elements to the full vector width with the element in the
6345 // bottom slot of the vector (which generates no code for SSE).
6346 for (unsigned i = 0; i < NumElems; ++i) {
6347 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6348 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6350 V[i] = DAG.getUNDEF(VT);
6353 // Next, we iteratively mix elements, e.g. for v4f32:
6354 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6355 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6356 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6357 unsigned EltStride = NumElems >> 1;
6358 while (EltStride != 0) {
6359 for (unsigned i = 0; i < EltStride; ++i) {
6360 // If V[i+EltStride] is undef and this is the first round of mixing,
6361 // then it is safe to just drop this shuffle: V[i] is already in the
6362 // right place, the one element (since it's the first round) being
6363 // inserted as undef can be dropped. This isn't safe for successive
6364 // rounds because they will permute elements within both vectors.
6365 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6366 EltStride == NumElems/2)
6369 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6378 // 256-bit AVX can use the vinsertf128 instruction
6379 // to create 256-bit vectors from two other 128-bit ones.
6380 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6382 MVT ResVT = Op.getSimpleValueType();
6384 assert((ResVT.is256BitVector() ||
6385 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6387 SDValue V1 = Op.getOperand(0);
6388 SDValue V2 = Op.getOperand(1);
6389 unsigned NumElems = ResVT.getVectorNumElements();
6390 if (ResVT.is256BitVector())
6391 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6393 if (Op.getNumOperands() == 4) {
6394 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6395 ResVT.getVectorNumElements()/2);
6396 SDValue V3 = Op.getOperand(2);
6397 SDValue V4 = Op.getOperand(3);
6398 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6399 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6401 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6404 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6405 const X86Subtarget *Subtarget,
6406 SelectionDAG & DAG) {
6408 MVT ResVT = Op.getSimpleValueType();
6409 unsigned NumOfOperands = Op.getNumOperands();
6411 assert(isPowerOf2_32(NumOfOperands) &&
6412 "Unexpected number of operands in CONCAT_VECTORS");
6414 if (NumOfOperands > 2) {
6415 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6416 ResVT.getVectorNumElements()/2);
6417 SmallVector<SDValue, 2> Ops;
6418 for (unsigned i = 0; i < NumOfOperands/2; i++)
6419 Ops.push_back(Op.getOperand(i));
6420 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6422 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6423 Ops.push_back(Op.getOperand(i));
6424 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6425 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6428 SDValue V1 = Op.getOperand(0);
6429 SDValue V2 = Op.getOperand(1);
6430 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6431 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6433 if (IsZeroV1 && IsZeroV2)
6434 return getZeroVector(ResVT, Subtarget, DAG, dl);
6436 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6437 SDValue Undef = DAG.getUNDEF(ResVT);
6438 unsigned NumElems = ResVT.getVectorNumElements();
6439 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6441 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6442 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6446 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6447 // Zero the upper bits of V1
6448 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6449 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6452 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6455 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6456 const X86Subtarget *Subtarget,
6457 SelectionDAG &DAG) {
6458 MVT VT = Op.getSimpleValueType();
6459 if (VT.getVectorElementType() == MVT::i1)
6460 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6462 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6463 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6464 Op.getNumOperands() == 4)));
6466 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6467 // from two other 128-bit ones.
6469 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6470 return LowerAVXCONCAT_VECTORS(Op, DAG);
6473 //===----------------------------------------------------------------------===//
6474 // Vector shuffle lowering
6476 // This is an experimental code path for lowering vector shuffles on x86. It is
6477 // designed to handle arbitrary vector shuffles and blends, gracefully
6478 // degrading performance as necessary. It works hard to recognize idiomatic
6479 // shuffles and lower them to optimal instruction patterns without leaving
6480 // a framework that allows reasonably efficient handling of all vector shuffle
6482 //===----------------------------------------------------------------------===//
6484 /// \brief Tiny helper function to identify a no-op mask.
6486 /// This is a somewhat boring predicate function. It checks whether the mask
6487 /// array input, which is assumed to be a single-input shuffle mask of the kind
6488 /// used by the X86 shuffle instructions (not a fully general
6489 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6490 /// in-place shuffle are 'no-op's.
6491 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6492 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6493 if (Mask[i] != -1 && Mask[i] != i)
6498 /// \brief Helper function to classify a mask as a single-input mask.
6500 /// This isn't a generic single-input test because in the vector shuffle
6501 /// lowering we canonicalize single inputs to be the first input operand. This
6502 /// means we can more quickly test for a single input by only checking whether
6503 /// an input from the second operand exists. We also assume that the size of
6504 /// mask corresponds to the size of the input vectors which isn't true in the
6505 /// fully general case.
6506 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6508 if (M >= (int)Mask.size())
6513 /// \brief Test whether there are elements crossing 128-bit lanes in this
6516 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6517 /// and we routinely test for these.
6518 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6519 int LaneSize = 128 / VT.getScalarSizeInBits();
6520 int Size = Mask.size();
6521 for (int i = 0; i < Size; ++i)
6522 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6527 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6529 /// This checks a shuffle mask to see if it is performing the same
6530 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6531 /// that it is also not lane-crossing. It may however involve a blend from the
6532 /// same lane of a second vector.
6534 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6535 /// non-trivial to compute in the face of undef lanes. The representation is
6536 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6537 /// entries from both V1 and V2 inputs to the wider mask.
6539 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6540 SmallVectorImpl<int> &RepeatedMask) {
6541 int LaneSize = 128 / VT.getScalarSizeInBits();
6542 RepeatedMask.resize(LaneSize, -1);
6543 int Size = Mask.size();
6544 for (int i = 0; i < Size; ++i) {
6547 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6548 // This entry crosses lanes, so there is no way to model this shuffle.
6551 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6552 if (RepeatedMask[i % LaneSize] == -1)
6553 // This is the first non-undef entry in this slot of a 128-bit lane.
6554 RepeatedMask[i % LaneSize] =
6555 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6556 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6557 // Found a mismatch with the repeated mask.
6563 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6566 /// This is a fast way to test a shuffle mask against a fixed pattern:
6568 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6570 /// It returns true if the mask is exactly as wide as the argument list, and
6571 /// each element of the mask is either -1 (signifying undef) or the value given
6572 /// in the argument.
6573 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6574 ArrayRef<int> ExpectedMask) {
6575 if (Mask.size() != ExpectedMask.size())
6578 int Size = Mask.size();
6580 // If the values are build vectors, we can look through them to find
6581 // equivalent inputs that make the shuffles equivalent.
6582 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6583 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6585 for (int i = 0; i < Size; ++i)
6586 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6587 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6588 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6589 if (!MaskBV || !ExpectedBV ||
6590 MaskBV->getOperand(Mask[i] % Size) !=
6591 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6598 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6600 /// This helper function produces an 8-bit shuffle immediate corresponding to
6601 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6602 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6605 /// NB: We rely heavily on "undef" masks preserving the input lane.
6606 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6607 SelectionDAG &DAG) {
6608 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6609 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6610 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6611 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6612 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6615 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6616 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6617 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6618 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6619 return DAG.getConstant(Imm, DL, MVT::i8);
6622 /// \brief Compute whether each element of a shuffle is zeroable.
6624 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6625 /// Either it is an undef element in the shuffle mask, the element of the input
6626 /// referenced is undef, or the element of the input referenced is known to be
6627 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6628 /// as many lanes with this technique as possible to simplify the remaining
6630 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6631 SDValue V1, SDValue V2) {
6632 SmallBitVector Zeroable(Mask.size(), false);
6634 while (V1.getOpcode() == ISD::BITCAST)
6635 V1 = V1->getOperand(0);
6636 while (V2.getOpcode() == ISD::BITCAST)
6637 V2 = V2->getOperand(0);
6639 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6640 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6642 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6644 // Handle the easy cases.
6645 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6650 // If this is an index into a build_vector node (which has the same number
6651 // of elements), dig out the input value and use it.
6652 SDValue V = M < Size ? V1 : V2;
6653 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6656 SDValue Input = V.getOperand(M % Size);
6657 // The UNDEF opcode check really should be dead code here, but not quite
6658 // worth asserting on (it isn't invalid, just unexpected).
6659 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6666 // X86 has dedicated unpack instructions that can handle specific blend
6667 // operations: UNPCKH and UNPCKL.
6668 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6669 SDValue V1, SDValue V2,
6670 SelectionDAG &DAG) {
6671 int NumElts = VT.getVectorNumElements();
6674 bool UnpcklSwapped = true;
6675 bool UnpckhSwapped = true;
6676 int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6678 for (int i = 0; i < NumElts; ++i) {
6679 unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6681 int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6682 int HiPos = LoPos + NumEltsInLane / 2;
6683 int LoPosSwapped = (LoPos + NumElts) % (NumElts * 2);
6684 int HiPosSwapped = (HiPos + NumElts) % (NumElts * 2);
6688 if (Mask[i] != LoPos)
6690 if (Mask[i] != HiPos)
6692 if (Mask[i] != LoPosSwapped)
6693 UnpcklSwapped = false;
6694 if (Mask[i] != HiPosSwapped)
6695 UnpckhSwapped = false;
6696 if (!Unpckl && !Unpckh && !UnpcklSwapped && !UnpckhSwapped)
6700 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6702 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6704 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6706 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6708 llvm_unreachable("Unexpected result of UNPCK mask analysis");
6712 /// \brief Try to emit a bitmask instruction for a shuffle.
6714 /// This handles cases where we can model a blend exactly as a bitmask due to
6715 /// one of the inputs being zeroable.
6716 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6717 SDValue V2, ArrayRef<int> Mask,
6718 SelectionDAG &DAG) {
6719 MVT EltVT = VT.getScalarType();
6720 int NumEltBits = EltVT.getSizeInBits();
6721 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6722 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6723 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6725 if (EltVT.isFloatingPoint()) {
6726 Zero = DAG.getBitcast(EltVT, Zero);
6727 AllOnes = DAG.getBitcast(EltVT, AllOnes);
6729 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6730 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6732 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6735 if (Mask[i] % Size != i)
6736 return SDValue(); // Not a blend.
6738 V = Mask[i] < Size ? V1 : V2;
6739 else if (V != (Mask[i] < Size ? V1 : V2))
6740 return SDValue(); // Can only let one input through the mask.
6742 VMaskOps[i] = AllOnes;
6745 return SDValue(); // No non-zeroable elements!
6747 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6748 V = DAG.getNode(VT.isFloatingPoint()
6749 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6754 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6756 /// This is used as a fallback approach when first class blend instructions are
6757 /// unavailable. Currently it is only suitable for integer vectors, but could
6758 /// be generalized for floating point vectors if desirable.
6759 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6760 SDValue V2, ArrayRef<int> Mask,
6761 SelectionDAG &DAG) {
6762 assert(VT.isInteger() && "Only supports integer vector types!");
6763 MVT EltVT = VT.getScalarType();
6764 int NumEltBits = EltVT.getSizeInBits();
6765 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6766 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6768 SmallVector<SDValue, 16> MaskOps;
6769 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6770 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6771 return SDValue(); // Shuffled input!
6772 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6775 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6776 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6777 // We have to cast V2 around.
6778 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6779 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6780 DAG.getBitcast(MaskVT, V1Mask),
6781 DAG.getBitcast(MaskVT, V2)));
6782 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6785 /// \brief Try to emit a blend instruction for a shuffle.
6787 /// This doesn't do any checks for the availability of instructions for blending
6788 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6789 /// be matched in the backend with the type given. What it does check for is
6790 /// that the shuffle mask is in fact a blend.
6791 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6792 SDValue V2, ArrayRef<int> Mask,
6793 const X86Subtarget *Subtarget,
6794 SelectionDAG &DAG) {
6795 unsigned BlendMask = 0;
6796 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6797 if (Mask[i] >= Size) {
6798 if (Mask[i] != i + Size)
6799 return SDValue(); // Shuffled V2 input!
6800 BlendMask |= 1u << i;
6803 if (Mask[i] >= 0 && Mask[i] != i)
6804 return SDValue(); // Shuffled V1 input!
6806 switch (VT.SimpleTy) {
6811 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6812 DAG.getConstant(BlendMask, DL, MVT::i8));
6816 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6820 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6821 // that instruction.
6822 if (Subtarget->hasAVX2()) {
6823 // Scale the blend by the number of 32-bit dwords per element.
6824 int Scale = VT.getScalarSizeInBits() / 32;
6826 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6827 if (Mask[i] >= Size)
6828 for (int j = 0; j < Scale; ++j)
6829 BlendMask |= 1u << (i * Scale + j);
6831 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6832 V1 = DAG.getBitcast(BlendVT, V1);
6833 V2 = DAG.getBitcast(BlendVT, V2);
6834 return DAG.getBitcast(
6835 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6836 DAG.getConstant(BlendMask, DL, MVT::i8)));
6840 // For integer shuffles we need to expand the mask and cast the inputs to
6841 // v8i16s prior to blending.
6842 int Scale = 8 / VT.getVectorNumElements();
6844 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6845 if (Mask[i] >= Size)
6846 for (int j = 0; j < Scale; ++j)
6847 BlendMask |= 1u << (i * Scale + j);
6849 V1 = DAG.getBitcast(MVT::v8i16, V1);
6850 V2 = DAG.getBitcast(MVT::v8i16, V2);
6851 return DAG.getBitcast(VT,
6852 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6853 DAG.getConstant(BlendMask, DL, MVT::i8)));
6857 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6858 SmallVector<int, 8> RepeatedMask;
6859 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6860 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6861 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6863 for (int i = 0; i < 8; ++i)
6864 if (RepeatedMask[i] >= 16)
6865 BlendMask |= 1u << i;
6866 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6867 DAG.getConstant(BlendMask, DL, MVT::i8));
6873 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6874 "256-bit byte-blends require AVX2 support!");
6876 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6877 if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6880 // Scale the blend by the number of bytes per element.
6881 int Scale = VT.getScalarSizeInBits() / 8;
6883 // This form of blend is always done on bytes. Compute the byte vector
6885 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6887 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6888 // mix of LLVM's code generator and the x86 backend. We tell the code
6889 // generator that boolean values in the elements of an x86 vector register
6890 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6891 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6892 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6893 // of the element (the remaining are ignored) and 0 in that high bit would
6894 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6895 // the LLVM model for boolean values in vector elements gets the relevant
6896 // bit set, it is set backwards and over constrained relative to x86's
6898 SmallVector<SDValue, 32> VSELECTMask;
6899 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6900 for (int j = 0; j < Scale; ++j)
6901 VSELECTMask.push_back(
6902 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6903 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6906 V1 = DAG.getBitcast(BlendVT, V1);
6907 V2 = DAG.getBitcast(BlendVT, V2);
6908 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6909 DAG.getNode(ISD::BUILD_VECTOR, DL,
6910 BlendVT, VSELECTMask),
6915 llvm_unreachable("Not a supported integer vector type!");
6919 /// \brief Try to lower as a blend of elements from two inputs followed by
6920 /// a single-input permutation.
6922 /// This matches the pattern where we can blend elements from two inputs and
6923 /// then reduce the shuffle to a single-input permutation.
6924 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6927 SelectionDAG &DAG) {
6928 // We build up the blend mask while checking whether a blend is a viable way
6929 // to reduce the shuffle.
6930 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6931 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6933 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6937 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6939 if (BlendMask[Mask[i] % Size] == -1)
6940 BlendMask[Mask[i] % Size] = Mask[i];
6941 else if (BlendMask[Mask[i] % Size] != Mask[i])
6942 return SDValue(); // Can't blend in the needed input!
6944 PermuteMask[i] = Mask[i] % Size;
6947 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6948 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6951 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6952 /// blends and permutes.
6954 /// This matches the extremely common pattern for handling combined
6955 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6956 /// operations. It will try to pick the best arrangement of shuffles and
6958 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6962 SelectionDAG &DAG) {
6963 // Shuffle the input elements into the desired positions in V1 and V2 and
6964 // blend them together.
6965 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6966 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6967 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6968 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6969 if (Mask[i] >= 0 && Mask[i] < Size) {
6970 V1Mask[i] = Mask[i];
6972 } else if (Mask[i] >= Size) {
6973 V2Mask[i] = Mask[i] - Size;
6974 BlendMask[i] = i + Size;
6977 // Try to lower with the simpler initial blend strategy unless one of the
6978 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6979 // shuffle may be able to fold with a load or other benefit. However, when
6980 // we'll have to do 2x as many shuffles in order to achieve this, blending
6981 // first is a better strategy.
6982 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6983 if (SDValue BlendPerm =
6984 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6987 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6988 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6989 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6992 /// \brief Try to lower a vector shuffle as a byte rotation.
6994 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6995 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6996 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6997 /// try to generically lower a vector shuffle through such an pattern. It
6998 /// does not check for the profitability of lowering either as PALIGNR or
6999 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7000 /// This matches shuffle vectors that look like:
7002 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7004 /// Essentially it concatenates V1 and V2, shifts right by some number of
7005 /// elements, and takes the low elements as the result. Note that while this is
7006 /// specified as a *right shift* because x86 is little-endian, it is a *left
7007 /// rotate* of the vector lanes.
7008 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7011 const X86Subtarget *Subtarget,
7012 SelectionDAG &DAG) {
7013 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7015 int NumElts = Mask.size();
7016 int NumLanes = VT.getSizeInBits() / 128;
7017 int NumLaneElts = NumElts / NumLanes;
7019 // We need to detect various ways of spelling a rotation:
7020 // [11, 12, 13, 14, 15, 0, 1, 2]
7021 // [-1, 12, 13, 14, -1, -1, 1, -1]
7022 // [-1, -1, -1, -1, -1, -1, 1, 2]
7023 // [ 3, 4, 5, 6, 7, 8, 9, 10]
7024 // [-1, 4, 5, 6, -1, -1, 9, -1]
7025 // [-1, 4, 5, 6, -1, -1, -1, -1]
7028 for (int l = 0; l < NumElts; l += NumLaneElts) {
7029 for (int i = 0; i < NumLaneElts; ++i) {
7030 if (Mask[l + i] == -1)
7032 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7034 // Get the mod-Size index and lane correct it.
7035 int LaneIdx = (Mask[l + i] % NumElts) - l;
7036 // Make sure it was in this lane.
7037 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7040 // Determine where a rotated vector would have started.
7041 int StartIdx = i - LaneIdx;
7043 // The identity rotation isn't interesting, stop.
7046 // If we found the tail of a vector the rotation must be the missing
7047 // front. If we found the head of a vector, it must be how much of the
7049 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7052 Rotation = CandidateRotation;
7053 else if (Rotation != CandidateRotation)
7054 // The rotations don't match, so we can't match this mask.
7057 // Compute which value this mask is pointing at.
7058 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7060 // Compute which of the two target values this index should be assigned
7061 // to. This reflects whether the high elements are remaining or the low
7062 // elements are remaining.
7063 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7065 // Either set up this value if we've not encountered it before, or check
7066 // that it remains consistent.
7069 else if (TargetV != MaskV)
7070 // This may be a rotation, but it pulls from the inputs in some
7071 // unsupported interleaving.
7076 // Check that we successfully analyzed the mask, and normalize the results.
7077 assert(Rotation != 0 && "Failed to locate a viable rotation!");
7078 assert((Lo || Hi) && "Failed to find a rotated input vector!");
7084 // The actual rotate instruction rotates bytes, so we need to scale the
7085 // rotation based on how many bytes are in the vector lane.
7086 int Scale = 16 / NumLaneElts;
7088 // SSSE3 targets can use the palignr instruction.
7089 if (Subtarget->hasSSSE3()) {
7090 // Cast the inputs to i8 vector of correct length to match PALIGNR.
7091 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7092 Lo = DAG.getBitcast(AlignVT, Lo);
7093 Hi = DAG.getBitcast(AlignVT, Hi);
7095 return DAG.getBitcast(
7096 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7097 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7100 assert(VT.getSizeInBits() == 128 &&
7101 "Rotate-based lowering only supports 128-bit lowering!");
7102 assert(Mask.size() <= 16 &&
7103 "Can shuffle at most 16 bytes in a 128-bit vector!");
7105 // Default SSE2 implementation
7106 int LoByteShift = 16 - Rotation * Scale;
7107 int HiByteShift = Rotation * Scale;
7109 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7110 Lo = DAG.getBitcast(MVT::v2i64, Lo);
7111 Hi = DAG.getBitcast(MVT::v2i64, Hi);
7113 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7114 DAG.getConstant(LoByteShift, DL, MVT::i8));
7115 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7116 DAG.getConstant(HiByteShift, DL, MVT::i8));
7117 return DAG.getBitcast(VT,
7118 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7121 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7123 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7124 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7125 /// matches elements from one of the input vectors shuffled to the left or
7126 /// right with zeroable elements 'shifted in'. It handles both the strictly
7127 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7130 /// PSHL : (little-endian) left bit shift.
7131 /// [ zz, 0, zz, 2 ]
7132 /// [ -1, 4, zz, -1 ]
7133 /// PSRL : (little-endian) right bit shift.
7135 /// [ -1, -1, 7, zz]
7136 /// PSLLDQ : (little-endian) left byte shift
7137 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
7138 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
7139 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
7140 /// PSRLDQ : (little-endian) right byte shift
7141 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
7142 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
7143 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
7144 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7145 SDValue V2, ArrayRef<int> Mask,
7146 SelectionDAG &DAG) {
7147 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7149 int Size = Mask.size();
7150 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7152 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7153 for (int i = 0; i < Size; i += Scale)
7154 for (int j = 0; j < Shift; ++j)
7155 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7161 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7162 for (int i = 0; i != Size; i += Scale) {
7163 unsigned Pos = Left ? i + Shift : i;
7164 unsigned Low = Left ? i : i + Shift;
7165 unsigned Len = Scale - Shift;
7166 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7167 Low + (V == V1 ? 0 : Size)))
7171 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7172 bool ByteShift = ShiftEltBits > 64;
7173 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7174 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7175 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7177 // Normalize the scale for byte shifts to still produce an i64 element
7179 Scale = ByteShift ? Scale / 2 : Scale;
7181 // We need to round trip through the appropriate type for the shift.
7182 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7183 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7184 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7185 "Illegal integer vector type");
7186 V = DAG.getBitcast(ShiftVT, V);
7188 V = DAG.getNode(OpCode, DL, ShiftVT, V,
7189 DAG.getConstant(ShiftAmt, DL, MVT::i8));
7190 return DAG.getBitcast(VT, V);
7193 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7194 // keep doubling the size of the integer elements up to that. We can
7195 // then shift the elements of the integer vector by whole multiples of
7196 // their width within the elements of the larger integer vector. Test each
7197 // multiple to see if we can find a match with the moved element indices
7198 // and that the shifted in elements are all zeroable.
7199 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7200 for (int Shift = 1; Shift != Scale; ++Shift)
7201 for (bool Left : {true, false})
7202 if (CheckZeros(Shift, Scale, Left))
7203 for (SDValue V : {V1, V2})
7204 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7211 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7212 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7213 SDValue V2, ArrayRef<int> Mask,
7214 SelectionDAG &DAG) {
7215 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7216 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7218 int Size = Mask.size();
7219 int HalfSize = Size / 2;
7220 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7222 // Upper half must be undefined.
7223 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7226 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7227 // Remainder of lower half result is zero and upper half is all undef.
7228 auto LowerAsEXTRQ = [&]() {
7229 // Determine the extraction length from the part of the
7230 // lower half that isn't zeroable.
7232 for (; Len >= 0; --Len)
7233 if (!Zeroable[Len - 1])
7235 assert(Len > 0 && "Zeroable shuffle mask");
7237 // Attempt to match first Len sequential elements from the lower half.
7240 for (int i = 0; i != Len; ++i) {
7244 SDValue &V = (M < Size ? V1 : V2);
7247 // All mask elements must be in the lower half.
7251 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7262 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7263 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7264 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7265 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7266 DAG.getConstant(BitLen, DL, MVT::i8),
7267 DAG.getConstant(BitIdx, DL, MVT::i8));
7270 if (SDValue ExtrQ = LowerAsEXTRQ())
7273 // INSERTQ: Extract lowest Len elements from lower half of second source and
7274 // insert over first source, starting at Idx.
7275 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7276 auto LowerAsInsertQ = [&]() {
7277 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7280 // Attempt to match first source from mask before insertion point.
7281 if (isUndefInRange(Mask, 0, Idx)) {
7283 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7285 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7291 // Extend the extraction length looking to match both the insertion of
7292 // the second source and the remaining elements of the first.
7293 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7298 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7300 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7306 // Match the remaining elements of the lower half.
7307 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7309 } else if ((!Base || (Base == V1)) &&
7310 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7312 } else if ((!Base || (Base == V2)) &&
7313 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7320 // We may not have a base (first source) - this can safely be undefined.
7322 Base = DAG.getUNDEF(VT);
7324 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7325 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7326 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7327 DAG.getConstant(BitLen, DL, MVT::i8),
7328 DAG.getConstant(BitIdx, DL, MVT::i8));
7335 if (SDValue InsertQ = LowerAsInsertQ())
7341 /// \brief Lower a vector shuffle as a zero or any extension.
7343 /// Given a specific number of elements, element bit width, and extension
7344 /// stride, produce either a zero or any extension based on the available
7345 /// features of the subtarget. The extended elements are consecutive and
7346 /// begin and can start from an offseted element index in the input; to
7347 /// avoid excess shuffling the offset must either being in the bottom lane
7348 /// or at the start of a higher lane. All extended elements must be from
7350 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7351 SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7352 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7353 assert(Scale > 1 && "Need a scale to extend.");
7354 int EltBits = VT.getScalarSizeInBits();
7355 int NumElements = VT.getVectorNumElements();
7356 int NumEltsPerLane = 128 / EltBits;
7357 int OffsetLane = Offset / NumEltsPerLane;
7358 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7359 "Only 8, 16, and 32 bit elements can be extended.");
7360 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7361 assert(0 <= Offset && "Extension offset must be positive.");
7362 assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7363 "Extension offset must be in the first lane or start an upper lane.");
7365 // Check that an index is in same lane as the base offset.
7366 auto SafeOffset = [&](int Idx) {
7367 return OffsetLane == (Idx / NumEltsPerLane);
7370 // Shift along an input so that the offset base moves to the first element.
7371 auto ShuffleOffset = [&](SDValue V) {
7375 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7376 for (int i = 0; i * Scale < NumElements; ++i) {
7377 int SrcIdx = i + Offset;
7378 ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7380 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7383 // Found a valid zext mask! Try various lowering strategies based on the
7384 // input type and available ISA extensions.
7385 if (Subtarget->hasSSE41()) {
7386 // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7387 // PUNPCK will catch this in a later shuffle match.
7388 if (Offset && Scale == 2 && VT.getSizeInBits() == 128)
7390 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7391 NumElements / Scale);
7392 InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7393 return DAG.getBitcast(VT, InputV);
7396 assert(VT.getSizeInBits() == 128 && "Only 128-bit vectors can be extended.");
7398 // For any extends we can cheat for larger element sizes and use shuffle
7399 // instructions that can fold with a load and/or copy.
7400 if (AnyExt && EltBits == 32) {
7401 int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7403 return DAG.getBitcast(
7404 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7405 DAG.getBitcast(MVT::v4i32, InputV),
7406 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7408 if (AnyExt && EltBits == 16 && Scale > 2) {
7409 int PSHUFDMask[4] = {Offset / 2, -1,
7410 SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7411 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7412 DAG.getBitcast(MVT::v4i32, InputV),
7413 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7414 int PSHUFWMask[4] = {1, -1, -1, -1};
7415 unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7416 return DAG.getBitcast(
7417 VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7418 DAG.getBitcast(MVT::v8i16, InputV),
7419 getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7422 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7424 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7425 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7426 assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7428 int LoIdx = Offset * EltBits;
7429 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7430 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7431 DAG.getConstant(EltBits, DL, MVT::i8),
7432 DAG.getConstant(LoIdx, DL, MVT::i8)));
7434 if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7435 !SafeOffset(Offset + 1))
7436 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7438 int HiIdx = (Offset + 1) * EltBits;
7439 SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7440 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7441 DAG.getConstant(EltBits, DL, MVT::i8),
7442 DAG.getConstant(HiIdx, DL, MVT::i8)));
7443 return DAG.getNode(ISD::BITCAST, DL, VT,
7444 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7447 // If this would require more than 2 unpack instructions to expand, use
7448 // pshufb when available. We can only use more than 2 unpack instructions
7449 // when zero extending i8 elements which also makes it easier to use pshufb.
7450 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7451 assert(NumElements == 16 && "Unexpected byte vector width!");
7452 SDValue PSHUFBMask[16];
7453 for (int i = 0; i < 16; ++i) {
7454 int Idx = Offset + (i / Scale);
7455 PSHUFBMask[i] = DAG.getConstant(
7456 (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7458 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7459 return DAG.getBitcast(VT,
7460 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7461 DAG.getNode(ISD::BUILD_VECTOR, DL,
7462 MVT::v16i8, PSHUFBMask)));
7465 // If we are extending from an (odd)offset, shuffle them by 1 element.
7467 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7468 for (int i = 1; i < NumElements; ++i)
7470 InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7474 // Otherwise emit a sequence of unpacks.
7476 unsigned UnpackLoHi = X86ISD::UNPCKL;
7477 if (Offset >= (NumElements / 2)) {
7478 UnpackLoHi = X86ISD::UNPCKH;
7479 Offset -= (NumElements / 2);
7482 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7483 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7484 : getZeroVector(InputVT, Subtarget, DAG, DL);
7485 InputV = DAG.getBitcast(InputVT, InputV);
7486 InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7490 } while (Scale > 1);
7491 return DAG.getBitcast(VT, InputV);
7494 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7496 /// This routine will try to do everything in its power to cleverly lower
7497 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7498 /// check for the profitability of this lowering, it tries to aggressively
7499 /// match this pattern. It will use all of the micro-architectural details it
7500 /// can to emit an efficient lowering. It handles both blends with all-zero
7501 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7502 /// masking out later).
7504 /// The reason we have dedicated lowering for zext-style shuffles is that they
7505 /// are both incredibly common and often quite performance sensitive.
7506 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7507 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7508 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7509 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7511 int Bits = VT.getSizeInBits();
7512 int NumLanes = Bits / 128;
7513 int NumElements = VT.getVectorNumElements();
7514 int NumEltsPerLane = NumElements / NumLanes;
7515 assert(VT.getScalarSizeInBits() <= 32 &&
7516 "Exceeds 32-bit integer zero extension limit");
7517 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7519 // Define a helper function to check a particular ext-scale and lower to it if
7521 auto Lower = [&](int Scale) -> SDValue {
7526 for (int i = 0; i < NumElements; ++i) {
7529 continue; // Valid anywhere but doesn't tell us anything.
7530 if (i % Scale != 0) {
7531 // Each of the extended elements need to be zeroable.
7535 // We no longer are in the anyext case.
7540 // Each of the base elements needs to be consecutive indices into the
7541 // same input vector.
7542 SDValue V = M < NumElements ? V1 : V2;
7543 M = M % NumElements;
7546 Offset = M - (i / Scale);
7547 } else if (InputV != V)
7548 return SDValue(); // Flip-flopping inputs.
7550 // Offset must start in the lowest 128-bit lane or at the start of an
7552 // FIXME: Is it ever worth allowing a negative base offset?
7553 if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7554 (Offset % NumEltsPerLane) == 0))
7557 // If we are offsetting, all referenced entries must come from the same
7559 if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7562 if ((M % NumElements) != (Offset + (i / Scale)))
7563 return SDValue(); // Non-consecutive strided elements.
7567 // If we fail to find an input, we have a zero-shuffle which should always
7568 // have already been handled.
7569 // FIXME: Maybe handle this here in case during blending we end up with one?
7573 // If we are offsetting, don't extend if we only match a single input, we
7574 // can always do better by using a basic PSHUF or PUNPCK.
7575 if (Offset != 0 && Matches < 2)
7578 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7579 DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7582 // The widest scale possible for extending is to a 64-bit integer.
7583 assert(Bits % 64 == 0 &&
7584 "The number of bits in a vector must be divisible by 64 on x86!");
7585 int NumExtElements = Bits / 64;
7587 // Each iteration, try extending the elements half as much, but into twice as
7589 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7590 assert(NumElements % NumExtElements == 0 &&
7591 "The input vector size must be divisible by the extended size.");
7592 if (SDValue V = Lower(NumElements / NumExtElements))
7596 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7600 // Returns one of the source operands if the shuffle can be reduced to a
7601 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7602 auto CanZExtLowHalf = [&]() {
7603 for (int i = NumElements / 2; i != NumElements; ++i)
7606 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7608 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7613 if (SDValue V = CanZExtLowHalf()) {
7614 V = DAG.getBitcast(MVT::v2i64, V);
7615 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7616 return DAG.getBitcast(VT, V);
7619 // No viable ext lowering found.
7623 /// \brief Try to get a scalar value for a specific element of a vector.
7625 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7626 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7627 SelectionDAG &DAG) {
7628 MVT VT = V.getSimpleValueType();
7629 MVT EltVT = VT.getVectorElementType();
7630 while (V.getOpcode() == ISD::BITCAST)
7631 V = V.getOperand(0);
7632 // If the bitcasts shift the element size, we can't extract an equivalent
7634 MVT NewVT = V.getSimpleValueType();
7635 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7638 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7639 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7640 // Ensure the scalar operand is the same size as the destination.
7641 // FIXME: Add support for scalar truncation where possible.
7642 SDValue S = V.getOperand(Idx);
7643 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7644 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7650 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7652 /// This is particularly important because the set of instructions varies
7653 /// significantly based on whether the operand is a load or not.
7654 static bool isShuffleFoldableLoad(SDValue V) {
7655 while (V.getOpcode() == ISD::BITCAST)
7656 V = V.getOperand(0);
7658 return ISD::isNON_EXTLoad(V.getNode());
7661 /// \brief Try to lower insertion of a single element into a zero vector.
7663 /// This is a common pattern that we have especially efficient patterns to lower
7664 /// across all subtarget feature sets.
7665 static SDValue lowerVectorShuffleAsElementInsertion(
7666 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7667 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7668 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7670 MVT EltVT = VT.getVectorElementType();
7672 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7673 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7675 bool IsV1Zeroable = true;
7676 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7677 if (i != V2Index && !Zeroable[i]) {
7678 IsV1Zeroable = false;
7682 // Check for a single input from a SCALAR_TO_VECTOR node.
7683 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7684 // all the smarts here sunk into that routine. However, the current
7685 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7686 // vector shuffle lowering is dead.
7687 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7689 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7690 // We need to zext the scalar if it is smaller than an i32.
7691 V2S = DAG.getBitcast(EltVT, V2S);
7692 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7693 // Using zext to expand a narrow element won't work for non-zero
7698 // Zero-extend directly to i32.
7700 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7702 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7703 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7704 EltVT == MVT::i16) {
7705 // Either not inserting from the low element of the input or the input
7706 // element size is too small to use VZEXT_MOVL to clear the high bits.
7710 if (!IsV1Zeroable) {
7711 // If V1 can't be treated as a zero vector we have fewer options to lower
7712 // this. We can't support integer vectors or non-zero targets cheaply, and
7713 // the V1 elements can't be permuted in any way.
7714 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7715 if (!VT.isFloatingPoint() || V2Index != 0)
7717 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7718 V1Mask[V2Index] = -1;
7719 if (!isNoopShuffleMask(V1Mask))
7721 // This is essentially a special case blend operation, but if we have
7722 // general purpose blend operations, they are always faster. Bail and let
7723 // the rest of the lowering handle these as blends.
7724 if (Subtarget->hasSSE41())
7727 // Otherwise, use MOVSD or MOVSS.
7728 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7729 "Only two types of floating point element types to handle!");
7730 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7734 // This lowering only works for the low element with floating point vectors.
7735 if (VT.isFloatingPoint() && V2Index != 0)
7738 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7740 V2 = DAG.getBitcast(VT, V2);
7743 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7744 // the desired position. Otherwise it is more efficient to do a vector
7745 // shift left. We know that we can do a vector shift left because all
7746 // the inputs are zero.
7747 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7748 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7749 V2Shuffle[V2Index] = 0;
7750 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7752 V2 = DAG.getBitcast(MVT::v2i64, V2);
7754 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7755 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7756 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7757 DAG.getDataLayout(), VT)));
7758 V2 = DAG.getBitcast(VT, V2);
7764 /// \brief Try to lower broadcast of a single element.
7766 /// For convenience, this code also bundles all of the subtarget feature set
7767 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7768 /// a convenient way to factor it out.
7769 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7771 const X86Subtarget *Subtarget,
7772 SelectionDAG &DAG) {
7773 if (!Subtarget->hasAVX())
7775 if (VT.isInteger() && !Subtarget->hasAVX2())
7778 // Check that the mask is a broadcast.
7779 int BroadcastIdx = -1;
7781 if (M >= 0 && BroadcastIdx == -1)
7783 else if (M >= 0 && M != BroadcastIdx)
7786 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7787 "a sorted mask where the broadcast "
7790 // Go up the chain of (vector) values to find a scalar load that we can
7791 // combine with the broadcast.
7793 switch (V.getOpcode()) {
7794 case ISD::CONCAT_VECTORS: {
7795 int OperandSize = Mask.size() / V.getNumOperands();
7796 V = V.getOperand(BroadcastIdx / OperandSize);
7797 BroadcastIdx %= OperandSize;
7801 case ISD::INSERT_SUBVECTOR: {
7802 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7803 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7807 int BeginIdx = (int)ConstantIdx->getZExtValue();
7809 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7810 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7811 BroadcastIdx -= BeginIdx;
7822 // Check if this is a broadcast of a scalar. We special case lowering
7823 // for scalars so that we can more effectively fold with loads.
7824 // First, look through bitcast: if the original value has a larger element
7825 // type than the shuffle, the broadcast element is in essence truncated.
7826 // Make that explicit to ease folding.
7827 if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7828 EVT EltVT = VT.getVectorElementType();
7829 SDValue V0 = V.getOperand(0);
7830 EVT V0VT = V0.getValueType();
7832 if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7833 ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7834 (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7835 V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7840 // Also check the simpler case, where we can directly reuse the scalar.
7841 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7842 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7843 V = V.getOperand(BroadcastIdx);
7845 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7846 // Only AVX2 has register broadcasts.
7847 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7849 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7850 // We can't broadcast from a vector register without AVX2, and we can only
7851 // broadcast from the zero-element of a vector register.
7855 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7858 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7859 // INSERTPS when the V1 elements are already in the correct locations
7860 // because otherwise we can just always use two SHUFPS instructions which
7861 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7862 // perform INSERTPS if a single V1 element is out of place and all V2
7863 // elements are zeroable.
7864 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7866 SelectionDAG &DAG) {
7867 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7868 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7869 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7870 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7872 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7875 int V1DstIndex = -1;
7876 int V2DstIndex = -1;
7877 bool V1UsedInPlace = false;
7879 for (int i = 0; i < 4; ++i) {
7880 // Synthesize a zero mask from the zeroable elements (includes undefs).
7886 // Flag if we use any V1 inputs in place.
7888 V1UsedInPlace = true;
7892 // We can only insert a single non-zeroable element.
7893 if (V1DstIndex != -1 || V2DstIndex != -1)
7897 // V1 input out of place for insertion.
7900 // V2 input for insertion.
7905 // Don't bother if we have no (non-zeroable) element for insertion.
7906 if (V1DstIndex == -1 && V2DstIndex == -1)
7909 // Determine element insertion src/dst indices. The src index is from the
7910 // start of the inserted vector, not the start of the concatenated vector.
7911 unsigned V2SrcIndex = 0;
7912 if (V1DstIndex != -1) {
7913 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7914 // and don't use the original V2 at all.
7915 V2SrcIndex = Mask[V1DstIndex];
7916 V2DstIndex = V1DstIndex;
7919 V2SrcIndex = Mask[V2DstIndex] - 4;
7922 // If no V1 inputs are used in place, then the result is created only from
7923 // the zero mask and the V2 insertion - so remove V1 dependency.
7925 V1 = DAG.getUNDEF(MVT::v4f32);
7927 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7928 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7930 // Insert the V2 element into the desired position.
7932 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7933 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7936 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7937 /// UNPCK instruction.
7939 /// This specifically targets cases where we end up with alternating between
7940 /// the two inputs, and so can permute them into something that feeds a single
7941 /// UNPCK instruction. Note that this routine only targets integer vectors
7942 /// because for floating point vectors we have a generalized SHUFPS lowering
7943 /// strategy that handles everything that doesn't *exactly* match an unpack,
7944 /// making this clever lowering unnecessary.
7945 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
7946 SDValue V1, SDValue V2,
7948 SelectionDAG &DAG) {
7949 assert(!VT.isFloatingPoint() &&
7950 "This routine only supports integer vectors.");
7951 assert(!isSingleInputShuffleMask(Mask) &&
7952 "This routine should only be used when blending two inputs.");
7953 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7955 int Size = Mask.size();
7957 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7958 return M >= 0 && M % Size < Size / 2;
7960 int NumHiInputs = std::count_if(
7961 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7963 bool UnpackLo = NumLoInputs >= NumHiInputs;
7965 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7966 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7967 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7969 for (int i = 0; i < Size; ++i) {
7973 // Each element of the unpack contains Scale elements from this mask.
7974 int UnpackIdx = i / Scale;
7976 // We only handle the case where V1 feeds the first slots of the unpack.
7977 // We rely on canonicalization to ensure this is the case.
7978 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7981 // Setup the mask for this input. The indexing is tricky as we have to
7982 // handle the unpack stride.
7983 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7984 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7988 // If we will have to shuffle both inputs to use the unpack, check whether
7989 // we can just unpack first and shuffle the result. If so, skip this unpack.
7990 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7991 !isNoopShuffleMask(V2Mask))
7994 // Shuffle the inputs into place.
7995 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7996 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7998 // Cast the inputs to the type we will use to unpack them.
7999 V1 = DAG.getBitcast(UnpackVT, V1);
8000 V2 = DAG.getBitcast(UnpackVT, V2);
8002 // Unpack the inputs and cast the result back to the desired type.
8003 return DAG.getBitcast(
8004 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8008 // We try each unpack from the largest to the smallest to try and find one
8009 // that fits this mask.
8010 int OrigNumElements = VT.getVectorNumElements();
8011 int OrigScalarSize = VT.getScalarSizeInBits();
8012 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8013 int Scale = ScalarSize / OrigScalarSize;
8014 int NumElements = OrigNumElements / Scale;
8015 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8016 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8020 // If none of the unpack-rooted lowerings worked (or were profitable) try an
8022 if (NumLoInputs == 0 || NumHiInputs == 0) {
8023 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8024 "We have to have *some* inputs!");
8025 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8027 // FIXME: We could consider the total complexity of the permute of each
8028 // possible unpacking. Or at the least we should consider how many
8029 // half-crossings are created.
8030 // FIXME: We could consider commuting the unpacks.
8032 SmallVector<int, 32> PermMask;
8033 PermMask.assign(Size, -1);
8034 for (int i = 0; i < Size; ++i) {
8038 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8041 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8043 return DAG.getVectorShuffle(
8044 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8046 DAG.getUNDEF(VT), PermMask);
8052 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8054 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8055 /// support for floating point shuffles but not integer shuffles. These
8056 /// instructions will incur a domain crossing penalty on some chips though so
8057 /// it is better to avoid lowering through this for integer vectors where
8059 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8060 const X86Subtarget *Subtarget,
8061 SelectionDAG &DAG) {
8063 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8064 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8065 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8066 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8067 ArrayRef<int> Mask = SVOp->getMask();
8068 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8070 if (isSingleInputShuffleMask(Mask)) {
8071 // Use low duplicate instructions for masks that match their pattern.
8072 if (Subtarget->hasSSE3())
8073 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8074 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8076 // Straight shuffle of a single input vector. Simulate this by using the
8077 // single input as both of the "inputs" to this instruction..
8078 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8080 if (Subtarget->hasAVX()) {
8081 // If we have AVX, we can use VPERMILPS which will allow folding a load
8082 // into the shuffle.
8083 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8084 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8087 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8088 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8090 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8091 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8093 // If we have a single input, insert that into V1 if we can do so cheaply.
8094 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8095 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8096 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8098 // Try inverting the insertion since for v2 masks it is easy to do and we
8099 // can't reliably sort the mask one way or the other.
8100 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8101 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8102 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8103 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8107 // Try to use one of the special instruction patterns to handle two common
8108 // blend patterns if a zero-blend above didn't work.
8109 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8110 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8111 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8112 // We can either use a special instruction to load over the low double or
8113 // to move just the low double.
8115 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8117 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8119 if (Subtarget->hasSSE41())
8120 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8124 // Use dedicated unpack instructions for masks that match their pattern.
8125 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8126 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
8127 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8128 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
8130 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8131 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8132 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8135 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8137 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8138 /// the integer unit to minimize domain crossing penalties. However, for blends
8139 /// it falls back to the floating point shuffle operation with appropriate bit
8141 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8142 const X86Subtarget *Subtarget,
8143 SelectionDAG &DAG) {
8145 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8146 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8147 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8148 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8149 ArrayRef<int> Mask = SVOp->getMask();
8150 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8152 if (isSingleInputShuffleMask(Mask)) {
8153 // Check for being able to broadcast a single element.
8154 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8155 Mask, Subtarget, DAG))
8158 // Straight shuffle of a single input vector. For everything from SSE2
8159 // onward this has a single fast instruction with no scary immediates.
8160 // We have to map the mask as it is actually a v4i32 shuffle instruction.
8161 V1 = DAG.getBitcast(MVT::v4i32, V1);
8162 int WidenedMask[4] = {
8163 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8164 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8165 return DAG.getBitcast(
8167 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8168 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8170 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8171 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8172 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8173 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8175 // If we have a blend of two PACKUS operations an the blend aligns with the
8176 // low and half halves, we can just merge the PACKUS operations. This is
8177 // particularly important as it lets us merge shuffles that this routine itself
8179 auto GetPackNode = [](SDValue V) {
8180 while (V.getOpcode() == ISD::BITCAST)
8181 V = V.getOperand(0);
8183 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8185 if (SDValue V1Pack = GetPackNode(V1))
8186 if (SDValue V2Pack = GetPackNode(V2))
8187 return DAG.getBitcast(MVT::v2i64,
8188 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8189 Mask[0] == 0 ? V1Pack.getOperand(0)
8190 : V1Pack.getOperand(1),
8191 Mask[1] == 2 ? V2Pack.getOperand(0)
8192 : V2Pack.getOperand(1)));
8194 // Try to use shift instructions.
8196 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8199 // When loading a scalar and then shuffling it into a vector we can often do
8200 // the insertion cheaply.
8201 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8202 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8204 // Try inverting the insertion since for v2 masks it is easy to do and we
8205 // can't reliably sort the mask one way or the other.
8206 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8207 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8208 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8211 // We have different paths for blend lowering, but they all must use the
8212 // *exact* same predicate.
8213 bool IsBlendSupported = Subtarget->hasSSE41();
8214 if (IsBlendSupported)
8215 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8219 // Use dedicated unpack instructions for masks that match their pattern.
8220 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
8221 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
8222 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8223 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
8225 // Try to use byte rotation instructions.
8226 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8227 if (Subtarget->hasSSSE3())
8228 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8229 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8232 // If we have direct support for blends, we should lower by decomposing into
8233 // a permute. That will be faster than the domain cross.
8234 if (IsBlendSupported)
8235 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8238 // We implement this with SHUFPD which is pretty lame because it will likely
8239 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8240 // However, all the alternatives are still more cycles and newer chips don't
8241 // have this problem. It would be really nice if x86 had better shuffles here.
8242 V1 = DAG.getBitcast(MVT::v2f64, V1);
8243 V2 = DAG.getBitcast(MVT::v2f64, V2);
8244 return DAG.getBitcast(MVT::v2i64,
8245 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8248 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8250 /// This is used to disable more specialized lowerings when the shufps lowering
8251 /// will happen to be efficient.
8252 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8253 // This routine only handles 128-bit shufps.
8254 assert(Mask.size() == 4 && "Unsupported mask size!");
8256 // To lower with a single SHUFPS we need to have the low half and high half
8257 // each requiring a single input.
8258 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8260 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8266 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8268 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8269 /// It makes no assumptions about whether this is the *best* lowering, it simply
8271 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8272 ArrayRef<int> Mask, SDValue V1,
8273 SDValue V2, SelectionDAG &DAG) {
8274 SDValue LowV = V1, HighV = V2;
8275 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8278 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8280 if (NumV2Elements == 1) {
8282 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8285 // Compute the index adjacent to V2Index and in the same half by toggling
8287 int V2AdjIndex = V2Index ^ 1;
8289 if (Mask[V2AdjIndex] == -1) {
8290 // Handles all the cases where we have a single V2 element and an undef.
8291 // This will only ever happen in the high lanes because we commute the
8292 // vector otherwise.
8294 std::swap(LowV, HighV);
8295 NewMask[V2Index] -= 4;
8297 // Handle the case where the V2 element ends up adjacent to a V1 element.
8298 // To make this work, blend them together as the first step.
8299 int V1Index = V2AdjIndex;
8300 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8301 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8302 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8304 // Now proceed to reconstruct the final blend as we have the necessary
8305 // high or low half formed.
8312 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8313 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8315 } else if (NumV2Elements == 2) {
8316 if (Mask[0] < 4 && Mask[1] < 4) {
8317 // Handle the easy case where we have V1 in the low lanes and V2 in the
8321 } else if (Mask[2] < 4 && Mask[3] < 4) {
8322 // We also handle the reversed case because this utility may get called
8323 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8324 // arrange things in the right direction.
8330 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8331 // trying to place elements directly, just blend them and set up the final
8332 // shuffle to place them.
8334 // The first two blend mask elements are for V1, the second two are for
8336 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8337 Mask[2] < 4 ? Mask[2] : Mask[3],
8338 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8339 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8340 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8341 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8343 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8346 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8347 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8348 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8349 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8352 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8353 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8356 /// \brief Lower 4-lane 32-bit floating point shuffles.
8358 /// Uses instructions exclusively from the floating point unit to minimize
8359 /// domain crossing penalties, as these are sufficient to implement all v4f32
8361 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8362 const X86Subtarget *Subtarget,
8363 SelectionDAG &DAG) {
8365 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8366 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8367 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8368 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8369 ArrayRef<int> Mask = SVOp->getMask();
8370 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8373 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8375 if (NumV2Elements == 0) {
8376 // Check for being able to broadcast a single element.
8377 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8378 Mask, Subtarget, DAG))
8381 // Use even/odd duplicate instructions for masks that match their pattern.
8382 if (Subtarget->hasSSE3()) {
8383 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8384 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8385 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8386 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8389 if (Subtarget->hasAVX()) {
8390 // If we have AVX, we can use VPERMILPS which will allow folding a load
8391 // into the shuffle.
8392 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8393 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8396 // Otherwise, use a straight shuffle of a single input vector. We pass the
8397 // input vector to both operands to simulate this with a SHUFPS.
8398 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8399 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8402 // There are special ways we can lower some single-element blends. However, we
8403 // have custom ways we can lower more complex single-element blends below that
8404 // we defer to if both this and BLENDPS fail to match, so restrict this to
8405 // when the V2 input is targeting element 0 of the mask -- that is the fast
8407 if (NumV2Elements == 1 && Mask[0] >= 4)
8408 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8409 Mask, Subtarget, DAG))
8412 if (Subtarget->hasSSE41()) {
8413 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8417 // Use INSERTPS if we can complete the shuffle efficiently.
8418 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8421 if (!isSingleSHUFPSMask(Mask))
8422 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8423 DL, MVT::v4f32, V1, V2, Mask, DAG))
8427 // Use dedicated unpack instructions for masks that match their pattern.
8428 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8429 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8430 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8431 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8432 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8433 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8434 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8435 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8437 // Otherwise fall back to a SHUFPS lowering strategy.
8438 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8441 /// \brief Lower 4-lane i32 vector shuffles.
8443 /// We try to handle these with integer-domain shuffles where we can, but for
8444 /// blends we use the floating point domain blend instructions.
8445 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8446 const X86Subtarget *Subtarget,
8447 SelectionDAG &DAG) {
8449 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8450 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8451 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8452 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8453 ArrayRef<int> Mask = SVOp->getMask();
8454 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8456 // Whenever we can lower this as a zext, that instruction is strictly faster
8457 // than any alternative. It also allows us to fold memory operands into the
8458 // shuffle in many cases.
8459 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8460 Mask, Subtarget, DAG))
8464 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8466 if (NumV2Elements == 0) {
8467 // Check for being able to broadcast a single element.
8468 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8469 Mask, Subtarget, DAG))
8472 // Straight shuffle of a single input vector. For everything from SSE2
8473 // onward this has a single fast instruction with no scary immediates.
8474 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8475 // but we aren't actually going to use the UNPCK instruction because doing
8476 // so prevents folding a load into this instruction or making a copy.
8477 const int UnpackLoMask[] = {0, 0, 1, 1};
8478 const int UnpackHiMask[] = {2, 2, 3, 3};
8479 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8480 Mask = UnpackLoMask;
8481 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8482 Mask = UnpackHiMask;
8484 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8485 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8488 // Try to use shift instructions.
8490 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8493 // There are special ways we can lower some single-element blends.
8494 if (NumV2Elements == 1)
8495 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8496 Mask, Subtarget, DAG))
8499 // We have different paths for blend lowering, but they all must use the
8500 // *exact* same predicate.
8501 bool IsBlendSupported = Subtarget->hasSSE41();
8502 if (IsBlendSupported)
8503 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8507 if (SDValue Masked =
8508 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8511 // Use dedicated unpack instructions for masks that match their pattern.
8512 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8513 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8514 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8515 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8516 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8517 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8518 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8519 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8521 // Try to use byte rotation instructions.
8522 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8523 if (Subtarget->hasSSSE3())
8524 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8525 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8528 // If we have direct support for blends, we should lower by decomposing into
8529 // a permute. That will be faster than the domain cross.
8530 if (IsBlendSupported)
8531 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8534 // Try to lower by permuting the inputs into an unpack instruction.
8535 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8539 // We implement this with SHUFPS because it can blend from two vectors.
8540 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8541 // up the inputs, bypassing domain shift penalties that we would encur if we
8542 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8544 return DAG.getBitcast(
8546 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8547 DAG.getBitcast(MVT::v4f32, V2), Mask));
8550 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8551 /// shuffle lowering, and the most complex part.
8553 /// The lowering strategy is to try to form pairs of input lanes which are
8554 /// targeted at the same half of the final vector, and then use a dword shuffle
8555 /// to place them onto the right half, and finally unpack the paired lanes into
8556 /// their final position.
8558 /// The exact breakdown of how to form these dword pairs and align them on the
8559 /// correct sides is really tricky. See the comments within the function for
8560 /// more of the details.
8562 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8563 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8564 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8565 /// vector, form the analogous 128-bit 8-element Mask.
8566 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8567 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8568 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8569 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8570 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8572 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8573 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8574 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8576 SmallVector<int, 4> LoInputs;
8577 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8578 [](int M) { return M >= 0; });
8579 std::sort(LoInputs.begin(), LoInputs.end());
8580 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8581 SmallVector<int, 4> HiInputs;
8582 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8583 [](int M) { return M >= 0; });
8584 std::sort(HiInputs.begin(), HiInputs.end());
8585 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8587 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8588 int NumHToL = LoInputs.size() - NumLToL;
8590 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8591 int NumHToH = HiInputs.size() - NumLToH;
8592 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8593 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8594 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8595 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8597 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8598 // such inputs we can swap two of the dwords across the half mark and end up
8599 // with <=2 inputs to each half in each half. Once there, we can fall through
8600 // to the generic code below. For example:
8602 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8603 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8605 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8606 // and an existing 2-into-2 on the other half. In this case we may have to
8607 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8608 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8609 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8610 // because any other situation (including a 3-into-1 or 1-into-3 in the other
8611 // half than the one we target for fixing) will be fixed when we re-enter this
8612 // path. We will also combine away any sequence of PSHUFD instructions that
8613 // result into a single instruction. Here is an example of the tricky case:
8615 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8616 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8618 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8620 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8621 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8623 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8624 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8626 // The result is fine to be handled by the generic logic.
8627 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8628 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8629 int AOffset, int BOffset) {
8630 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8631 "Must call this with A having 3 or 1 inputs from the A half.");
8632 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8633 "Must call this with B having 1 or 3 inputs from the B half.");
8634 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8635 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8637 bool ThreeAInputs = AToAInputs.size() == 3;
8639 // Compute the index of dword with only one word among the three inputs in
8640 // a half by taking the sum of the half with three inputs and subtracting
8641 // the sum of the actual three inputs. The difference is the remaining
8644 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8645 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8646 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8647 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8648 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8649 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8650 int TripleNonInputIdx =
8651 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8652 TripleDWord = TripleNonInputIdx / 2;
8654 // We use xor with one to compute the adjacent DWord to whichever one the
8656 OneInputDWord = (OneInput / 2) ^ 1;
8658 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8659 // and BToA inputs. If there is also such a problem with the BToB and AToB
8660 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8661 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8662 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8663 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8664 // Compute how many inputs will be flipped by swapping these DWords. We
8666 // to balance this to ensure we don't form a 3-1 shuffle in the other
8668 int NumFlippedAToBInputs =
8669 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8670 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8671 int NumFlippedBToBInputs =
8672 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8673 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8674 if ((NumFlippedAToBInputs == 1 &&
8675 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8676 (NumFlippedBToBInputs == 1 &&
8677 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8678 // We choose whether to fix the A half or B half based on whether that
8679 // half has zero flipped inputs. At zero, we may not be able to fix it
8680 // with that half. We also bias towards fixing the B half because that
8681 // will more commonly be the high half, and we have to bias one way.
8682 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8683 ArrayRef<int> Inputs) {
8684 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8685 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8686 PinnedIdx ^ 1) != Inputs.end();
8687 // Determine whether the free index is in the flipped dword or the
8688 // unflipped dword based on where the pinned index is. We use this bit
8689 // in an xor to conditionally select the adjacent dword.
8690 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8691 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8692 FixFreeIdx) != Inputs.end();
8693 if (IsFixIdxInput == IsFixFreeIdxInput)
8695 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8696 FixFreeIdx) != Inputs.end();
8697 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8698 "We need to be changing the number of flipped inputs!");
8699 int PSHUFHalfMask[] = {0, 1, 2, 3};
8700 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8701 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8703 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8706 if (M != -1 && M == FixIdx)
8708 else if (M != -1 && M == FixFreeIdx)
8711 if (NumFlippedBToBInputs != 0) {
8713 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8714 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8716 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8717 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8718 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8723 int PSHUFDMask[] = {0, 1, 2, 3};
8724 PSHUFDMask[ADWord] = BDWord;
8725 PSHUFDMask[BDWord] = ADWord;
8728 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8729 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8731 // Adjust the mask to match the new locations of A and B.
8733 if (M != -1 && M/2 == ADWord)
8734 M = 2 * BDWord + M % 2;
8735 else if (M != -1 && M/2 == BDWord)
8736 M = 2 * ADWord + M % 2;
8738 // Recurse back into this routine to re-compute state now that this isn't
8739 // a 3 and 1 problem.
8740 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8743 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8744 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8745 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8746 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8748 // At this point there are at most two inputs to the low and high halves from
8749 // each half. That means the inputs can always be grouped into dwords and
8750 // those dwords can then be moved to the correct half with a dword shuffle.
8751 // We use at most one low and one high word shuffle to collect these paired
8752 // inputs into dwords, and finally a dword shuffle to place them.
8753 int PSHUFLMask[4] = {-1, -1, -1, -1};
8754 int PSHUFHMask[4] = {-1, -1, -1, -1};
8755 int PSHUFDMask[4] = {-1, -1, -1, -1};
8757 // First fix the masks for all the inputs that are staying in their
8758 // original halves. This will then dictate the targets of the cross-half
8760 auto fixInPlaceInputs =
8761 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8762 MutableArrayRef<int> SourceHalfMask,
8763 MutableArrayRef<int> HalfMask, int HalfOffset) {
8764 if (InPlaceInputs.empty())
8766 if (InPlaceInputs.size() == 1) {
8767 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8768 InPlaceInputs[0] - HalfOffset;
8769 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8772 if (IncomingInputs.empty()) {
8773 // Just fix all of the in place inputs.
8774 for (int Input : InPlaceInputs) {
8775 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8776 PSHUFDMask[Input / 2] = Input / 2;
8781 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8782 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8783 InPlaceInputs[0] - HalfOffset;
8784 // Put the second input next to the first so that they are packed into
8785 // a dword. We find the adjacent index by toggling the low bit.
8786 int AdjIndex = InPlaceInputs[0] ^ 1;
8787 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8788 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8789 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8791 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8792 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8794 // Now gather the cross-half inputs and place them into a free dword of
8795 // their target half.
8796 // FIXME: This operation could almost certainly be simplified dramatically to
8797 // look more like the 3-1 fixing operation.
8798 auto moveInputsToRightHalf = [&PSHUFDMask](
8799 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8800 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8801 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8803 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8804 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8806 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8808 int LowWord = Word & ~1;
8809 int HighWord = Word | 1;
8810 return isWordClobbered(SourceHalfMask, LowWord) ||
8811 isWordClobbered(SourceHalfMask, HighWord);
8814 if (IncomingInputs.empty())
8817 if (ExistingInputs.empty()) {
8818 // Map any dwords with inputs from them into the right half.
8819 for (int Input : IncomingInputs) {
8820 // If the source half mask maps over the inputs, turn those into
8821 // swaps and use the swapped lane.
8822 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8823 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8824 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8825 Input - SourceOffset;
8826 // We have to swap the uses in our half mask in one sweep.
8827 for (int &M : HalfMask)
8828 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8830 else if (M == Input)
8831 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8833 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8834 Input - SourceOffset &&
8835 "Previous placement doesn't match!");
8837 // Note that this correctly re-maps both when we do a swap and when
8838 // we observe the other side of the swap above. We rely on that to
8839 // avoid swapping the members of the input list directly.
8840 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8843 // Map the input's dword into the correct half.
8844 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8845 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8847 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8849 "Previous placement doesn't match!");
8852 // And just directly shift any other-half mask elements to be same-half
8853 // as we will have mirrored the dword containing the element into the
8854 // same position within that half.
8855 for (int &M : HalfMask)
8856 if (M >= SourceOffset && M < SourceOffset + 4) {
8857 M = M - SourceOffset + DestOffset;
8858 assert(M >= 0 && "This should never wrap below zero!");
8863 // Ensure we have the input in a viable dword of its current half. This
8864 // is particularly tricky because the original position may be clobbered
8865 // by inputs being moved and *staying* in that half.
8866 if (IncomingInputs.size() == 1) {
8867 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8868 int InputFixed = std::find(std::begin(SourceHalfMask),
8869 std::end(SourceHalfMask), -1) -
8870 std::begin(SourceHalfMask) + SourceOffset;
8871 SourceHalfMask[InputFixed - SourceOffset] =
8872 IncomingInputs[0] - SourceOffset;
8873 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8875 IncomingInputs[0] = InputFixed;
8877 } else if (IncomingInputs.size() == 2) {
8878 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8879 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8880 // We have two non-adjacent or clobbered inputs we need to extract from
8881 // the source half. To do this, we need to map them into some adjacent
8882 // dword slot in the source mask.
8883 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8884 IncomingInputs[1] - SourceOffset};
8886 // If there is a free slot in the source half mask adjacent to one of
8887 // the inputs, place the other input in it. We use (Index XOR 1) to
8888 // compute an adjacent index.
8889 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8890 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8891 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8892 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8893 InputsFixed[1] = InputsFixed[0] ^ 1;
8894 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8895 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8896 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8897 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8898 InputsFixed[0] = InputsFixed[1] ^ 1;
8899 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8900 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8901 // The two inputs are in the same DWord but it is clobbered and the
8902 // adjacent DWord isn't used at all. Move both inputs to the free
8904 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8905 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8906 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8907 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8909 // The only way we hit this point is if there is no clobbering
8910 // (because there are no off-half inputs to this half) and there is no
8911 // free slot adjacent to one of the inputs. In this case, we have to
8912 // swap an input with a non-input.
8913 for (int i = 0; i < 4; ++i)
8914 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8915 "We can't handle any clobbers here!");
8916 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8917 "Cannot have adjacent inputs here!");
8919 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8920 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8922 // We also have to update the final source mask in this case because
8923 // it may need to undo the above swap.
8924 for (int &M : FinalSourceHalfMask)
8925 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8926 M = InputsFixed[1] + SourceOffset;
8927 else if (M == InputsFixed[1] + SourceOffset)
8928 M = (InputsFixed[0] ^ 1) + SourceOffset;
8930 InputsFixed[1] = InputsFixed[0] ^ 1;
8933 // Point everything at the fixed inputs.
8934 for (int &M : HalfMask)
8935 if (M == IncomingInputs[0])
8936 M = InputsFixed[0] + SourceOffset;
8937 else if (M == IncomingInputs[1])
8938 M = InputsFixed[1] + SourceOffset;
8940 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8941 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8944 llvm_unreachable("Unhandled input size!");
8947 // Now hoist the DWord down to the right half.
8948 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8949 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8950 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8951 for (int &M : HalfMask)
8952 for (int Input : IncomingInputs)
8954 M = FreeDWord * 2 + Input % 2;
8956 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8957 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8958 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8959 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8961 // Now enact all the shuffles we've computed to move the inputs into their
8963 if (!isNoopShuffleMask(PSHUFLMask))
8964 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8965 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8966 if (!isNoopShuffleMask(PSHUFHMask))
8967 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8968 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8969 if (!isNoopShuffleMask(PSHUFDMask))
8972 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8973 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8975 // At this point, each half should contain all its inputs, and we can then
8976 // just shuffle them into their final position.
8977 assert(std::count_if(LoMask.begin(), LoMask.end(),
8978 [](int M) { return M >= 4; }) == 0 &&
8979 "Failed to lift all the high half inputs to the low mask!");
8980 assert(std::count_if(HiMask.begin(), HiMask.end(),
8981 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8982 "Failed to lift all the low half inputs to the high mask!");
8984 // Do a half shuffle for the low mask.
8985 if (!isNoopShuffleMask(LoMask))
8986 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8987 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8989 // Do a half shuffle with the high mask after shifting its values down.
8990 for (int &M : HiMask)
8993 if (!isNoopShuffleMask(HiMask))
8994 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8995 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9000 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9001 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9002 SDValue V2, ArrayRef<int> Mask,
9003 SelectionDAG &DAG, bool &V1InUse,
9005 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9011 int Size = Mask.size();
9012 int Scale = 16 / Size;
9013 for (int i = 0; i < 16; ++i) {
9014 if (Mask[i / Scale] == -1) {
9015 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9017 const int ZeroMask = 0x80;
9018 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9020 int V2Idx = Mask[i / Scale] < Size
9022 : (Mask[i / Scale] - Size) * Scale + i % Scale;
9023 if (Zeroable[i / Scale])
9024 V1Idx = V2Idx = ZeroMask;
9025 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9026 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9027 V1InUse |= (ZeroMask != V1Idx);
9028 V2InUse |= (ZeroMask != V2Idx);
9033 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9034 DAG.getBitcast(MVT::v16i8, V1),
9035 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9037 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9038 DAG.getBitcast(MVT::v16i8, V2),
9039 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9041 // If we need shuffled inputs from both, blend the two.
9043 if (V1InUse && V2InUse)
9044 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9046 V = V1InUse ? V1 : V2;
9048 // Cast the result back to the correct type.
9049 return DAG.getBitcast(VT, V);
9052 /// \brief Generic lowering of 8-lane i16 shuffles.
9054 /// This handles both single-input shuffles and combined shuffle/blends with
9055 /// two inputs. The single input shuffles are immediately delegated to
9056 /// a dedicated lowering routine.
9058 /// The blends are lowered in one of three fundamental ways. If there are few
9059 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9060 /// of the input is significantly cheaper when lowered as an interleaving of
9061 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9062 /// halves of the inputs separately (making them have relatively few inputs)
9063 /// and then concatenate them.
9064 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9065 const X86Subtarget *Subtarget,
9066 SelectionDAG &DAG) {
9068 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9069 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9070 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9071 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9072 ArrayRef<int> OrigMask = SVOp->getMask();
9073 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9074 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9075 MutableArrayRef<int> Mask(MaskStorage);
9077 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9079 // Whenever we can lower this as a zext, that instruction is strictly faster
9080 // than any alternative.
9081 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9082 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9085 auto isV1 = [](int M) { return M >= 0 && M < 8; };
9087 auto isV2 = [](int M) { return M >= 8; };
9089 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9091 if (NumV2Inputs == 0) {
9092 // Check for being able to broadcast a single element.
9093 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9094 Mask, Subtarget, DAG))
9097 // Try to use shift instructions.
9099 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9102 // Use dedicated unpack instructions for masks that match their pattern.
9103 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
9104 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
9105 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
9106 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
9108 // Try to use byte rotation instructions.
9109 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9110 Mask, Subtarget, DAG))
9113 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9117 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9118 "All single-input shuffles should be canonicalized to be V1-input "
9121 // Try to use shift instructions.
9123 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9126 // See if we can use SSE4A Extraction / Insertion.
9127 if (Subtarget->hasSSE4A())
9128 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9131 // There are special ways we can lower some single-element blends.
9132 if (NumV2Inputs == 1)
9133 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9134 Mask, Subtarget, DAG))
9137 // We have different paths for blend lowering, but they all must use the
9138 // *exact* same predicate.
9139 bool IsBlendSupported = Subtarget->hasSSE41();
9140 if (IsBlendSupported)
9141 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9145 if (SDValue Masked =
9146 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9149 // Use dedicated unpack instructions for masks that match their pattern.
9150 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
9151 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
9152 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
9153 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
9155 // Try to use byte rotation instructions.
9156 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9157 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9160 if (SDValue BitBlend =
9161 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9164 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9168 // If we can't directly blend but can use PSHUFB, that will be better as it
9169 // can both shuffle and set up the inefficient blend.
9170 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9171 bool V1InUse, V2InUse;
9172 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9176 // We can always bit-blend if we have to so the fallback strategy is to
9177 // decompose into single-input permutes and blends.
9178 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9182 /// \brief Check whether a compaction lowering can be done by dropping even
9183 /// elements and compute how many times even elements must be dropped.
9185 /// This handles shuffles which take every Nth element where N is a power of
9186 /// two. Example shuffle masks:
9188 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
9189 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9190 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
9191 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
9192 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
9193 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
9195 /// Any of these lanes can of course be undef.
9197 /// This routine only supports N <= 3.
9198 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9201 /// \returns N above, or the number of times even elements must be dropped if
9202 /// there is such a number. Otherwise returns zero.
9203 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9204 // Figure out whether we're looping over two inputs or just one.
9205 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9207 // The modulus for the shuffle vector entries is based on whether this is
9208 // a single input or not.
9209 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9210 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9211 "We should only be called with masks with a power-of-2 size!");
9213 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9215 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9216 // and 2^3 simultaneously. This is because we may have ambiguity with
9217 // partially undef inputs.
9218 bool ViableForN[3] = {true, true, true};
9220 for (int i = 0, e = Mask.size(); i < e; ++i) {
9221 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9226 bool IsAnyViable = false;
9227 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9228 if (ViableForN[j]) {
9231 // The shuffle mask must be equal to (i * 2^N) % M.
9232 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9235 ViableForN[j] = false;
9237 // Early exit if we exhaust the possible powers of two.
9242 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9246 // Return 0 as there is no viable power of two.
9250 /// \brief Generic lowering of v16i8 shuffles.
9252 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9253 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9254 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9255 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9257 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9258 const X86Subtarget *Subtarget,
9259 SelectionDAG &DAG) {
9261 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9262 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9263 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9264 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9265 ArrayRef<int> Mask = SVOp->getMask();
9266 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9268 // Try to use shift instructions.
9270 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9273 // Try to use byte rotation instructions.
9274 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9275 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9278 // Try to use a zext lowering.
9279 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9280 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9283 // See if we can use SSE4A Extraction / Insertion.
9284 if (Subtarget->hasSSE4A())
9285 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9289 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9291 // For single-input shuffles, there are some nicer lowering tricks we can use.
9292 if (NumV2Elements == 0) {
9293 // Check for being able to broadcast a single element.
9294 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9295 Mask, Subtarget, DAG))
9298 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9299 // Notably, this handles splat and partial-splat shuffles more efficiently.
9300 // However, it only makes sense if the pre-duplication shuffle simplifies
9301 // things significantly. Currently, this means we need to be able to
9302 // express the pre-duplication shuffle as an i16 shuffle.
9304 // FIXME: We should check for other patterns which can be widened into an
9305 // i16 shuffle as well.
9306 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9307 for (int i = 0; i < 16; i += 2)
9308 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9313 auto tryToWidenViaDuplication = [&]() -> SDValue {
9314 if (!canWidenViaDuplication(Mask))
9316 SmallVector<int, 4> LoInputs;
9317 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9318 [](int M) { return M >= 0 && M < 8; });
9319 std::sort(LoInputs.begin(), LoInputs.end());
9320 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9322 SmallVector<int, 4> HiInputs;
9323 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9324 [](int M) { return M >= 8; });
9325 std::sort(HiInputs.begin(), HiInputs.end());
9326 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9329 bool TargetLo = LoInputs.size() >= HiInputs.size();
9330 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9331 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9333 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9334 SmallDenseMap<int, int, 8> LaneMap;
9335 for (int I : InPlaceInputs) {
9336 PreDupI16Shuffle[I/2] = I/2;
9339 int j = TargetLo ? 0 : 4, je = j + 4;
9340 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9341 // Check if j is already a shuffle of this input. This happens when
9342 // there are two adjacent bytes after we move the low one.
9343 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9344 // If we haven't yet mapped the input, search for a slot into which
9346 while (j < je && PreDupI16Shuffle[j] != -1)
9350 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9353 // Map this input with the i16 shuffle.
9354 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9357 // Update the lane map based on the mapping we ended up with.
9358 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9360 V1 = DAG.getBitcast(
9362 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9363 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9365 // Unpack the bytes to form the i16s that will be shuffled into place.
9366 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9367 MVT::v16i8, V1, V1);
9369 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9370 for (int i = 0; i < 16; ++i)
9371 if (Mask[i] != -1) {
9372 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9373 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9374 if (PostDupI16Shuffle[i / 2] == -1)
9375 PostDupI16Shuffle[i / 2] = MappedMask;
9377 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9378 "Conflicting entrties in the original shuffle!");
9380 return DAG.getBitcast(
9382 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9383 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9385 if (SDValue V = tryToWidenViaDuplication())
9389 if (SDValue Masked =
9390 lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9393 // Use dedicated unpack instructions for masks that match their pattern.
9394 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9395 0, 16, 1, 17, 2, 18, 3, 19,
9397 4, 20, 5, 21, 6, 22, 7, 23}))
9398 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9399 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9400 8, 24, 9, 25, 10, 26, 11, 27,
9402 12, 28, 13, 29, 14, 30, 15, 31}))
9403 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9405 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9406 // with PSHUFB. It is important to do this before we attempt to generate any
9407 // blends but after all of the single-input lowerings. If the single input
9408 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9409 // want to preserve that and we can DAG combine any longer sequences into
9410 // a PSHUFB in the end. But once we start blending from multiple inputs,
9411 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9412 // and there are *very* few patterns that would actually be faster than the
9413 // PSHUFB approach because of its ability to zero lanes.
9415 // FIXME: The only exceptions to the above are blends which are exact
9416 // interleavings with direct instructions supporting them. We currently don't
9417 // handle those well here.
9418 if (Subtarget->hasSSSE3()) {
9419 bool V1InUse = false;
9420 bool V2InUse = false;
9422 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9423 DAG, V1InUse, V2InUse);
9425 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9426 // do so. This avoids using them to handle blends-with-zero which is
9427 // important as a single pshufb is significantly faster for that.
9428 if (V1InUse && V2InUse) {
9429 if (Subtarget->hasSSE41())
9430 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9431 Mask, Subtarget, DAG))
9434 // We can use an unpack to do the blending rather than an or in some
9435 // cases. Even though the or may be (very minorly) more efficient, we
9436 // preference this lowering because there are common cases where part of
9437 // the complexity of the shuffles goes away when we do the final blend as
9439 // FIXME: It might be worth trying to detect if the unpack-feeding
9440 // shuffles will both be pshufb, in which case we shouldn't bother with
9442 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9443 DL, MVT::v16i8, V1, V2, Mask, DAG))
9450 // There are special ways we can lower some single-element blends.
9451 if (NumV2Elements == 1)
9452 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9453 Mask, Subtarget, DAG))
9456 if (SDValue BitBlend =
9457 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9460 // Check whether a compaction lowering can be done. This handles shuffles
9461 // which take every Nth element for some even N. See the helper function for
9464 // We special case these as they can be particularly efficiently handled with
9465 // the PACKUSB instruction on x86 and they show up in common patterns of
9466 // rearranging bytes to truncate wide elements.
9467 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9468 // NumEvenDrops is the power of two stride of the elements. Another way of
9469 // thinking about it is that we need to drop the even elements this many
9470 // times to get the original input.
9471 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9473 // First we need to zero all the dropped bytes.
9474 assert(NumEvenDrops <= 3 &&
9475 "No support for dropping even elements more than 3 times.");
9476 // We use the mask type to pick which bytes are preserved based on how many
9477 // elements are dropped.
9478 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9479 SDValue ByteClearMask = DAG.getBitcast(
9480 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9481 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9483 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9485 // Now pack things back together.
9486 V1 = DAG.getBitcast(MVT::v8i16, V1);
9487 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9488 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9489 for (int i = 1; i < NumEvenDrops; ++i) {
9490 Result = DAG.getBitcast(MVT::v8i16, Result);
9491 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9497 // Handle multi-input cases by blending single-input shuffles.
9498 if (NumV2Elements > 0)
9499 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9502 // The fallback path for single-input shuffles widens this into two v8i16
9503 // vectors with unpacks, shuffles those, and then pulls them back together
9507 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9508 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9509 for (int i = 0; i < 16; ++i)
9511 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9513 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9515 SDValue VLoHalf, VHiHalf;
9516 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9517 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9519 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9520 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9521 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9522 [](int M) { return M >= 0 && M % 2 == 1; })) {
9523 // Use a mask to drop the high bytes.
9524 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9525 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9526 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9528 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9529 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9531 // Squash the masks to point directly into VLoHalf.
9532 for (int &M : LoBlendMask)
9535 for (int &M : HiBlendMask)
9539 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9540 // VHiHalf so that we can blend them as i16s.
9541 VLoHalf = DAG.getBitcast(
9542 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9543 VHiHalf = DAG.getBitcast(
9544 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9547 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9548 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9550 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9553 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9555 /// This routine breaks down the specific type of 128-bit shuffle and
9556 /// dispatches to the lowering routines accordingly.
9557 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9558 MVT VT, const X86Subtarget *Subtarget,
9559 SelectionDAG &DAG) {
9560 switch (VT.SimpleTy) {
9562 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9564 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9566 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9568 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9570 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9572 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9575 llvm_unreachable("Unimplemented!");
9579 /// \brief Helper function to test whether a shuffle mask could be
9580 /// simplified by widening the elements being shuffled.
9582 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9583 /// leaves it in an unspecified state.
9585 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9586 /// shuffle masks. The latter have the special property of a '-2' representing
9587 /// a zero-ed lane of a vector.
9588 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9589 SmallVectorImpl<int> &WidenedMask) {
9590 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9591 // If both elements are undef, its trivial.
9592 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9593 WidenedMask.push_back(SM_SentinelUndef);
9597 // Check for an undef mask and a mask value properly aligned to fit with
9598 // a pair of values. If we find such a case, use the non-undef mask's value.
9599 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9600 WidenedMask.push_back(Mask[i + 1] / 2);
9603 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9604 WidenedMask.push_back(Mask[i] / 2);
9608 // When zeroing, we need to spread the zeroing across both lanes to widen.
9609 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9610 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9611 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9612 WidenedMask.push_back(SM_SentinelZero);
9618 // Finally check if the two mask values are adjacent and aligned with
9620 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9621 WidenedMask.push_back(Mask[i] / 2);
9625 // Otherwise we can't safely widen the elements used in this shuffle.
9628 assert(WidenedMask.size() == Mask.size() / 2 &&
9629 "Incorrect size of mask after widening the elements!");
9634 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9636 /// This routine just extracts two subvectors, shuffles them independently, and
9637 /// then concatenates them back together. This should work effectively with all
9638 /// AVX vector shuffle types.
9639 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9640 SDValue V2, ArrayRef<int> Mask,
9641 SelectionDAG &DAG) {
9642 assert(VT.getSizeInBits() >= 256 &&
9643 "Only for 256-bit or wider vector shuffles!");
9644 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9645 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9647 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9648 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9650 int NumElements = VT.getVectorNumElements();
9651 int SplitNumElements = NumElements / 2;
9652 MVT ScalarVT = VT.getScalarType();
9653 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9655 // Rather than splitting build-vectors, just build two narrower build
9656 // vectors. This helps shuffling with splats and zeros.
9657 auto SplitVector = [&](SDValue V) {
9658 while (V.getOpcode() == ISD::BITCAST)
9659 V = V->getOperand(0);
9661 MVT OrigVT = V.getSimpleValueType();
9662 int OrigNumElements = OrigVT.getVectorNumElements();
9663 int OrigSplitNumElements = OrigNumElements / 2;
9664 MVT OrigScalarVT = OrigVT.getScalarType();
9665 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9669 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9671 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9672 DAG.getIntPtrConstant(0, DL));
9673 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9674 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9677 SmallVector<SDValue, 16> LoOps, HiOps;
9678 for (int i = 0; i < OrigSplitNumElements; ++i) {
9679 LoOps.push_back(BV->getOperand(i));
9680 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9682 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9683 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9685 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9686 DAG.getBitcast(SplitVT, HiV));
9689 SDValue LoV1, HiV1, LoV2, HiV2;
9690 std::tie(LoV1, HiV1) = SplitVector(V1);
9691 std::tie(LoV2, HiV2) = SplitVector(V2);
9693 // Now create two 4-way blends of these half-width vectors.
9694 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9695 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9696 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9697 for (int i = 0; i < SplitNumElements; ++i) {
9698 int M = HalfMask[i];
9699 if (M >= NumElements) {
9700 if (M >= NumElements + SplitNumElements)
9704 V2BlendMask.push_back(M - NumElements);
9705 V1BlendMask.push_back(-1);
9706 BlendMask.push_back(SplitNumElements + i);
9707 } else if (M >= 0) {
9708 if (M >= SplitNumElements)
9712 V2BlendMask.push_back(-1);
9713 V1BlendMask.push_back(M);
9714 BlendMask.push_back(i);
9716 V2BlendMask.push_back(-1);
9717 V1BlendMask.push_back(-1);
9718 BlendMask.push_back(-1);
9722 // Because the lowering happens after all combining takes place, we need to
9723 // manually combine these blend masks as much as possible so that we create
9724 // a minimal number of high-level vector shuffle nodes.
9726 // First try just blending the halves of V1 or V2.
9727 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9728 return DAG.getUNDEF(SplitVT);
9729 if (!UseLoV2 && !UseHiV2)
9730 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9731 if (!UseLoV1 && !UseHiV1)
9732 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9734 SDValue V1Blend, V2Blend;
9735 if (UseLoV1 && UseHiV1) {
9737 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9739 // We only use half of V1 so map the usage down into the final blend mask.
9740 V1Blend = UseLoV1 ? LoV1 : HiV1;
9741 for (int i = 0; i < SplitNumElements; ++i)
9742 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9743 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9745 if (UseLoV2 && UseHiV2) {
9747 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9749 // We only use half of V2 so map the usage down into the final blend mask.
9750 V2Blend = UseLoV2 ? LoV2 : HiV2;
9751 for (int i = 0; i < SplitNumElements; ++i)
9752 if (BlendMask[i] >= SplitNumElements)
9753 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9755 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9757 SDValue Lo = HalfBlend(LoMask);
9758 SDValue Hi = HalfBlend(HiMask);
9759 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9762 /// \brief Either split a vector in halves or decompose the shuffles and the
9765 /// This is provided as a good fallback for many lowerings of non-single-input
9766 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9767 /// between splitting the shuffle into 128-bit components and stitching those
9768 /// back together vs. extracting the single-input shuffles and blending those
9770 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9771 SDValue V2, ArrayRef<int> Mask,
9772 SelectionDAG &DAG) {
9773 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9774 "lower single-input shuffles as it "
9775 "could then recurse on itself.");
9776 int Size = Mask.size();
9778 // If this can be modeled as a broadcast of two elements followed by a blend,
9779 // prefer that lowering. This is especially important because broadcasts can
9780 // often fold with memory operands.
9781 auto DoBothBroadcast = [&] {
9782 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9785 if (V2BroadcastIdx == -1)
9786 V2BroadcastIdx = M - Size;
9787 else if (M - Size != V2BroadcastIdx)
9789 } else if (M >= 0) {
9790 if (V1BroadcastIdx == -1)
9792 else if (M != V1BroadcastIdx)
9797 if (DoBothBroadcast())
9798 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9801 // If the inputs all stem from a single 128-bit lane of each input, then we
9802 // split them rather than blending because the split will decompose to
9803 // unusually few instructions.
9804 int LaneCount = VT.getSizeInBits() / 128;
9805 int LaneSize = Size / LaneCount;
9806 SmallBitVector LaneInputs[2];
9807 LaneInputs[0].resize(LaneCount, false);
9808 LaneInputs[1].resize(LaneCount, false);
9809 for (int i = 0; i < Size; ++i)
9811 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9812 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9813 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9815 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9816 // that the decomposed single-input shuffles don't end up here.
9817 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9820 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9821 /// a permutation and blend of those lanes.
9823 /// This essentially blends the out-of-lane inputs to each lane into the lane
9824 /// from a permuted copy of the vector. This lowering strategy results in four
9825 /// instructions in the worst case for a single-input cross lane shuffle which
9826 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9827 /// of. Special cases for each particular shuffle pattern should be handled
9828 /// prior to trying this lowering.
9829 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9830 SDValue V1, SDValue V2,
9832 SelectionDAG &DAG) {
9833 // FIXME: This should probably be generalized for 512-bit vectors as well.
9834 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9835 int LaneSize = Mask.size() / 2;
9837 // If there are only inputs from one 128-bit lane, splitting will in fact be
9838 // less expensive. The flags track whether the given lane contains an element
9839 // that crosses to another lane.
9840 bool LaneCrossing[2] = {false, false};
9841 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9842 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9843 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9844 if (!LaneCrossing[0] || !LaneCrossing[1])
9845 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9847 if (isSingleInputShuffleMask(Mask)) {
9848 SmallVector<int, 32> FlippedBlendMask;
9849 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9850 FlippedBlendMask.push_back(
9851 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9853 : Mask[i] % LaneSize +
9854 (i / LaneSize) * LaneSize + Size));
9856 // Flip the vector, and blend the results which should now be in-lane. The
9857 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9858 // 5 for the high source. The value 3 selects the high half of source 2 and
9859 // the value 2 selects the low half of source 2. We only use source 2 to
9860 // allow folding it into a memory operand.
9861 unsigned PERMMask = 3 | 2 << 4;
9862 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9863 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9864 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9867 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9868 // will be handled by the above logic and a blend of the results, much like
9869 // other patterns in AVX.
9870 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9873 /// \brief Handle lowering 2-lane 128-bit shuffles.
9874 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9875 SDValue V2, ArrayRef<int> Mask,
9876 const X86Subtarget *Subtarget,
9877 SelectionDAG &DAG) {
9878 // TODO: If minimizing size and one of the inputs is a zero vector and the
9879 // the zero vector has only one use, we could use a VPERM2X128 to save the
9880 // instruction bytes needed to explicitly generate the zero vector.
9882 // Blends are faster and handle all the non-lane-crossing cases.
9883 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9887 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9888 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9890 // If either input operand is a zero vector, use VPERM2X128 because its mask
9891 // allows us to replace the zero input with an implicit zero.
9892 if (!IsV1Zero && !IsV2Zero) {
9893 // Check for patterns which can be matched with a single insert of a 128-bit
9895 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9896 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9897 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9898 VT.getVectorNumElements() / 2);
9899 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9900 DAG.getIntPtrConstant(0, DL));
9901 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9902 OnlyUsesV1 ? V1 : V2,
9903 DAG.getIntPtrConstant(0, DL));
9904 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9908 // Otherwise form a 128-bit permutation. After accounting for undefs,
9909 // convert the 64-bit shuffle mask selection values into 128-bit
9910 // selection bits by dividing the indexes by 2 and shifting into positions
9911 // defined by a vperm2*128 instruction's immediate control byte.
9913 // The immediate permute control byte looks like this:
9914 // [1:0] - select 128 bits from sources for low half of destination
9916 // [3] - zero low half of destination
9917 // [5:4] - select 128 bits from sources for high half of destination
9919 // [7] - zero high half of destination
9921 int MaskLO = Mask[0];
9922 if (MaskLO == SM_SentinelUndef)
9923 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9925 int MaskHI = Mask[2];
9926 if (MaskHI == SM_SentinelUndef)
9927 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9929 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9931 // If either input is a zero vector, replace it with an undef input.
9932 // Shuffle mask values < 4 are selecting elements of V1.
9933 // Shuffle mask values >= 4 are selecting elements of V2.
9934 // Adjust each half of the permute mask by clearing the half that was
9935 // selecting the zero vector and setting the zero mask bit.
9937 V1 = DAG.getUNDEF(VT);
9939 PermMask = (PermMask & 0xf0) | 0x08;
9941 PermMask = (PermMask & 0x0f) | 0x80;
9944 V2 = DAG.getUNDEF(VT);
9946 PermMask = (PermMask & 0xf0) | 0x08;
9948 PermMask = (PermMask & 0x0f) | 0x80;
9951 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9952 DAG.getConstant(PermMask, DL, MVT::i8));
9955 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9956 /// shuffling each lane.
9958 /// This will only succeed when the result of fixing the 128-bit lanes results
9959 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9960 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9961 /// the lane crosses early and then use simpler shuffles within each lane.
9963 /// FIXME: It might be worthwhile at some point to support this without
9964 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9965 /// in x86 only floating point has interesting non-repeating shuffles, and even
9966 /// those are still *marginally* more expensive.
9967 static SDValue lowerVectorShuffleByMerging128BitLanes(
9968 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9969 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9970 assert(!isSingleInputShuffleMask(Mask) &&
9971 "This is only useful with multiple inputs.");
9973 int Size = Mask.size();
9974 int LaneSize = 128 / VT.getScalarSizeInBits();
9975 int NumLanes = Size / LaneSize;
9976 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9978 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9979 // check whether the in-128-bit lane shuffles share a repeating pattern.
9980 SmallVector<int, 4> Lanes;
9981 Lanes.resize(NumLanes, -1);
9982 SmallVector<int, 4> InLaneMask;
9983 InLaneMask.resize(LaneSize, -1);
9984 for (int i = 0; i < Size; ++i) {
9988 int j = i / LaneSize;
9991 // First entry we've seen for this lane.
9992 Lanes[j] = Mask[i] / LaneSize;
9993 } else if (Lanes[j] != Mask[i] / LaneSize) {
9994 // This doesn't match the lane selected previously!
9998 // Check that within each lane we have a consistent shuffle mask.
9999 int k = i % LaneSize;
10000 if (InLaneMask[k] < 0) {
10001 InLaneMask[k] = Mask[i] % LaneSize;
10002 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10003 // This doesn't fit a repeating in-lane mask.
10008 // First shuffle the lanes into place.
10009 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10010 VT.getSizeInBits() / 64);
10011 SmallVector<int, 8> LaneMask;
10012 LaneMask.resize(NumLanes * 2, -1);
10013 for (int i = 0; i < NumLanes; ++i)
10014 if (Lanes[i] >= 0) {
10015 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10016 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10019 V1 = DAG.getBitcast(LaneVT, V1);
10020 V2 = DAG.getBitcast(LaneVT, V2);
10021 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10023 // Cast it back to the type we actually want.
10024 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10026 // Now do a simple shuffle that isn't lane crossing.
10027 SmallVector<int, 8> NewMask;
10028 NewMask.resize(Size, -1);
10029 for (int i = 0; i < Size; ++i)
10031 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10032 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10033 "Must not introduce lane crosses at this point!");
10035 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10038 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10041 /// This returns true if the elements from a particular input are already in the
10042 /// slot required by the given mask and require no permutation.
10043 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10044 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10045 int Size = Mask.size();
10046 for (int i = 0; i < Size; ++i)
10047 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10053 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10054 ArrayRef<int> Mask, SDValue V1,
10055 SDValue V2, SelectionDAG &DAG) {
10057 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
10058 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
10059 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10060 int NumElts = VT.getVectorNumElements();
10061 bool ShufpdMask = true;
10062 bool CommutableMask = true;
10063 unsigned Immediate = 0;
10064 for (int i = 0; i < NumElts; ++i) {
10067 int Val = (i & 6) + NumElts * (i & 1);
10068 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10069 if (Mask[i] < Val || Mask[i] > Val + 1)
10070 ShufpdMask = false;
10071 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
10072 CommutableMask = false;
10073 Immediate |= (Mask[i] % 2) << i;
10076 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10077 DAG.getConstant(Immediate, DL, MVT::i8));
10078 if (CommutableMask)
10079 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10080 DAG.getConstant(Immediate, DL, MVT::i8));
10084 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10086 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10087 /// isn't available.
10088 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10089 const X86Subtarget *Subtarget,
10090 SelectionDAG &DAG) {
10092 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10093 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10094 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10095 ArrayRef<int> Mask = SVOp->getMask();
10096 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10098 SmallVector<int, 4> WidenedMask;
10099 if (canWidenShuffleElements(Mask, WidenedMask))
10100 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10103 if (isSingleInputShuffleMask(Mask)) {
10104 // Check for being able to broadcast a single element.
10105 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10106 Mask, Subtarget, DAG))
10109 // Use low duplicate instructions for masks that match their pattern.
10110 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10111 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10113 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10114 // Non-half-crossing single input shuffles can be lowerid with an
10115 // interleaved permutation.
10116 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10117 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10118 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10119 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10122 // With AVX2 we have direct support for this permutation.
10123 if (Subtarget->hasAVX2())
10124 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10125 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10127 // Otherwise, fall back.
10128 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10132 // X86 has dedicated unpack instructions that can handle specific blend
10133 // operations: UNPCKH and UNPCKL.
10134 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10135 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
10136 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10137 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
10138 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10139 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
10140 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10141 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
10143 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10147 // Check if the blend happens to exactly fit that of SHUFPD.
10149 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10152 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10153 // shuffle. However, if we have AVX2 and either inputs are already in place,
10154 // we will be able to shuffle even across lanes the other input in a single
10155 // instruction so skip this pattern.
10156 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10157 isShuffleMaskInputInPlace(1, Mask))))
10158 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10159 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10162 // If we have AVX2 then we always want to lower with a blend because an v4 we
10163 // can fully permute the elements.
10164 if (Subtarget->hasAVX2())
10165 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10168 // Otherwise fall back on generic lowering.
10169 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10172 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10174 /// This routine is only called when we have AVX2 and thus a reasonable
10175 /// instruction set for v4i64 shuffling..
10176 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10177 const X86Subtarget *Subtarget,
10178 SelectionDAG &DAG) {
10180 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10181 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10182 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10183 ArrayRef<int> Mask = SVOp->getMask();
10184 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10185 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10187 SmallVector<int, 4> WidenedMask;
10188 if (canWidenShuffleElements(Mask, WidenedMask))
10189 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10192 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10196 // Check for being able to broadcast a single element.
10197 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10198 Mask, Subtarget, DAG))
10201 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10202 // use lower latency instructions that will operate on both 128-bit lanes.
10203 SmallVector<int, 2> RepeatedMask;
10204 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10205 if (isSingleInputShuffleMask(Mask)) {
10206 int PSHUFDMask[] = {-1, -1, -1, -1};
10207 for (int i = 0; i < 2; ++i)
10208 if (RepeatedMask[i] >= 0) {
10209 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10210 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10212 return DAG.getBitcast(
10214 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10215 DAG.getBitcast(MVT::v8i32, V1),
10216 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10220 // AVX2 provides a direct instruction for permuting a single input across
10222 if (isSingleInputShuffleMask(Mask))
10223 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10224 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10226 // Try to use shift instructions.
10227 if (SDValue Shift =
10228 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10231 // Use dedicated unpack instructions for masks that match their pattern.
10232 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
10233 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
10234 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
10235 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
10236 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
10237 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
10238 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
10239 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
10241 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10242 // shuffle. However, if we have AVX2 and either inputs are already in place,
10243 // we will be able to shuffle even across lanes the other input in a single
10244 // instruction so skip this pattern.
10245 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10246 isShuffleMaskInputInPlace(1, Mask))))
10247 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10248 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10251 // Otherwise fall back on generic blend lowering.
10252 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10256 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10258 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10259 /// isn't available.
10260 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10261 const X86Subtarget *Subtarget,
10262 SelectionDAG &DAG) {
10264 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10265 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10266 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10267 ArrayRef<int> Mask = SVOp->getMask();
10268 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10270 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10274 // Check for being able to broadcast a single element.
10275 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10276 Mask, Subtarget, DAG))
10279 // If the shuffle mask is repeated in each 128-bit lane, we have many more
10280 // options to efficiently lower the shuffle.
10281 SmallVector<int, 4> RepeatedMask;
10282 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10283 assert(RepeatedMask.size() == 4 &&
10284 "Repeated masks must be half the mask width!");
10286 // Use even/odd duplicate instructions for masks that match their pattern.
10287 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10288 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10289 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10290 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10292 if (isSingleInputShuffleMask(Mask))
10293 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10294 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10296 // Use dedicated unpack instructions for masks that match their pattern.
10297 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10298 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10299 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10300 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10301 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10302 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10303 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10304 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10306 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10307 // have already handled any direct blends. We also need to squash the
10308 // repeated mask into a simulated v4f32 mask.
10309 for (int i = 0; i < 4; ++i)
10310 if (RepeatedMask[i] >= 8)
10311 RepeatedMask[i] -= 4;
10312 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10315 // If we have a single input shuffle with different shuffle patterns in the
10316 // two 128-bit lanes use the variable mask to VPERMILPS.
10317 if (isSingleInputShuffleMask(Mask)) {
10318 SDValue VPermMask[8];
10319 for (int i = 0; i < 8; ++i)
10320 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10321 : DAG.getConstant(Mask[i], DL, MVT::i32);
10322 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10323 return DAG.getNode(
10324 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10325 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10327 if (Subtarget->hasAVX2())
10328 return DAG.getNode(
10329 X86ISD::VPERMV, DL, MVT::v8f32,
10330 DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10331 MVT::v8i32, VPermMask)),
10334 // Otherwise, fall back.
10335 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10339 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10341 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10342 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10345 // If we have AVX2 then we always want to lower with a blend because at v8 we
10346 // can fully permute the elements.
10347 if (Subtarget->hasAVX2())
10348 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10351 // Otherwise fall back on generic lowering.
10352 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10355 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10357 /// This routine is only called when we have AVX2 and thus a reasonable
10358 /// instruction set for v8i32 shuffling..
10359 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10360 const X86Subtarget *Subtarget,
10361 SelectionDAG &DAG) {
10363 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10364 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10365 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10366 ArrayRef<int> Mask = SVOp->getMask();
10367 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10368 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10370 // Whenever we can lower this as a zext, that instruction is strictly faster
10371 // than any alternative. It also allows us to fold memory operands into the
10372 // shuffle in many cases.
10373 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10374 Mask, Subtarget, DAG))
10377 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10381 // Check for being able to broadcast a single element.
10382 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10383 Mask, Subtarget, DAG))
10386 // If the shuffle mask is repeated in each 128-bit lane we can use more
10387 // efficient instructions that mirror the shuffles across the two 128-bit
10389 SmallVector<int, 4> RepeatedMask;
10390 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10391 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10392 if (isSingleInputShuffleMask(Mask))
10393 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10394 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10396 // Use dedicated unpack instructions for masks that match their pattern.
10397 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10398 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10399 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10400 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10401 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10402 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10403 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10404 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10407 // Try to use shift instructions.
10408 if (SDValue Shift =
10409 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10412 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10413 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10416 // If the shuffle patterns aren't repeated but it is a single input, directly
10417 // generate a cross-lane VPERMD instruction.
10418 if (isSingleInputShuffleMask(Mask)) {
10419 SDValue VPermMask[8];
10420 for (int i = 0; i < 8; ++i)
10421 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10422 : DAG.getConstant(Mask[i], DL, MVT::i32);
10423 return DAG.getNode(
10424 X86ISD::VPERMV, DL, MVT::v8i32,
10425 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10428 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10430 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10431 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10434 // Otherwise fall back on generic blend lowering.
10435 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10439 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10441 /// This routine is only called when we have AVX2 and thus a reasonable
10442 /// instruction set for v16i16 shuffling..
10443 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10444 const X86Subtarget *Subtarget,
10445 SelectionDAG &DAG) {
10447 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10448 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10449 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10450 ArrayRef<int> Mask = SVOp->getMask();
10451 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10452 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10454 // Whenever we can lower this as a zext, that instruction is strictly faster
10455 // than any alternative. It also allows us to fold memory operands into the
10456 // shuffle in many cases.
10457 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10458 Mask, Subtarget, DAG))
10461 // Check for being able to broadcast a single element.
10462 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10463 Mask, Subtarget, DAG))
10466 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10470 // Use dedicated unpack instructions for masks that match their pattern.
10471 if (isShuffleEquivalent(V1, V2, Mask,
10472 {// First 128-bit lane:
10473 0, 16, 1, 17, 2, 18, 3, 19,
10474 // Second 128-bit lane:
10475 8, 24, 9, 25, 10, 26, 11, 27}))
10476 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10477 if (isShuffleEquivalent(V1, V2, Mask,
10478 {// First 128-bit lane:
10479 4, 20, 5, 21, 6, 22, 7, 23,
10480 // Second 128-bit lane:
10481 12, 28, 13, 29, 14, 30, 15, 31}))
10482 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10484 // Try to use shift instructions.
10485 if (SDValue Shift =
10486 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10489 // Try to use byte rotation instructions.
10490 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10491 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10494 if (isSingleInputShuffleMask(Mask)) {
10495 // There are no generalized cross-lane shuffle operations available on i16
10497 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10498 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10501 SmallVector<int, 8> RepeatedMask;
10502 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10503 // As this is a single-input shuffle, the repeated mask should be
10504 // a strictly valid v8i16 mask that we can pass through to the v8i16
10505 // lowering to handle even the v16 case.
10506 return lowerV8I16GeneralSingleInputVectorShuffle(
10507 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10510 SDValue PSHUFBMask[32];
10511 for (int i = 0; i < 16; ++i) {
10512 if (Mask[i] == -1) {
10513 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10517 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10518 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10519 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10520 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10522 return DAG.getBitcast(MVT::v16i16,
10523 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10524 DAG.getBitcast(MVT::v32i8, V1),
10525 DAG.getNode(ISD::BUILD_VECTOR, DL,
10526 MVT::v32i8, PSHUFBMask)));
10529 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10531 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10532 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10535 // Otherwise fall back on generic lowering.
10536 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10539 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10541 /// This routine is only called when we have AVX2 and thus a reasonable
10542 /// instruction set for v32i8 shuffling..
10543 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10544 const X86Subtarget *Subtarget,
10545 SelectionDAG &DAG) {
10547 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10548 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10549 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10550 ArrayRef<int> Mask = SVOp->getMask();
10551 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10552 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10554 // Whenever we can lower this as a zext, that instruction is strictly faster
10555 // than any alternative. It also allows us to fold memory operands into the
10556 // shuffle in many cases.
10557 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10558 Mask, Subtarget, DAG))
10561 // Check for being able to broadcast a single element.
10562 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10563 Mask, Subtarget, DAG))
10566 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10570 // Use dedicated unpack instructions for masks that match their pattern.
10571 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10573 if (isShuffleEquivalent(
10575 {// First 128-bit lane:
10576 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10577 // Second 128-bit lane:
10578 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10579 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10580 if (isShuffleEquivalent(
10582 {// First 128-bit lane:
10583 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10584 // Second 128-bit lane:
10585 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10586 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10588 // Try to use shift instructions.
10589 if (SDValue Shift =
10590 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10593 // Try to use byte rotation instructions.
10594 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10595 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10598 if (isSingleInputShuffleMask(Mask)) {
10599 // There are no generalized cross-lane shuffle operations available on i8
10601 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10602 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10605 SDValue PSHUFBMask[32];
10606 for (int i = 0; i < 32; ++i)
10609 ? DAG.getUNDEF(MVT::i8)
10610 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10613 return DAG.getNode(
10614 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10615 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10618 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10620 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10621 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10624 // Otherwise fall back on generic lowering.
10625 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10628 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10630 /// This routine either breaks down the specific type of a 256-bit x86 vector
10631 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10632 /// together based on the available instructions.
10633 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10634 MVT VT, const X86Subtarget *Subtarget,
10635 SelectionDAG &DAG) {
10637 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10638 ArrayRef<int> Mask = SVOp->getMask();
10640 // If we have a single input to the zero element, insert that into V1 if we
10641 // can do so cheaply.
10642 int NumElts = VT.getVectorNumElements();
10643 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10644 return M >= NumElts;
10647 if (NumV2Elements == 1 && Mask[0] >= NumElts)
10648 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10649 DL, VT, V1, V2, Mask, Subtarget, DAG))
10652 // There is a really nice hard cut-over between AVX1 and AVX2 that means we
10653 // can check for those subtargets here and avoid much of the subtarget
10654 // querying in the per-vector-type lowering routines. With AVX1 we have
10655 // essentially *zero* ability to manipulate a 256-bit vector with integer
10656 // types. Since we'll use floating point types there eventually, just
10657 // immediately cast everything to a float and operate entirely in that domain.
10658 if (VT.isInteger() && !Subtarget->hasAVX2()) {
10659 int ElementBits = VT.getScalarSizeInBits();
10660 if (ElementBits < 32)
10661 // No floating point type available, decompose into 128-bit vectors.
10662 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10664 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10665 VT.getVectorNumElements());
10666 V1 = DAG.getBitcast(FpVT, V1);
10667 V2 = DAG.getBitcast(FpVT, V2);
10668 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10671 switch (VT.SimpleTy) {
10673 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10675 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10677 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10679 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10681 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10683 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10686 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10690 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10691 ArrayRef<int> Mask, SDValue V1,
10692 SDValue V2, SelectionDAG &DAG) {
10694 assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10696 MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10697 MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10699 SmallVector<SDValue, 32> VPermMask;
10700 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i)
10701 VPermMask.push_back(Mask[i] < 0 ? DAG.getUNDEF(MaskEltVT) :
10702 DAG.getConstant(Mask[i], DL, MaskEltVT));
10703 SDValue MaskNode = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVecVT,
10705 if (isSingleInputShuffleMask(Mask))
10706 return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10708 return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10711 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10712 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10713 const X86Subtarget *Subtarget,
10714 SelectionDAG &DAG) {
10716 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10717 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10718 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10719 ArrayRef<int> Mask = SVOp->getMask();
10720 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10722 if (SDValue Unpck =
10723 lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10726 return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10729 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10730 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10731 const X86Subtarget *Subtarget,
10732 SelectionDAG &DAG) {
10734 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10735 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10736 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10737 ArrayRef<int> Mask = SVOp->getMask();
10738 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10740 if (SDValue Unpck =
10741 lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
10744 return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
10747 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10748 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10749 const X86Subtarget *Subtarget,
10750 SelectionDAG &DAG) {
10752 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10753 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10754 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10755 ArrayRef<int> Mask = SVOp->getMask();
10756 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10758 if (SDValue Unpck =
10759 lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
10762 return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
10765 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10766 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10767 const X86Subtarget *Subtarget,
10768 SelectionDAG &DAG) {
10770 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10771 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10772 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10773 ArrayRef<int> Mask = SVOp->getMask();
10774 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10776 if (SDValue Unpck =
10777 lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
10780 return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
10783 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10784 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10785 const X86Subtarget *Subtarget,
10786 SelectionDAG &DAG) {
10788 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10789 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10790 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10791 ArrayRef<int> Mask = SVOp->getMask();
10792 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10793 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10795 return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
10798 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10799 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10800 const X86Subtarget *Subtarget,
10801 SelectionDAG &DAG) {
10803 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10804 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10805 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10806 ArrayRef<int> Mask = SVOp->getMask();
10807 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10808 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10810 // FIXME: Implement direct support for this type!
10811 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10814 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10816 /// This routine either breaks down the specific type of a 512-bit x86 vector
10817 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10818 /// together based on the available instructions.
10819 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10820 MVT VT, const X86Subtarget *Subtarget,
10821 SelectionDAG &DAG) {
10823 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10824 ArrayRef<int> Mask = SVOp->getMask();
10825 assert(Subtarget->hasAVX512() &&
10826 "Cannot lower 512-bit vectors w/ basic ISA!");
10828 // Check for being able to broadcast a single element.
10829 if (SDValue Broadcast =
10830 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10833 // Dispatch to each element type for lowering. If we don't have supprot for
10834 // specific element type shuffles at 512 bits, immediately split them and
10835 // lower them. Each lowering routine of a given type is allowed to assume that
10836 // the requisite ISA extensions for that element type are available.
10837 switch (VT.SimpleTy) {
10839 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10841 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10843 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10845 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10847 if (Subtarget->hasBWI())
10848 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10851 if (Subtarget->hasBWI())
10852 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10856 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10859 // Otherwise fall back on splitting.
10860 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10863 // Lower vXi1 vector shuffles.
10864 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
10865 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
10866 // vector, shuffle and then truncate it back.
10867 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10868 MVT VT, const X86Subtarget *Subtarget,
10869 SelectionDAG &DAG) {
10871 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10872 ArrayRef<int> Mask = SVOp->getMask();
10873 assert(Subtarget->hasAVX512() &&
10874 "Cannot lower 512-bit vectors w/o basic ISA!");
10876 switch (VT.SimpleTy) {
10878 assert(false && "Expected a vector of i1 elements");
10881 ExtVT = MVT::v2i64;
10884 ExtVT = MVT::v4i32;
10887 ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
10890 ExtVT = MVT::v16i32;
10893 ExtVT = MVT::v32i16;
10896 ExtVT = MVT::v64i8;
10900 if (ISD::isBuildVectorAllZeros(V1.getNode()))
10901 V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10902 else if (ISD::isBuildVectorAllOnes(V1.getNode()))
10903 V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10905 V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
10908 V2 = DAG.getUNDEF(ExtVT);
10909 else if (ISD::isBuildVectorAllZeros(V2.getNode()))
10910 V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
10911 else if (ISD::isBuildVectorAllOnes(V2.getNode()))
10912 V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
10914 V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
10915 return DAG.getNode(ISD::TRUNCATE, DL, VT,
10916 DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
10918 /// \brief Top-level lowering for x86 vector shuffles.
10920 /// This handles decomposition, canonicalization, and lowering of all x86
10921 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10922 /// above in helper routines. The canonicalization attempts to widen shuffles
10923 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10924 /// s.t. only one of the two inputs needs to be tested, etc.
10925 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10926 SelectionDAG &DAG) {
10927 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10928 ArrayRef<int> Mask = SVOp->getMask();
10929 SDValue V1 = Op.getOperand(0);
10930 SDValue V2 = Op.getOperand(1);
10931 MVT VT = Op.getSimpleValueType();
10932 int NumElements = VT.getVectorNumElements();
10934 bool Is1BitVector = (VT.getScalarType() == MVT::i1);
10936 assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
10937 "Can't lower MMX shuffles");
10939 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10940 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10941 if (V1IsUndef && V2IsUndef)
10942 return DAG.getUNDEF(VT);
10944 // When we create a shuffle node we put the UNDEF node to second operand,
10945 // but in some cases the first operand may be transformed to UNDEF.
10946 // In this case we should just commute the node.
10948 return DAG.getCommutedVectorShuffle(*SVOp);
10950 // Check for non-undef masks pointing at an undef vector and make the masks
10951 // undef as well. This makes it easier to match the shuffle based solely on
10955 if (M >= NumElements) {
10956 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10957 for (int &M : NewMask)
10958 if (M >= NumElements)
10960 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10963 // We actually see shuffles that are entirely re-arrangements of a set of
10964 // zero inputs. This mostly happens while decomposing complex shuffles into
10965 // simple ones. Directly lower these as a buildvector of zeros.
10966 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10967 if (Zeroable.all())
10968 return getZeroVector(VT, Subtarget, DAG, dl);
10970 // Try to collapse shuffles into using a vector type with fewer elements but
10971 // wider element types. We cap this to not form integers or floating point
10972 // elements wider than 64 bits, but it might be interesting to form i128
10973 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10974 SmallVector<int, 16> WidenedMask;
10975 if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
10976 canWidenShuffleElements(Mask, WidenedMask)) {
10977 MVT NewEltVT = VT.isFloatingPoint()
10978 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10979 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10980 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10981 // Make sure that the new vector type is legal. For example, v2f64 isn't
10983 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10984 V1 = DAG.getBitcast(NewVT, V1);
10985 V2 = DAG.getBitcast(NewVT, V2);
10986 return DAG.getBitcast(
10987 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10991 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10992 for (int M : SVOp->getMask())
10994 ++NumUndefElements;
10995 else if (M < NumElements)
11000 // Commute the shuffle as needed such that more elements come from V1 than
11001 // V2. This allows us to match the shuffle pattern strictly on how many
11002 // elements come from V1 without handling the symmetric cases.
11003 if (NumV2Elements > NumV1Elements)
11004 return DAG.getCommutedVectorShuffle(*SVOp);
11006 // When the number of V1 and V2 elements are the same, try to minimize the
11007 // number of uses of V2 in the low half of the vector. When that is tied,
11008 // ensure that the sum of indices for V1 is equal to or lower than the sum
11009 // indices for V2. When those are equal, try to ensure that the number of odd
11010 // indices for V1 is lower than the number of odd indices for V2.
11011 if (NumV1Elements == NumV2Elements) {
11012 int LowV1Elements = 0, LowV2Elements = 0;
11013 for (int M : SVOp->getMask().slice(0, NumElements / 2))
11014 if (M >= NumElements)
11018 if (LowV2Elements > LowV1Elements) {
11019 return DAG.getCommutedVectorShuffle(*SVOp);
11020 } else if (LowV2Elements == LowV1Elements) {
11021 int SumV1Indices = 0, SumV2Indices = 0;
11022 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11023 if (SVOp->getMask()[i] >= NumElements)
11025 else if (SVOp->getMask()[i] >= 0)
11027 if (SumV2Indices < SumV1Indices) {
11028 return DAG.getCommutedVectorShuffle(*SVOp);
11029 } else if (SumV2Indices == SumV1Indices) {
11030 int NumV1OddIndices = 0, NumV2OddIndices = 0;
11031 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11032 if (SVOp->getMask()[i] >= NumElements)
11033 NumV2OddIndices += i % 2;
11034 else if (SVOp->getMask()[i] >= 0)
11035 NumV1OddIndices += i % 2;
11036 if (NumV2OddIndices < NumV1OddIndices)
11037 return DAG.getCommutedVectorShuffle(*SVOp);
11042 // For each vector width, delegate to a specialized lowering routine.
11043 if (VT.getSizeInBits() == 128)
11044 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11046 if (VT.getSizeInBits() == 256)
11047 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11049 if (VT.getSizeInBits() == 512)
11050 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11053 return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11054 llvm_unreachable("Unimplemented!");
11057 // This function assumes its argument is a BUILD_VECTOR of constants or
11058 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11060 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11061 unsigned &MaskValue) {
11063 unsigned NumElems = BuildVector->getNumOperands();
11064 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11065 unsigned NumLanes = (NumElems - 1) / 8 + 1;
11066 unsigned NumElemsInLane = NumElems / NumLanes;
11068 // Blend for v16i16 should be symmetric for the both lanes.
11069 for (unsigned i = 0; i < NumElemsInLane; ++i) {
11070 SDValue EltCond = BuildVector->getOperand(i);
11071 SDValue SndLaneEltCond =
11072 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11074 int Lane1Cond = -1, Lane2Cond = -1;
11075 if (isa<ConstantSDNode>(EltCond))
11076 Lane1Cond = !isZero(EltCond);
11077 if (isa<ConstantSDNode>(SndLaneEltCond))
11078 Lane2Cond = !isZero(SndLaneEltCond);
11080 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11081 // Lane1Cond != 0, means we want the first argument.
11082 // Lane1Cond == 0, means we want the second argument.
11083 // The encoding of this argument is 0 for the first argument, 1
11084 // for the second. Therefore, invert the condition.
11085 MaskValue |= !Lane1Cond << i;
11086 else if (Lane1Cond < 0)
11087 MaskValue |= !Lane2Cond << i;
11094 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11095 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11096 const X86Subtarget *Subtarget,
11097 SelectionDAG &DAG) {
11098 SDValue Cond = Op.getOperand(0);
11099 SDValue LHS = Op.getOperand(1);
11100 SDValue RHS = Op.getOperand(2);
11102 MVT VT = Op.getSimpleValueType();
11104 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11106 auto *CondBV = cast<BuildVectorSDNode>(Cond);
11108 // Only non-legal VSELECTs reach this lowering, convert those into generic
11109 // shuffles and re-use the shuffle lowering path for blends.
11110 SmallVector<int, 32> Mask;
11111 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11112 SDValue CondElt = CondBV->getOperand(i);
11114 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
11116 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11119 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11120 // A vselect where all conditions and data are constants can be optimized into
11121 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11122 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11123 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11124 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11127 // Try to lower this to a blend-style vector shuffle. This can handle all
11128 // constant condition cases.
11129 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11132 // Variable blends are only legal from SSE4.1 onward.
11133 if (!Subtarget->hasSSE41())
11136 // Only some types will be legal on some subtargets. If we can emit a legal
11137 // VSELECT-matching blend, return Op, and but if we need to expand, return
11139 switch (Op.getSimpleValueType().SimpleTy) {
11141 // Most of the vector types have blends past SSE4.1.
11145 // The byte blends for AVX vectors were introduced only in AVX2.
11146 if (Subtarget->hasAVX2())
11153 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11154 if (Subtarget->hasBWI() && Subtarget->hasVLX())
11157 // FIXME: We should custom lower this by fixing the condition and using i8
11163 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11164 MVT VT = Op.getSimpleValueType();
11167 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11170 if (VT.getSizeInBits() == 8) {
11171 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11172 Op.getOperand(0), Op.getOperand(1));
11173 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11174 DAG.getValueType(VT));
11175 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11178 if (VT.getSizeInBits() == 16) {
11179 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11180 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11182 return DAG.getNode(
11183 ISD::TRUNCATE, dl, MVT::i16,
11184 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11185 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11186 Op.getOperand(1)));
11187 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11188 Op.getOperand(0), Op.getOperand(1));
11189 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11190 DAG.getValueType(VT));
11191 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11194 if (VT == MVT::f32) {
11195 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11196 // the result back to FR32 register. It's only worth matching if the
11197 // result has a single use which is a store or a bitcast to i32. And in
11198 // the case of a store, it's not worth it if the index is a constant 0,
11199 // because a MOVSSmr can be used instead, which is smaller and faster.
11200 if (!Op.hasOneUse())
11202 SDNode *User = *Op.getNode()->use_begin();
11203 if ((User->getOpcode() != ISD::STORE ||
11204 (isa<ConstantSDNode>(Op.getOperand(1)) &&
11205 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11206 (User->getOpcode() != ISD::BITCAST ||
11207 User->getValueType(0) != MVT::i32))
11209 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11210 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11212 return DAG.getBitcast(MVT::f32, Extract);
11215 if (VT == MVT::i32 || VT == MVT::i64) {
11216 // ExtractPS/pextrq works with constant index.
11217 if (isa<ConstantSDNode>(Op.getOperand(1)))
11223 /// Extract one bit from mask vector, like v16i1 or v8i1.
11224 /// AVX-512 feature.
11226 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11227 SDValue Vec = Op.getOperand(0);
11229 MVT VecVT = Vec.getSimpleValueType();
11230 SDValue Idx = Op.getOperand(1);
11231 MVT EltVT = Op.getSimpleValueType();
11233 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11234 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11235 "Unexpected vector type in ExtractBitFromMaskVector");
11237 // variable index can't be handled in mask registers,
11238 // extend vector to VR512
11239 if (!isa<ConstantSDNode>(Idx)) {
11240 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11241 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11242 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11243 ExtVT.getVectorElementType(), Ext, Idx);
11244 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11247 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11248 const TargetRegisterClass* rc = getRegClassFor(VecVT);
11249 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11250 rc = getRegClassFor(MVT::v16i1);
11251 unsigned MaxSift = rc->getSize()*8 - 1;
11252 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11253 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11254 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11255 DAG.getConstant(MaxSift, dl, MVT::i8));
11256 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11257 DAG.getIntPtrConstant(0, dl));
11261 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11262 SelectionDAG &DAG) const {
11264 SDValue Vec = Op.getOperand(0);
11265 MVT VecVT = Vec.getSimpleValueType();
11266 SDValue Idx = Op.getOperand(1);
11268 if (Op.getSimpleValueType() == MVT::i1)
11269 return ExtractBitFromMaskVector(Op, DAG);
11271 if (!isa<ConstantSDNode>(Idx)) {
11272 if (VecVT.is512BitVector() ||
11273 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11274 VecVT.getVectorElementType().getSizeInBits() == 32)) {
11277 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11278 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11279 MaskEltVT.getSizeInBits());
11281 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11282 auto PtrVT = getPointerTy(DAG.getDataLayout());
11283 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11284 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11285 DAG.getConstant(0, dl, PtrVT));
11286 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11287 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11288 DAG.getConstant(0, dl, PtrVT));
11293 // If this is a 256-bit vector result, first extract the 128-bit vector and
11294 // then extract the element from the 128-bit vector.
11295 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11297 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11298 // Get the 128-bit vector.
11299 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11300 MVT EltVT = VecVT.getVectorElementType();
11302 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11304 //if (IdxVal >= NumElems/2)
11305 // IdxVal -= NumElems/2;
11306 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11307 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11308 DAG.getConstant(IdxVal, dl, MVT::i32));
11311 assert(VecVT.is128BitVector() && "Unexpected vector length");
11313 if (Subtarget->hasSSE41())
11314 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11317 MVT VT = Op.getSimpleValueType();
11318 // TODO: handle v16i8.
11319 if (VT.getSizeInBits() == 16) {
11320 SDValue Vec = Op.getOperand(0);
11321 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11323 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11324 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11325 DAG.getBitcast(MVT::v4i32, Vec),
11326 Op.getOperand(1)));
11327 // Transform it so it match pextrw which produces a 32-bit result.
11328 MVT EltVT = MVT::i32;
11329 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11330 Op.getOperand(0), Op.getOperand(1));
11331 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11332 DAG.getValueType(VT));
11333 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11336 if (VT.getSizeInBits() == 32) {
11337 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11341 // SHUFPS the element to the lowest double word, then movss.
11342 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11343 MVT VVT = Op.getOperand(0).getSimpleValueType();
11344 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11345 DAG.getUNDEF(VVT), Mask);
11346 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11347 DAG.getIntPtrConstant(0, dl));
11350 if (VT.getSizeInBits() == 64) {
11351 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11352 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11353 // to match extract_elt for f64.
11354 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11358 // UNPCKHPD the element to the lowest double word, then movsd.
11359 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11360 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11361 int Mask[2] = { 1, -1 };
11362 MVT VVT = Op.getOperand(0).getSimpleValueType();
11363 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11364 DAG.getUNDEF(VVT), Mask);
11365 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11366 DAG.getIntPtrConstant(0, dl));
11372 /// Insert one bit to mask vector, like v16i1 or v8i1.
11373 /// AVX-512 feature.
11375 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11377 SDValue Vec = Op.getOperand(0);
11378 SDValue Elt = Op.getOperand(1);
11379 SDValue Idx = Op.getOperand(2);
11380 MVT VecVT = Vec.getSimpleValueType();
11382 if (!isa<ConstantSDNode>(Idx)) {
11383 // Non constant index. Extend source and destination,
11384 // insert element and then truncate the result.
11385 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11386 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
11387 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11388 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11389 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11390 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11393 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11394 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11396 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11397 DAG.getConstant(IdxVal, dl, MVT::i8));
11398 if (Vec.getOpcode() == ISD::UNDEF)
11400 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11403 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11404 SelectionDAG &DAG) const {
11405 MVT VT = Op.getSimpleValueType();
11406 MVT EltVT = VT.getVectorElementType();
11408 if (EltVT == MVT::i1)
11409 return InsertBitToMaskVector(Op, DAG);
11412 SDValue N0 = Op.getOperand(0);
11413 SDValue N1 = Op.getOperand(1);
11414 SDValue N2 = Op.getOperand(2);
11415 if (!isa<ConstantSDNode>(N2))
11417 auto *N2C = cast<ConstantSDNode>(N2);
11418 unsigned IdxVal = N2C->getZExtValue();
11420 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11421 // into that, and then insert the subvector back into the result.
11422 if (VT.is256BitVector() || VT.is512BitVector()) {
11423 // With a 256-bit vector, we can insert into the zero element efficiently
11424 // using a blend if we have AVX or AVX2 and the right data type.
11425 if (VT.is256BitVector() && IdxVal == 0) {
11426 // TODO: It is worthwhile to cast integer to floating point and back
11427 // and incur a domain crossing penalty if that's what we'll end up
11428 // doing anyway after extracting to a 128-bit vector.
11429 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11430 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11431 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11432 N2 = DAG.getIntPtrConstant(1, dl);
11433 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11437 // Get the desired 128-bit vector chunk.
11438 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11440 // Insert the element into the desired chunk.
11441 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11442 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11444 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11445 DAG.getConstant(IdxIn128, dl, MVT::i32));
11447 // Insert the changed part back into the bigger vector
11448 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11450 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11452 if (Subtarget->hasSSE41()) {
11453 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11455 if (VT == MVT::v8i16) {
11456 Opc = X86ISD::PINSRW;
11458 assert(VT == MVT::v16i8);
11459 Opc = X86ISD::PINSRB;
11462 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11464 if (N1.getValueType() != MVT::i32)
11465 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11466 if (N2.getValueType() != MVT::i32)
11467 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11468 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11471 if (EltVT == MVT::f32) {
11472 // Bits [7:6] of the constant are the source select. This will always be
11473 // zero here. The DAG Combiner may combine an extract_elt index into
11474 // these bits. For example (insert (extract, 3), 2) could be matched by
11475 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11476 // Bits [5:4] of the constant are the destination select. This is the
11477 // value of the incoming immediate.
11478 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11479 // combine either bitwise AND or insert of float 0.0 to set these bits.
11481 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11482 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11483 // If this is an insertion of 32-bits into the low 32-bits of
11484 // a vector, we prefer to generate a blend with immediate rather
11485 // than an insertps. Blends are simpler operations in hardware and so
11486 // will always have equal or better performance than insertps.
11487 // But if optimizing for size and there's a load folding opportunity,
11488 // generate insertps because blendps does not have a 32-bit memory
11490 N2 = DAG.getIntPtrConstant(1, dl);
11491 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11492 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11494 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11495 // Create this as a scalar to vector..
11496 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11497 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11500 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11501 // PINSR* works with constant index.
11506 if (EltVT == MVT::i8)
11509 if (EltVT.getSizeInBits() == 16) {
11510 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11511 // as its second argument.
11512 if (N1.getValueType() != MVT::i32)
11513 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11514 if (N2.getValueType() != MVT::i32)
11515 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11516 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11521 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11523 MVT OpVT = Op.getSimpleValueType();
11525 // If this is a 256-bit vector result, first insert into a 128-bit
11526 // vector and then insert into the 256-bit vector.
11527 if (!OpVT.is128BitVector()) {
11528 // Insert into a 128-bit vector.
11529 unsigned SizeFactor = OpVT.getSizeInBits()/128;
11530 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11531 OpVT.getVectorNumElements() / SizeFactor);
11533 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11535 // Insert the 128-bit vector.
11536 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11539 if (OpVT == MVT::v1i64 &&
11540 Op.getOperand(0).getValueType() == MVT::i64)
11541 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11543 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11544 assert(OpVT.is128BitVector() && "Expected an SSE type!");
11545 return DAG.getBitcast(
11546 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11549 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
11550 // a simple subregister reference or explicit instructions to grab
11551 // upper bits of a vector.
11552 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11553 SelectionDAG &DAG) {
11555 SDValue In = Op.getOperand(0);
11556 SDValue Idx = Op.getOperand(1);
11557 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11558 MVT ResVT = Op.getSimpleValueType();
11559 MVT InVT = In.getSimpleValueType();
11561 if (Subtarget->hasFp256()) {
11562 if (ResVT.is128BitVector() &&
11563 (InVT.is256BitVector() || InVT.is512BitVector()) &&
11564 isa<ConstantSDNode>(Idx)) {
11565 return Extract128BitVector(In, IdxVal, DAG, dl);
11567 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11568 isa<ConstantSDNode>(Idx)) {
11569 return Extract256BitVector(In, IdxVal, DAG, dl);
11575 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
11576 // simple superregister reference or explicit instructions to insert
11577 // the upper bits of a vector.
11578 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11579 SelectionDAG &DAG) {
11580 if (!Subtarget->hasAVX())
11584 SDValue Vec = Op.getOperand(0);
11585 SDValue SubVec = Op.getOperand(1);
11586 SDValue Idx = Op.getOperand(2);
11588 if (!isa<ConstantSDNode>(Idx))
11591 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11592 MVT OpVT = Op.getSimpleValueType();
11593 MVT SubVecVT = SubVec.getSimpleValueType();
11595 // Fold two 16-byte subvector loads into one 32-byte load:
11596 // (insert_subvector (insert_subvector undef, (load addr), 0),
11597 // (load addr + 16), Elts/2)
11599 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11600 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11601 OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11602 auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11603 if (Idx2 && Idx2->getZExtValue() == 0) {
11604 SDValue SubVec2 = Vec.getOperand(1);
11605 // If needed, look through a bitcast to get to the load.
11606 if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11607 SubVec2 = SubVec2.getOperand(0);
11609 if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11611 unsigned Alignment = FirstLd->getAlignment();
11612 unsigned AS = FirstLd->getAddressSpace();
11613 const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11614 if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11615 OpVT, AS, Alignment, &Fast) && Fast) {
11616 SDValue Ops[] = { SubVec2, SubVec };
11617 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11624 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11625 SubVecVT.is128BitVector())
11626 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11628 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11629 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11631 if (OpVT.getVectorElementType() == MVT::i1) {
11632 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11634 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11635 SDValue Undef = DAG.getUNDEF(OpVT);
11636 unsigned NumElems = OpVT.getVectorNumElements();
11637 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11639 if (IdxVal == OpVT.getVectorNumElements() / 2) {
11640 // Zero upper bits of the Vec
11641 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11642 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11644 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11646 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11647 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11650 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11652 // Zero upper bits of the Vec2
11653 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11654 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11655 // Zero lower bits of the Vec
11656 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11657 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11658 // Merge them together
11659 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11665 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11666 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11667 // one of the above mentioned nodes. It has to be wrapped because otherwise
11668 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11669 // be used to form addressing mode. These wrapped nodes will be selected
11672 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11673 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11675 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11676 // global base reg.
11677 unsigned char OpFlag = 0;
11678 unsigned WrapperKind = X86ISD::Wrapper;
11679 CodeModel::Model M = DAG.getTarget().getCodeModel();
11681 if (Subtarget->isPICStyleRIPRel() &&
11682 (M == CodeModel::Small || M == CodeModel::Kernel))
11683 WrapperKind = X86ISD::WrapperRIP;
11684 else if (Subtarget->isPICStyleGOT())
11685 OpFlag = X86II::MO_GOTOFF;
11686 else if (Subtarget->isPICStyleStubPIC())
11687 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11689 auto PtrVT = getPointerTy(DAG.getDataLayout());
11690 SDValue Result = DAG.getTargetConstantPool(
11691 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11693 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11694 // With PIC, the address is actually $g + Offset.
11697 DAG.getNode(ISD::ADD, DL, PtrVT,
11698 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11704 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11705 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11707 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11708 // global base reg.
11709 unsigned char OpFlag = 0;
11710 unsigned WrapperKind = X86ISD::Wrapper;
11711 CodeModel::Model M = DAG.getTarget().getCodeModel();
11713 if (Subtarget->isPICStyleRIPRel() &&
11714 (M == CodeModel::Small || M == CodeModel::Kernel))
11715 WrapperKind = X86ISD::WrapperRIP;
11716 else if (Subtarget->isPICStyleGOT())
11717 OpFlag = X86II::MO_GOTOFF;
11718 else if (Subtarget->isPICStyleStubPIC())
11719 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11721 auto PtrVT = getPointerTy(DAG.getDataLayout());
11722 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11724 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11726 // With PIC, the address is actually $g + Offset.
11729 DAG.getNode(ISD::ADD, DL, PtrVT,
11730 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11736 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11737 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11739 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11740 // global base reg.
11741 unsigned char OpFlag = 0;
11742 unsigned WrapperKind = X86ISD::Wrapper;
11743 CodeModel::Model M = DAG.getTarget().getCodeModel();
11745 if (Subtarget->isPICStyleRIPRel() &&
11746 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11747 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11748 OpFlag = X86II::MO_GOTPCREL;
11749 WrapperKind = X86ISD::WrapperRIP;
11750 } else if (Subtarget->isPICStyleGOT()) {
11751 OpFlag = X86II::MO_GOT;
11752 } else if (Subtarget->isPICStyleStubPIC()) {
11753 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11754 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11755 OpFlag = X86II::MO_DARWIN_NONLAZY;
11758 auto PtrVT = getPointerTy(DAG.getDataLayout());
11759 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11762 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11764 // With PIC, the address is actually $g + Offset.
11765 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11766 !Subtarget->is64Bit()) {
11768 DAG.getNode(ISD::ADD, DL, PtrVT,
11769 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11772 // For symbols that require a load from a stub to get the address, emit the
11774 if (isGlobalStubReference(OpFlag))
11775 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11776 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11777 false, false, false, 0);
11783 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11784 // Create the TargetBlockAddressAddress node.
11785 unsigned char OpFlags =
11786 Subtarget->ClassifyBlockAddressReference();
11787 CodeModel::Model M = DAG.getTarget().getCodeModel();
11788 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11789 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11791 auto PtrVT = getPointerTy(DAG.getDataLayout());
11792 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11794 if (Subtarget->isPICStyleRIPRel() &&
11795 (M == CodeModel::Small || M == CodeModel::Kernel))
11796 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11798 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11800 // With PIC, the address is actually $g + Offset.
11801 if (isGlobalRelativeToPICBase(OpFlags)) {
11802 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11803 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11810 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11811 int64_t Offset, SelectionDAG &DAG) const {
11812 // Create the TargetGlobalAddress node, folding in the constant
11813 // offset if it is legal.
11814 unsigned char OpFlags =
11815 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11816 CodeModel::Model M = DAG.getTarget().getCodeModel();
11817 auto PtrVT = getPointerTy(DAG.getDataLayout());
11819 if (OpFlags == X86II::MO_NO_FLAG &&
11820 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11821 // A direct static reference to a global.
11822 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11825 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11828 if (Subtarget->isPICStyleRIPRel() &&
11829 (M == CodeModel::Small || M == CodeModel::Kernel))
11830 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11832 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11834 // With PIC, the address is actually $g + Offset.
11835 if (isGlobalRelativeToPICBase(OpFlags)) {
11836 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11837 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11840 // For globals that require a load from a stub to get the address, emit the
11842 if (isGlobalStubReference(OpFlags))
11843 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11844 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11845 false, false, false, 0);
11847 // If there was a non-zero offset that we didn't fold, create an explicit
11848 // addition for it.
11850 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11851 DAG.getConstant(Offset, dl, PtrVT));
11857 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11858 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11859 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11860 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11864 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11865 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11866 unsigned char OperandFlags, bool LocalDynamic = false) {
11867 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11868 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11870 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11871 GA->getValueType(0),
11875 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11879 SDValue Ops[] = { Chain, TGA, *InFlag };
11880 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11882 SDValue Ops[] = { Chain, TGA };
11883 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11886 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11887 MFI->setAdjustsStack(true);
11888 MFI->setHasCalls(true);
11890 SDValue Flag = Chain.getValue(1);
11891 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11894 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11896 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11899 SDLoc dl(GA); // ? function entry point might be better
11900 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11901 DAG.getNode(X86ISD::GlobalBaseReg,
11902 SDLoc(), PtrVT), InFlag);
11903 InFlag = Chain.getValue(1);
11905 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11908 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11910 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11912 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11913 X86::RAX, X86II::MO_TLSGD);
11916 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11922 // Get the start address of the TLS block for this module.
11923 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11924 .getInfo<X86MachineFunctionInfo>();
11925 MFI->incNumLocalDynamicTLSAccesses();
11929 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11930 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11933 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11934 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11935 InFlag = Chain.getValue(1);
11936 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11937 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11940 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11944 unsigned char OperandFlags = X86II::MO_DTPOFF;
11945 unsigned WrapperKind = X86ISD::Wrapper;
11946 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11947 GA->getValueType(0),
11948 GA->getOffset(), OperandFlags);
11949 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11951 // Add x@dtpoff with the base.
11952 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11955 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11956 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11957 const EVT PtrVT, TLSModel::Model model,
11958 bool is64Bit, bool isPIC) {
11961 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11962 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11963 is64Bit ? 257 : 256));
11965 SDValue ThreadPointer =
11966 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11967 MachinePointerInfo(Ptr), false, false, false, 0);
11969 unsigned char OperandFlags = 0;
11970 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11972 unsigned WrapperKind = X86ISD::Wrapper;
11973 if (model == TLSModel::LocalExec) {
11974 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11975 } else if (model == TLSModel::InitialExec) {
11977 OperandFlags = X86II::MO_GOTTPOFF;
11978 WrapperKind = X86ISD::WrapperRIP;
11980 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11983 llvm_unreachable("Unexpected model");
11986 // emit "addl x@ntpoff,%eax" (local exec)
11987 // or "addl x@indntpoff,%eax" (initial exec)
11988 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11990 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11991 GA->getOffset(), OperandFlags);
11992 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11994 if (model == TLSModel::InitialExec) {
11995 if (isPIC && !is64Bit) {
11996 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11997 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12001 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12002 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12003 false, false, false, 0);
12006 // The address of the thread local variable is the add of the thread
12007 // pointer with the offset of the variable.
12008 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12012 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12014 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12015 const GlobalValue *GV = GA->getGlobal();
12016 auto PtrVT = getPointerTy(DAG.getDataLayout());
12018 if (Subtarget->isTargetELF()) {
12019 if (DAG.getTarget().Options.EmulatedTLS)
12020 return LowerToTLSEmulatedModel(GA, DAG);
12021 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12023 case TLSModel::GeneralDynamic:
12024 if (Subtarget->is64Bit())
12025 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12026 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12027 case TLSModel::LocalDynamic:
12028 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12029 Subtarget->is64Bit());
12030 case TLSModel::InitialExec:
12031 case TLSModel::LocalExec:
12032 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12033 DAG.getTarget().getRelocationModel() ==
12036 llvm_unreachable("Unknown TLS model.");
12039 if (Subtarget->isTargetDarwin()) {
12040 // Darwin only has one model of TLS. Lower to that.
12041 unsigned char OpFlag = 0;
12042 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12043 X86ISD::WrapperRIP : X86ISD::Wrapper;
12045 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12046 // global base reg.
12047 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12048 !Subtarget->is64Bit();
12050 OpFlag = X86II::MO_TLVP_PIC_BASE;
12052 OpFlag = X86II::MO_TLVP;
12054 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12055 GA->getValueType(0),
12056 GA->getOffset(), OpFlag);
12057 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12059 // With PIC32, the address is actually $g + Offset.
12061 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12062 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12065 // Lowering the machine isd will make sure everything is in the right
12067 SDValue Chain = DAG.getEntryNode();
12068 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12069 SDValue Args[] = { Chain, Offset };
12070 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12072 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12073 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12074 MFI->setAdjustsStack(true);
12076 // And our return value (tls address) is in the standard call return value
12078 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12079 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12082 if (Subtarget->isTargetKnownWindowsMSVC() ||
12083 Subtarget->isTargetWindowsGNU()) {
12084 // Just use the implicit TLS architecture
12085 // Need to generate someting similar to:
12086 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12088 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
12089 // mov rcx, qword [rdx+rcx*8]
12090 // mov eax, .tls$:tlsvar
12091 // [rax+rcx] contains the address
12092 // Windows 64bit: gs:0x58
12093 // Windows 32bit: fs:__tls_array
12096 SDValue Chain = DAG.getEntryNode();
12098 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12099 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12100 // use its literal value of 0x2C.
12101 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12102 ? Type::getInt8PtrTy(*DAG.getContext(),
12104 : Type::getInt32PtrTy(*DAG.getContext(),
12107 SDValue TlsArray = Subtarget->is64Bit()
12108 ? DAG.getIntPtrConstant(0x58, dl)
12109 : (Subtarget->isTargetWindowsGNU()
12110 ? DAG.getIntPtrConstant(0x2C, dl)
12111 : DAG.getExternalSymbol("_tls_array", PtrVT));
12113 SDValue ThreadPointer =
12114 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12118 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12119 res = ThreadPointer;
12121 // Load the _tls_index variable
12122 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12123 if (Subtarget->is64Bit())
12124 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12125 MachinePointerInfo(), MVT::i32, false, false,
12128 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12131 auto &DL = DAG.getDataLayout();
12133 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12134 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12136 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12139 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12142 // Get the offset of start of .tls section
12143 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12144 GA->getValueType(0),
12145 GA->getOffset(), X86II::MO_SECREL);
12146 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12148 // The address of the thread local variable is the add of the thread
12149 // pointer with the offset of the variable.
12150 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12153 llvm_unreachable("TLS not implemented for this target.");
12156 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12157 /// and take a 2 x i32 value to shift plus a shift amount.
12158 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12159 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12160 MVT VT = Op.getSimpleValueType();
12161 unsigned VTBits = VT.getSizeInBits();
12163 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12164 SDValue ShOpLo = Op.getOperand(0);
12165 SDValue ShOpHi = Op.getOperand(1);
12166 SDValue ShAmt = Op.getOperand(2);
12167 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12168 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12170 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12171 DAG.getConstant(VTBits - 1, dl, MVT::i8));
12172 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12173 DAG.getConstant(VTBits - 1, dl, MVT::i8))
12174 : DAG.getConstant(0, dl, VT);
12176 SDValue Tmp2, Tmp3;
12177 if (Op.getOpcode() == ISD::SHL_PARTS) {
12178 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12179 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12181 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12182 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12185 // If the shift amount is larger or equal than the width of a part we can't
12186 // rely on the results of shld/shrd. Insert a test and select the appropriate
12187 // values for large shift amounts.
12188 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12189 DAG.getConstant(VTBits, dl, MVT::i8));
12190 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12191 AndNode, DAG.getConstant(0, dl, MVT::i8));
12194 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12195 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12196 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12198 if (Op.getOpcode() == ISD::SHL_PARTS) {
12199 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12200 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12202 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12203 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12206 SDValue Ops[2] = { Lo, Hi };
12207 return DAG.getMergeValues(Ops, dl);
12210 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12211 SelectionDAG &DAG) const {
12212 SDValue Src = Op.getOperand(0);
12213 MVT SrcVT = Src.getSimpleValueType();
12214 MVT VT = Op.getSimpleValueType();
12217 if (SrcVT.isVector()) {
12218 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12219 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12220 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12221 DAG.getUNDEF(SrcVT)));
12223 if (SrcVT.getVectorElementType() == MVT::i1) {
12224 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12225 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12226 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12231 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12232 "Unknown SINT_TO_FP to lower!");
12234 // These are really Legal; return the operand so the caller accepts it as
12236 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12238 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12239 Subtarget->is64Bit()) {
12243 unsigned Size = SrcVT.getSizeInBits()/8;
12244 MachineFunction &MF = DAG.getMachineFunction();
12245 auto PtrVT = getPointerTy(MF.getDataLayout());
12246 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12247 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12248 SDValue Chain = DAG.getStore(
12249 DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12250 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12252 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12255 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12257 SelectionDAG &DAG) const {
12261 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12263 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12265 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12267 unsigned ByteSize = SrcVT.getSizeInBits()/8;
12269 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12270 MachineMemOperand *MMO;
12272 int SSFI = FI->getIndex();
12273 MMO = DAG.getMachineFunction().getMachineMemOperand(
12274 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12275 MachineMemOperand::MOLoad, ByteSize, ByteSize);
12277 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12278 StackSlot = StackSlot.getOperand(1);
12280 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12281 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12283 Tys, Ops, SrcVT, MMO);
12286 Chain = Result.getValue(1);
12287 SDValue InFlag = Result.getValue(2);
12289 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12290 // shouldn't be necessary except that RFP cannot be live across
12291 // multiple blocks. When stackifier is fixed, they can be uncoupled.
12292 MachineFunction &MF = DAG.getMachineFunction();
12293 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12294 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12295 auto PtrVT = getPointerTy(MF.getDataLayout());
12296 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12297 Tys = DAG.getVTList(MVT::Other);
12299 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12301 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12302 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12303 MachineMemOperand::MOStore, SSFISize, SSFISize);
12305 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12306 Ops, Op.getValueType(), MMO);
12307 Result = DAG.getLoad(
12308 Op.getValueType(), DL, Chain, StackSlot,
12309 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12310 false, false, false, 0);
12316 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12317 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12318 SelectionDAG &DAG) const {
12319 // This algorithm is not obvious. Here it is what we're trying to output:
12322 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12323 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12325 haddpd %xmm0, %xmm0
12327 pshufd $0x4e, %xmm0, %xmm1
12333 LLVMContext *Context = DAG.getContext();
12335 // Build some magic constants.
12336 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12337 Constant *C0 = ConstantDataVector::get(*Context, CV0);
12338 auto PtrVT = getPointerTy(DAG.getDataLayout());
12339 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12341 SmallVector<Constant*,2> CV1;
12343 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12344 APInt(64, 0x4330000000000000ULL))));
12346 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12347 APInt(64, 0x4530000000000000ULL))));
12348 Constant *C1 = ConstantVector::get(CV1);
12349 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12351 // Load the 64-bit value into an XMM register.
12352 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12355 DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12356 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12357 false, false, false, 16);
12359 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12362 DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12363 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12364 false, false, false, 16);
12365 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12366 // TODO: Are there any fast-math-flags to propagate here?
12367 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12370 if (Subtarget->hasSSE3()) {
12371 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12372 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12374 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12375 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12377 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12378 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12381 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12382 DAG.getIntPtrConstant(0, dl));
12385 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12386 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12387 SelectionDAG &DAG) const {
12389 // FP constant to bias correct the final result.
12390 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12393 // Load the 32-bit value into an XMM register.
12394 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12397 // Zero out the upper parts of the register.
12398 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12400 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12401 DAG.getBitcast(MVT::v2f64, Load),
12402 DAG.getIntPtrConstant(0, dl));
12404 // Or the load with the bias.
12405 SDValue Or = DAG.getNode(
12406 ISD::OR, dl, MVT::v2i64,
12407 DAG.getBitcast(MVT::v2i64,
12408 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12409 DAG.getBitcast(MVT::v2i64,
12410 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12412 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12413 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12415 // Subtract the bias.
12416 // TODO: Are there any fast-math-flags to propagate here?
12417 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12419 // Handle final rounding.
12420 EVT DestVT = Op.getValueType();
12422 if (DestVT.bitsLT(MVT::f64))
12423 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12424 DAG.getIntPtrConstant(0, dl));
12425 if (DestVT.bitsGT(MVT::f64))
12426 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12428 // Handle final rounding.
12432 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12433 const X86Subtarget &Subtarget) {
12434 // The algorithm is the following:
12435 // #ifdef __SSE4_1__
12436 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12437 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12438 // (uint4) 0x53000000, 0xaa);
12440 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12441 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12443 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12444 // return (float4) lo + fhi;
12447 SDValue V = Op->getOperand(0);
12448 EVT VecIntVT = V.getValueType();
12449 bool Is128 = VecIntVT == MVT::v4i32;
12450 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12451 // If we convert to something else than the supported type, e.g., to v4f64,
12453 if (VecFloatVT != Op->getValueType(0))
12456 unsigned NumElts = VecIntVT.getVectorNumElements();
12457 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12458 "Unsupported custom type");
12459 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12461 // In the #idef/#else code, we have in common:
12462 // - The vector of constants:
12468 // Create the splat vector for 0x4b000000.
12469 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12470 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12471 CstLow, CstLow, CstLow, CstLow};
12472 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12473 makeArrayRef(&CstLowArray[0], NumElts));
12474 // Create the splat vector for 0x53000000.
12475 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12476 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12477 CstHigh, CstHigh, CstHigh, CstHigh};
12478 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12479 makeArrayRef(&CstHighArray[0], NumElts));
12481 // Create the right shift.
12482 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12483 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12484 CstShift, CstShift, CstShift, CstShift};
12485 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12486 makeArrayRef(&CstShiftArray[0], NumElts));
12487 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12490 if (Subtarget.hasSSE41()) {
12491 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12492 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12493 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12494 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12495 // Low will be bitcasted right away, so do not bother bitcasting back to its
12497 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12498 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12499 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12500 // (uint4) 0x53000000, 0xaa);
12501 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12502 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12503 // High will be bitcasted right away, so do not bother bitcasting back to
12504 // its original type.
12505 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12506 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12508 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12509 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12510 CstMask, CstMask, CstMask);
12511 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12512 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12513 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12515 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12516 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12519 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12520 SDValue CstFAdd = DAG.getConstantFP(
12521 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12522 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12523 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12524 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12525 makeArrayRef(&CstFAddArray[0], NumElts));
12527 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12528 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12529 // TODO: Are there any fast-math-flags to propagate here?
12531 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12532 // return (float4) lo + fhi;
12533 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12534 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12537 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12538 SelectionDAG &DAG) const {
12539 SDValue N0 = Op.getOperand(0);
12540 MVT SVT = N0.getSimpleValueType();
12543 switch (SVT.SimpleTy) {
12545 llvm_unreachable("Custom UINT_TO_FP is not supported!");
12550 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12551 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12552 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12556 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12559 if (Subtarget->hasAVX512())
12560 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12561 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12563 llvm_unreachable(nullptr);
12566 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12567 SelectionDAG &DAG) const {
12568 SDValue N0 = Op.getOperand(0);
12570 auto PtrVT = getPointerTy(DAG.getDataLayout());
12572 if (Op.getValueType().isVector())
12573 return lowerUINT_TO_FP_vec(Op, DAG);
12575 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12576 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12577 // the optimization here.
12578 if (DAG.SignBitIsZero(N0))
12579 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12581 MVT SrcVT = N0.getSimpleValueType();
12582 MVT DstVT = Op.getSimpleValueType();
12584 if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
12585 (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
12586 // Conversions from unsigned i32 to f32/f64 are legal,
12587 // using VCVTUSI2SS/SD. Same for i64 in 64-bit mode.
12591 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12592 return LowerUINT_TO_FP_i64(Op, DAG);
12593 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12594 return LowerUINT_TO_FP_i32(Op, DAG);
12595 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12598 // Make a 64-bit buffer, and use it to build an FILD.
12599 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12600 if (SrcVT == MVT::i32) {
12601 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12602 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12603 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12604 StackSlot, MachinePointerInfo(),
12606 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12607 OffsetSlot, MachinePointerInfo(),
12609 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12613 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12614 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12615 StackSlot, MachinePointerInfo(),
12617 // For i64 source, we need to add the appropriate power of 2 if the input
12618 // was negative. This is the same as the optimization in
12619 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12620 // we must be careful to do the computation in x87 extended precision, not
12621 // in SSE. (The generic code can't know it's OK to do this, or how to.)
12622 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12623 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12624 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12625 MachineMemOperand::MOLoad, 8, 8);
12627 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12628 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12629 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12632 APInt FF(32, 0x5F800000ULL);
12634 // Check whether the sign bit is set.
12635 SDValue SignSet = DAG.getSetCC(
12636 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12637 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12639 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12640 SDValue FudgePtr = DAG.getConstantPool(
12641 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12643 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12644 SDValue Zero = DAG.getIntPtrConstant(0, dl);
12645 SDValue Four = DAG.getIntPtrConstant(4, dl);
12646 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12648 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12650 // Load the value out, extending it from f32 to f80.
12651 // FIXME: Avoid the extend by constructing the right constant pool?
12652 SDValue Fudge = DAG.getExtLoad(
12653 ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12654 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12655 false, false, false, 4);
12656 // Extend everything to 80 bits to force it to be done on x87.
12657 // TODO: Are there any fast-math-flags to propagate here?
12658 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12659 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12660 DAG.getIntPtrConstant(0, dl));
12663 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12664 // is legal, or has an f16 source (which needs to be promoted to f32),
12665 // just return an <SDValue(), SDValue()> pair.
12666 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12667 // to i16, i32 or i64, and we lower it to a legal sequence.
12668 // If lowered to the final integer result we return a <result, SDValue()> pair.
12669 // Otherwise we lower it to a sequence ending with a FIST, return a
12670 // <FIST, StackSlot> pair, and the caller is responsible for loading
12671 // the final integer result from StackSlot.
12672 std::pair<SDValue,SDValue>
12673 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12674 bool IsSigned, bool IsReplace) const {
12677 EVT DstTy = Op.getValueType();
12678 EVT TheVT = Op.getOperand(0).getValueType();
12679 auto PtrVT = getPointerTy(DAG.getDataLayout());
12681 if (TheVT == MVT::f16)
12682 // We need to promote the f16 to f32 before using the lowering
12683 // in this routine.
12684 return std::make_pair(SDValue(), SDValue());
12686 assert((TheVT == MVT::f32 ||
12687 TheVT == MVT::f64 ||
12688 TheVT == MVT::f80) &&
12689 "Unexpected FP operand type in FP_TO_INTHelper");
12691 // If using FIST to compute an unsigned i64, we'll need some fixup
12692 // to handle values above the maximum signed i64. A FIST is always
12693 // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12694 bool UnsignedFixup = !IsSigned &&
12695 DstTy == MVT::i64 &&
12696 (!Subtarget->is64Bit() ||
12697 !isScalarFPTypeInSSEReg(TheVT));
12699 if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12700 // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12701 // The low 32 bits of the fist result will have the correct uint32 result.
12702 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12706 assert(DstTy.getSimpleVT() <= MVT::i64 &&
12707 DstTy.getSimpleVT() >= MVT::i16 &&
12708 "Unknown FP_TO_INT to lower!");
12710 // These are really Legal.
12711 if (DstTy == MVT::i32 &&
12712 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12713 return std::make_pair(SDValue(), SDValue());
12714 if (Subtarget->is64Bit() &&
12715 DstTy == MVT::i64 &&
12716 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12717 return std::make_pair(SDValue(), SDValue());
12719 // We lower FP->int64 into FISTP64 followed by a load from a temporary
12721 MachineFunction &MF = DAG.getMachineFunction();
12722 unsigned MemSize = DstTy.getSizeInBits()/8;
12723 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12724 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12727 switch (DstTy.getSimpleVT().SimpleTy) {
12728 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12729 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12730 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12731 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12734 SDValue Chain = DAG.getEntryNode();
12735 SDValue Value = Op.getOperand(0);
12736 SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12738 if (UnsignedFixup) {
12740 // Conversion to unsigned i64 is implemented with a select,
12741 // depending on whether the source value fits in the range
12742 // of a signed i64. Let Thresh be the FP equivalent of
12743 // 0x8000000000000000ULL.
12745 // Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12746 // FistSrc = (Value < Thresh) ? Value : (Value - Thresh);
12747 // Fist-to-mem64 FistSrc
12748 // Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12749 // to XOR'ing the high 32 bits with Adjust.
12751 // Being a power of 2, Thresh is exactly representable in all FP formats.
12752 // For X87 we'd like to use the smallest FP type for this constant, but
12753 // for DAG type consistency we have to match the FP operand type.
12755 APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12756 APFloat::opStatus Status = APFloat::opOK;
12757 bool LosesInfo = false;
12758 if (TheVT == MVT::f64)
12759 // The rounding mode is irrelevant as the conversion should be exact.
12760 Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12762 else if (TheVT == MVT::f80)
12763 Status = Thresh.convert(APFloat::x87DoubleExtended,
12764 APFloat::rmNearestTiesToEven, &LosesInfo);
12766 assert(Status == APFloat::opOK && !LosesInfo &&
12767 "FP conversion should have been exact");
12769 SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12771 SDValue Cmp = DAG.getSetCC(DL,
12772 getSetCCResultType(DAG.getDataLayout(),
12773 *DAG.getContext(), TheVT),
12774 Value, ThreshVal, ISD::SETLT);
12775 Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12776 DAG.getConstant(0, DL, MVT::i32),
12777 DAG.getConstant(0x80000000, DL, MVT::i32));
12778 SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12779 Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12780 *DAG.getContext(), TheVT),
12781 Value, ThreshVal, ISD::SETLT);
12782 Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12785 // FIXME This causes a redundant load/store if the SSE-class value is already
12786 // in memory, such as if it is on the callstack.
12787 if (isScalarFPTypeInSSEReg(TheVT)) {
12788 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12789 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12790 MachinePointerInfo::getFixedStack(MF, SSFI), false,
12792 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12794 Chain, StackSlot, DAG.getValueType(TheVT)
12797 MachineMemOperand *MMO =
12798 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12799 MachineMemOperand::MOLoad, MemSize, MemSize);
12800 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12801 Chain = Value.getValue(1);
12802 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12803 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12806 MachineMemOperand *MMO =
12807 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12808 MachineMemOperand::MOStore, MemSize, MemSize);
12810 if (UnsignedFixup) {
12812 // Insert the FIST, load its result as two i32's,
12813 // and XOR the high i32 with Adjust.
12815 SDValue FistOps[] = { Chain, Value, StackSlot };
12816 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12817 FistOps, DstTy, MMO);
12819 SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12820 MachinePointerInfo(),
12821 false, false, false, 0);
12822 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12823 DAG.getConstant(4, DL, PtrVT));
12825 SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12826 MachinePointerInfo(),
12827 false, false, false, 0);
12828 High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12830 if (Subtarget->is64Bit()) {
12831 // Join High32 and Low32 into a 64-bit result.
12832 // (High32 << 32) | Low32
12833 Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12834 High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12835 High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12836 DAG.getConstant(32, DL, MVT::i8));
12837 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12838 return std::make_pair(Result, SDValue());
12841 SDValue ResultOps[] = { Low32, High32 };
12843 SDValue pair = IsReplace
12844 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12845 : DAG.getMergeValues(ResultOps, DL);
12846 return std::make_pair(pair, SDValue());
12848 // Build the FP_TO_INT*_IN_MEM
12849 SDValue Ops[] = { Chain, Value, StackSlot };
12850 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12852 return std::make_pair(FIST, StackSlot);
12856 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12857 const X86Subtarget *Subtarget) {
12858 MVT VT = Op->getSimpleValueType(0);
12859 SDValue In = Op->getOperand(0);
12860 MVT InVT = In.getSimpleValueType();
12863 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12864 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12866 // Optimize vectors in AVX mode:
12869 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12870 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12871 // Concat upper and lower parts.
12874 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12875 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12876 // Concat upper and lower parts.
12879 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12880 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12881 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12884 if (Subtarget->hasInt256())
12885 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12887 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12888 SDValue Undef = DAG.getUNDEF(InVT);
12889 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12890 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12891 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12893 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12894 VT.getVectorNumElements()/2);
12896 OpLo = DAG.getBitcast(HVT, OpLo);
12897 OpHi = DAG.getBitcast(HVT, OpHi);
12899 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12902 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12903 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12904 MVT VT = Op->getSimpleValueType(0);
12905 SDValue In = Op->getOperand(0);
12906 MVT InVT = In.getSimpleValueType();
12908 unsigned int NumElts = VT.getVectorNumElements();
12909 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12912 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12913 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12915 assert(InVT.getVectorElementType() == MVT::i1);
12916 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12918 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12920 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12922 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12923 if (VT.is512BitVector())
12925 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12928 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12929 SelectionDAG &DAG) {
12930 if (Subtarget->hasFp256())
12931 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12937 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12938 SelectionDAG &DAG) {
12940 MVT VT = Op.getSimpleValueType();
12941 SDValue In = Op.getOperand(0);
12942 MVT SVT = In.getSimpleValueType();
12944 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12945 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12947 if (Subtarget->hasFp256())
12948 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12951 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12952 VT.getVectorNumElements() != SVT.getVectorNumElements());
12956 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12958 MVT VT = Op.getSimpleValueType();
12959 SDValue In = Op.getOperand(0);
12960 MVT InVT = In.getSimpleValueType();
12962 if (VT == MVT::i1) {
12963 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12964 "Invalid scalar TRUNCATE operation");
12965 if (InVT.getSizeInBits() >= 32)
12967 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12968 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12970 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12971 "Invalid TRUNCATE operation");
12973 // move vector to mask - truncate solution for SKX
12974 if (VT.getVectorElementType() == MVT::i1) {
12975 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12976 Subtarget->hasBWI())
12977 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12978 if ((InVT.is256BitVector() || InVT.is128BitVector())
12979 && InVT.getScalarSizeInBits() <= 16 &&
12980 Subtarget->hasBWI() && Subtarget->hasVLX())
12981 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12982 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12983 Subtarget->hasDQI())
12984 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12985 if ((InVT.is256BitVector() || InVT.is128BitVector())
12986 && InVT.getScalarSizeInBits() >= 32 &&
12987 Subtarget->hasDQI() && Subtarget->hasVLX())
12988 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12991 if (VT.getVectorElementType() == MVT::i1) {
12992 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12993 unsigned NumElts = InVT.getVectorNumElements();
12994 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12995 if (InVT.getSizeInBits() < 512) {
12996 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12997 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13002 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
13003 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13004 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13007 // vpmovqb/w/d, vpmovdb/w, vpmovwb
13008 if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
13009 (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
13010 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13012 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13013 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13014 if (Subtarget->hasInt256()) {
13015 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13016 In = DAG.getBitcast(MVT::v8i32, In);
13017 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13019 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13020 DAG.getIntPtrConstant(0, DL));
13023 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13024 DAG.getIntPtrConstant(0, DL));
13025 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13026 DAG.getIntPtrConstant(2, DL));
13027 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13028 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13029 static const int ShufMask[] = {0, 2, 4, 6};
13030 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13033 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13034 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13035 if (Subtarget->hasInt256()) {
13036 In = DAG.getBitcast(MVT::v32i8, In);
13038 SmallVector<SDValue,32> pshufbMask;
13039 for (unsigned i = 0; i < 2; ++i) {
13040 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13041 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13042 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13043 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13044 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13045 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13046 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13047 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13048 for (unsigned j = 0; j < 8; ++j)
13049 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13051 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13052 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13053 In = DAG.getBitcast(MVT::v4i64, In);
13055 static const int ShufMask[] = {0, 2, -1, -1};
13056 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
13058 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13059 DAG.getIntPtrConstant(0, DL));
13060 return DAG.getBitcast(VT, In);
13063 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13064 DAG.getIntPtrConstant(0, DL));
13066 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13067 DAG.getIntPtrConstant(4, DL));
13069 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13070 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13072 // The PSHUFB mask:
13073 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13074 -1, -1, -1, -1, -1, -1, -1, -1};
13076 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13077 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13078 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13080 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13081 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13083 // The MOVLHPS Mask:
13084 static const int ShufMask2[] = {0, 1, 4, 5};
13085 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13086 return DAG.getBitcast(MVT::v8i16, res);
13089 // Handle truncation of V256 to V128 using shuffles.
13090 if (!VT.is128BitVector() || !InVT.is256BitVector())
13093 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13095 unsigned NumElems = VT.getVectorNumElements();
13096 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13098 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13099 // Prepare truncation shuffle mask
13100 for (unsigned i = 0; i != NumElems; ++i)
13101 MaskVec[i] = i * 2;
13102 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13103 DAG.getUNDEF(NVT), &MaskVec[0]);
13104 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13105 DAG.getIntPtrConstant(0, DL));
13108 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13109 SelectionDAG &DAG) const {
13110 assert(!Op.getSimpleValueType().isVector());
13112 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13113 /*IsSigned=*/ true, /*IsReplace=*/ false);
13114 SDValue FIST = Vals.first, StackSlot = Vals.second;
13115 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13116 if (!FIST.getNode())
13119 if (StackSlot.getNode())
13120 // Load the result.
13121 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13122 FIST, StackSlot, MachinePointerInfo(),
13123 false, false, false, 0);
13125 // The node is the result.
13129 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13130 SelectionDAG &DAG) const {
13131 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13132 /*IsSigned=*/ false, /*IsReplace=*/ false);
13133 SDValue FIST = Vals.first, StackSlot = Vals.second;
13134 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13135 if (!FIST.getNode())
13138 if (StackSlot.getNode())
13139 // Load the result.
13140 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13141 FIST, StackSlot, MachinePointerInfo(),
13142 false, false, false, 0);
13144 // The node is the result.
13148 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13150 MVT VT = Op.getSimpleValueType();
13151 SDValue In = Op.getOperand(0);
13152 MVT SVT = In.getSimpleValueType();
13154 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13156 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13157 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13158 In, DAG.getUNDEF(SVT)));
13161 /// The only differences between FABS and FNEG are the mask and the logic op.
13162 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13163 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13164 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13165 "Wrong opcode for lowering FABS or FNEG.");
13167 bool IsFABS = (Op.getOpcode() == ISD::FABS);
13169 // If this is a FABS and it has an FNEG user, bail out to fold the combination
13170 // into an FNABS. We'll lower the FABS after that if it is still in use.
13172 for (SDNode *User : Op->uses())
13173 if (User->getOpcode() == ISD::FNEG)
13177 MVT VT = Op.getSimpleValueType();
13179 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13180 // decide if we should generate a 16-byte constant mask when we only need 4 or
13181 // 8 bytes for the scalar case.
13187 if (VT.isVector()) {
13189 EltVT = VT.getVectorElementType();
13190 NumElts = VT.getVectorNumElements();
13192 // There are no scalar bitwise logical SSE/AVX instructions, so we
13193 // generate a 16-byte vector constant and logic op even for the scalar case.
13194 // Using a 16-byte mask allows folding the load of the mask with
13195 // the logic op, so it can save (~4 bytes) on code size.
13196 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13198 NumElts = (VT == MVT::f64) ? 2 : 4;
13201 unsigned EltBits = EltVT.getSizeInBits();
13202 LLVMContext *Context = DAG.getContext();
13203 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13205 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13206 Constant *C = ConstantInt::get(*Context, MaskElt);
13207 C = ConstantVector::getSplat(NumElts, C);
13208 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13209 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13210 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13212 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13213 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13214 false, false, false, Alignment);
13216 SDValue Op0 = Op.getOperand(0);
13217 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13219 IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13220 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13223 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13225 // For the scalar case extend to a 128-bit vector, perform the logic op,
13226 // and extract the scalar result back out.
13227 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13228 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13229 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13230 DAG.getIntPtrConstant(0, dl));
13233 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13234 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13235 LLVMContext *Context = DAG.getContext();
13236 SDValue Op0 = Op.getOperand(0);
13237 SDValue Op1 = Op.getOperand(1);
13239 MVT VT = Op.getSimpleValueType();
13240 MVT SrcVT = Op1.getSimpleValueType();
13242 // If second operand is smaller, extend it first.
13243 if (SrcVT.bitsLT(VT)) {
13244 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13247 // And if it is bigger, shrink it first.
13248 if (SrcVT.bitsGT(VT)) {
13249 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13253 // At this point the operands and the result should have the same
13254 // type, and that won't be f80 since that is not custom lowered.
13256 const fltSemantics &Sem =
13257 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
13258 const unsigned SizeInBits = VT.getSizeInBits();
13260 SmallVector<Constant *, 4> CV(
13261 VT == MVT::f64 ? 2 : 4,
13262 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13264 // First, clear all bits but the sign bit from the second operand (sign).
13265 CV[0] = ConstantFP::get(*Context,
13266 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13267 Constant *C = ConstantVector::get(CV);
13268 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13269 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13271 // Perform all logic operations as 16-byte vectors because there are no
13272 // scalar FP logic instructions in SSE. This allows load folding of the
13273 // constants into the logic instructions.
13274 MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13276 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13277 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13278 false, false, false, 16);
13279 Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13280 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13282 // Next, clear the sign bit from the first operand (magnitude).
13283 // If it's a constant, we can clear it here.
13284 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13285 APFloat APF = Op0CN->getValueAPF();
13286 // If the magnitude is a positive zero, the sign bit alone is enough.
13287 if (APF.isPosZero())
13288 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13289 DAG.getIntPtrConstant(0, dl));
13291 CV[0] = ConstantFP::get(*Context, APF);
13293 CV[0] = ConstantFP::get(
13295 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13297 C = ConstantVector::get(CV);
13298 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13300 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13301 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13302 false, false, false, 16);
13303 // If the magnitude operand wasn't a constant, we need to AND out the sign.
13304 if (!isa<ConstantFPSDNode>(Op0)) {
13305 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13306 Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13308 // OR the magnitude value with the sign bit.
13309 Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13310 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13311 DAG.getIntPtrConstant(0, dl));
13314 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13315 SDValue N0 = Op.getOperand(0);
13317 MVT VT = Op.getSimpleValueType();
13319 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13320 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13321 DAG.getConstant(1, dl, VT));
13322 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13325 // Check whether an OR'd tree is PTEST-able.
13326 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13327 SelectionDAG &DAG) {
13328 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13330 if (!Subtarget->hasSSE41())
13333 if (!Op->hasOneUse())
13336 SDNode *N = Op.getNode();
13339 SmallVector<SDValue, 8> Opnds;
13340 DenseMap<SDValue, unsigned> VecInMap;
13341 SmallVector<SDValue, 8> VecIns;
13342 EVT VT = MVT::Other;
13344 // Recognize a special case where a vector is casted into wide integer to
13346 Opnds.push_back(N->getOperand(0));
13347 Opnds.push_back(N->getOperand(1));
13349 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13350 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13351 // BFS traverse all OR'd operands.
13352 if (I->getOpcode() == ISD::OR) {
13353 Opnds.push_back(I->getOperand(0));
13354 Opnds.push_back(I->getOperand(1));
13355 // Re-evaluate the number of nodes to be traversed.
13356 e += 2; // 2 more nodes (LHS and RHS) are pushed.
13360 // Quit if a non-EXTRACT_VECTOR_ELT
13361 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13364 // Quit if without a constant index.
13365 SDValue Idx = I->getOperand(1);
13366 if (!isa<ConstantSDNode>(Idx))
13369 SDValue ExtractedFromVec = I->getOperand(0);
13370 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13371 if (M == VecInMap.end()) {
13372 VT = ExtractedFromVec.getValueType();
13373 // Quit if not 128/256-bit vector.
13374 if (!VT.is128BitVector() && !VT.is256BitVector())
13376 // Quit if not the same type.
13377 if (VecInMap.begin() != VecInMap.end() &&
13378 VT != VecInMap.begin()->first.getValueType())
13380 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13381 VecIns.push_back(ExtractedFromVec);
13383 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13386 assert((VT.is128BitVector() || VT.is256BitVector()) &&
13387 "Not extracted from 128-/256-bit vector.");
13389 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13391 for (DenseMap<SDValue, unsigned>::const_iterator
13392 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13393 // Quit if not all elements are used.
13394 if (I->second != FullMask)
13398 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13400 // Cast all vectors into TestVT for PTEST.
13401 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13402 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13404 // If more than one full vectors are evaluated, OR them first before PTEST.
13405 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13406 // Each iteration will OR 2 nodes and append the result until there is only
13407 // 1 node left, i.e. the final OR'd value of all vectors.
13408 SDValue LHS = VecIns[Slot];
13409 SDValue RHS = VecIns[Slot + 1];
13410 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13413 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13414 VecIns.back(), VecIns.back());
13417 /// \brief return true if \c Op has a use that doesn't just read flags.
13418 static bool hasNonFlagsUse(SDValue Op) {
13419 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13421 SDNode *User = *UI;
13422 unsigned UOpNo = UI.getOperandNo();
13423 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13424 // Look pass truncate.
13425 UOpNo = User->use_begin().getOperandNo();
13426 User = *User->use_begin();
13429 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13430 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13436 /// Emit nodes that will be selected as "test Op0,Op0", or something
13438 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13439 SelectionDAG &DAG) const {
13440 if (Op.getValueType() == MVT::i1) {
13441 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13442 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13443 DAG.getConstant(0, dl, MVT::i8));
13445 // CF and OF aren't always set the way we want. Determine which
13446 // of these we need.
13447 bool NeedCF = false;
13448 bool NeedOF = false;
13451 case X86::COND_A: case X86::COND_AE:
13452 case X86::COND_B: case X86::COND_BE:
13455 case X86::COND_G: case X86::COND_GE:
13456 case X86::COND_L: case X86::COND_LE:
13457 case X86::COND_O: case X86::COND_NO: {
13458 // Check if we really need to set the
13459 // Overflow flag. If NoSignedWrap is present
13460 // that is not actually needed.
13461 switch (Op->getOpcode()) {
13466 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13467 if (BinNode->Flags.hasNoSignedWrap())
13477 // See if we can use the EFLAGS value from the operand instead of
13478 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13479 // we prove that the arithmetic won't overflow, we can't use OF or CF.
13480 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13481 // Emit a CMP with 0, which is the TEST pattern.
13482 //if (Op.getValueType() == MVT::i1)
13483 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13484 // DAG.getConstant(0, MVT::i1));
13485 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13486 DAG.getConstant(0, dl, Op.getValueType()));
13488 unsigned Opcode = 0;
13489 unsigned NumOperands = 0;
13491 // Truncate operations may prevent the merge of the SETCC instruction
13492 // and the arithmetic instruction before it. Attempt to truncate the operands
13493 // of the arithmetic instruction and use a reduced bit-width instruction.
13494 bool NeedTruncation = false;
13495 SDValue ArithOp = Op;
13496 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13497 SDValue Arith = Op->getOperand(0);
13498 // Both the trunc and the arithmetic op need to have one user each.
13499 if (Arith->hasOneUse())
13500 switch (Arith.getOpcode()) {
13507 NeedTruncation = true;
13513 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13514 // which may be the result of a CAST. We use the variable 'Op', which is the
13515 // non-casted variable when we check for possible users.
13516 switch (ArithOp.getOpcode()) {
13518 // Due to an isel shortcoming, be conservative if this add is likely to be
13519 // selected as part of a load-modify-store instruction. When the root node
13520 // in a match is a store, isel doesn't know how to remap non-chain non-flag
13521 // uses of other nodes in the match, such as the ADD in this case. This
13522 // leads to the ADD being left around and reselected, with the result being
13523 // two adds in the output. Alas, even if none our users are stores, that
13524 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
13525 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
13526 // climbing the DAG back to the root, and it doesn't seem to be worth the
13528 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13529 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13530 if (UI->getOpcode() != ISD::CopyToReg &&
13531 UI->getOpcode() != ISD::SETCC &&
13532 UI->getOpcode() != ISD::STORE)
13535 if (ConstantSDNode *C =
13536 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13537 // An add of one will be selected as an INC.
13538 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13539 Opcode = X86ISD::INC;
13544 // An add of negative one (subtract of one) will be selected as a DEC.
13545 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13546 Opcode = X86ISD::DEC;
13552 // Otherwise use a regular EFLAGS-setting add.
13553 Opcode = X86ISD::ADD;
13558 // If we have a constant logical shift that's only used in a comparison
13559 // against zero turn it into an equivalent AND. This allows turning it into
13560 // a TEST instruction later.
13561 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13562 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13563 EVT VT = Op.getValueType();
13564 unsigned BitWidth = VT.getSizeInBits();
13565 unsigned ShAmt = Op->getConstantOperandVal(1);
13566 if (ShAmt >= BitWidth) // Avoid undefined shifts.
13568 APInt Mask = ArithOp.getOpcode() == ISD::SRL
13569 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13570 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13571 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13573 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13574 DAG.getConstant(Mask, dl, VT));
13575 DAG.ReplaceAllUsesWith(Op, New);
13581 // If the primary and result isn't used, don't bother using X86ISD::AND,
13582 // because a TEST instruction will be better.
13583 if (!hasNonFlagsUse(Op))
13589 // Due to the ISEL shortcoming noted above, be conservative if this op is
13590 // likely to be selected as part of a load-modify-store instruction.
13591 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13592 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13593 if (UI->getOpcode() == ISD::STORE)
13596 // Otherwise use a regular EFLAGS-setting instruction.
13597 switch (ArithOp.getOpcode()) {
13598 default: llvm_unreachable("unexpected operator!");
13599 case ISD::SUB: Opcode = X86ISD::SUB; break;
13600 case ISD::XOR: Opcode = X86ISD::XOR; break;
13601 case ISD::AND: Opcode = X86ISD::AND; break;
13603 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13604 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13605 if (EFLAGS.getNode())
13608 Opcode = X86ISD::OR;
13622 return SDValue(Op.getNode(), 1);
13628 // If we found that truncation is beneficial, perform the truncation and
13630 if (NeedTruncation) {
13631 EVT VT = Op.getValueType();
13632 SDValue WideVal = Op->getOperand(0);
13633 EVT WideVT = WideVal.getValueType();
13634 unsigned ConvertedOp = 0;
13635 // Use a target machine opcode to prevent further DAGCombine
13636 // optimizations that may separate the arithmetic operations
13637 // from the setcc node.
13638 switch (WideVal.getOpcode()) {
13640 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13641 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13642 case ISD::AND: ConvertedOp = X86ISD::AND; break;
13643 case ISD::OR: ConvertedOp = X86ISD::OR; break;
13644 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13648 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13649 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13650 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13651 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13652 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13658 // Emit a CMP with 0, which is the TEST pattern.
13659 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13660 DAG.getConstant(0, dl, Op.getValueType()));
13662 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13663 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13665 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13666 DAG.ReplaceAllUsesWith(Op, New);
13667 return SDValue(New.getNode(), 1);
13670 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13672 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13673 SDLoc dl, SelectionDAG &DAG) const {
13674 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13675 if (C->getAPIntValue() == 0)
13676 return EmitTest(Op0, X86CC, dl, DAG);
13678 if (Op0.getValueType() == MVT::i1)
13679 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13682 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13683 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13684 // Do the comparison at i32 if it's smaller, besides the Atom case.
13685 // This avoids subregister aliasing issues. Keep the smaller reference
13686 // if we're optimizing for size, however, as that'll allow better folding
13687 // of memory operations.
13688 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13689 !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13690 !Subtarget->isAtom()) {
13691 unsigned ExtendOp =
13692 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13693 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13694 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13696 // Use SUB instead of CMP to enable CSE between SUB and CMP.
13697 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13698 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13700 return SDValue(Sub.getNode(), 1);
13702 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13705 /// Convert a comparison if required by the subtarget.
13706 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13707 SelectionDAG &DAG) const {
13708 // If the subtarget does not support the FUCOMI instruction, floating-point
13709 // comparisons have to be converted.
13710 if (Subtarget->hasCMov() ||
13711 Cmp.getOpcode() != X86ISD::CMP ||
13712 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13713 !Cmp.getOperand(1).getValueType().isFloatingPoint())
13716 // The instruction selector will select an FUCOM instruction instead of
13717 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13718 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13719 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13721 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13722 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13723 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13724 DAG.getConstant(8, dl, MVT::i8));
13725 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13726 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13729 /// The minimum architected relative accuracy is 2^-12. We need one
13730 /// Newton-Raphson step to have a good float result (24 bits of precision).
13731 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13732 DAGCombinerInfo &DCI,
13733 unsigned &RefinementSteps,
13734 bool &UseOneConstNR) const {
13735 EVT VT = Op.getValueType();
13736 const char *RecipOp;
13738 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13739 // TODO: Add support for AVX512 (v16f32).
13740 // It is likely not profitable to do this for f64 because a double-precision
13741 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13742 // instructions: convert to single, rsqrtss, convert back to double, refine
13743 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13744 // along with FMA, this could be a throughput win.
13745 if (VT == MVT::f32 && Subtarget->hasSSE1())
13747 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13748 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13749 RecipOp = "vec-sqrtf";
13753 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13754 if (!Recips.isEnabled(RecipOp))
13757 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13758 UseOneConstNR = false;
13759 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13762 /// The minimum architected relative accuracy is 2^-12. We need one
13763 /// Newton-Raphson step to have a good float result (24 bits of precision).
13764 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13765 DAGCombinerInfo &DCI,
13766 unsigned &RefinementSteps) const {
13767 EVT VT = Op.getValueType();
13768 const char *RecipOp;
13770 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13771 // TODO: Add support for AVX512 (v16f32).
13772 // It is likely not profitable to do this for f64 because a double-precision
13773 // reciprocal estimate with refinement on x86 prior to FMA requires
13774 // 15 instructions: convert to single, rcpss, convert back to double, refine
13775 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13776 // along with FMA, this could be a throughput win.
13777 if (VT == MVT::f32 && Subtarget->hasSSE1())
13779 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13780 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13781 RecipOp = "vec-divf";
13785 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13786 if (!Recips.isEnabled(RecipOp))
13789 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13790 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13793 /// If we have at least two divisions that use the same divisor, convert to
13794 /// multplication by a reciprocal. This may need to be adjusted for a given
13795 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13796 /// This is because we still need one division to calculate the reciprocal and
13797 /// then we need two multiplies by that reciprocal as replacements for the
13798 /// original divisions.
13799 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13803 static bool isAllOnes(SDValue V) {
13804 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13805 return C && C->isAllOnesValue();
13808 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13809 /// if it's possible.
13810 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13811 SDLoc dl, SelectionDAG &DAG) const {
13812 SDValue Op0 = And.getOperand(0);
13813 SDValue Op1 = And.getOperand(1);
13814 if (Op0.getOpcode() == ISD::TRUNCATE)
13815 Op0 = Op0.getOperand(0);
13816 if (Op1.getOpcode() == ISD::TRUNCATE)
13817 Op1 = Op1.getOperand(0);
13820 if (Op1.getOpcode() == ISD::SHL)
13821 std::swap(Op0, Op1);
13822 if (Op0.getOpcode() == ISD::SHL) {
13823 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13824 if (And00C->getZExtValue() == 1) {
13825 // If we looked past a truncate, check that it's only truncating away
13827 unsigned BitWidth = Op0.getValueSizeInBits();
13828 unsigned AndBitWidth = And.getValueSizeInBits();
13829 if (BitWidth > AndBitWidth) {
13831 DAG.computeKnownBits(Op0, Zeros, Ones);
13832 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13836 RHS = Op0.getOperand(1);
13838 } else if (Op1.getOpcode() == ISD::Constant) {
13839 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13840 uint64_t AndRHSVal = AndRHS->getZExtValue();
13841 SDValue AndLHS = Op0;
13843 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13844 LHS = AndLHS.getOperand(0);
13845 RHS = AndLHS.getOperand(1);
13848 // Use BT if the immediate can't be encoded in a TEST instruction.
13849 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13851 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13855 if (LHS.getNode()) {
13856 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
13857 // instruction. Since the shift amount is in-range-or-undefined, we know
13858 // that doing a bittest on the i32 value is ok. We extend to i32 because
13859 // the encoding for the i16 version is larger than the i32 version.
13860 // Also promote i16 to i32 for performance / code size reason.
13861 if (LHS.getValueType() == MVT::i8 ||
13862 LHS.getValueType() == MVT::i16)
13863 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13865 // If the operand types disagree, extend the shift amount to match. Since
13866 // BT ignores high bits (like shifts) we can use anyextend.
13867 if (LHS.getValueType() != RHS.getValueType())
13868 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13870 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13871 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13872 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13873 DAG.getConstant(Cond, dl, MVT::i8), BT);
13879 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13881 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13886 // SSE Condition code mapping:
13895 switch (SetCCOpcode) {
13896 default: llvm_unreachable("Unexpected SETCC condition");
13898 case ISD::SETEQ: SSECC = 0; break;
13900 case ISD::SETGT: Swap = true; // Fallthrough
13902 case ISD::SETOLT: SSECC = 1; break;
13904 case ISD::SETGE: Swap = true; // Fallthrough
13906 case ISD::SETOLE: SSECC = 2; break;
13907 case ISD::SETUO: SSECC = 3; break;
13909 case ISD::SETNE: SSECC = 4; break;
13910 case ISD::SETULE: Swap = true; // Fallthrough
13911 case ISD::SETUGE: SSECC = 5; break;
13912 case ISD::SETULT: Swap = true; // Fallthrough
13913 case ISD::SETUGT: SSECC = 6; break;
13914 case ISD::SETO: SSECC = 7; break;
13916 case ISD::SETONE: SSECC = 8; break;
13919 std::swap(Op0, Op1);
13924 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13925 // ones, and then concatenate the result back.
13926 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13927 MVT VT = Op.getSimpleValueType();
13929 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13930 "Unsupported value type for operation");
13932 unsigned NumElems = VT.getVectorNumElements();
13934 SDValue CC = Op.getOperand(2);
13936 // Extract the LHS vectors
13937 SDValue LHS = Op.getOperand(0);
13938 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13939 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13941 // Extract the RHS vectors
13942 SDValue RHS = Op.getOperand(1);
13943 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13944 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13946 // Issue the operation on the smaller types and concatenate the result back
13947 MVT EltVT = VT.getVectorElementType();
13948 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13949 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13950 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13951 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13954 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13955 SDValue Op0 = Op.getOperand(0);
13956 SDValue Op1 = Op.getOperand(1);
13957 SDValue CC = Op.getOperand(2);
13958 MVT VT = Op.getSimpleValueType();
13961 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13962 "Unexpected type for boolean compare operation");
13963 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13964 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13965 DAG.getConstant(-1, dl, VT));
13966 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13967 DAG.getConstant(-1, dl, VT));
13968 switch (SetCCOpcode) {
13969 default: llvm_unreachable("Unexpected SETCC condition");
13971 // (x == y) -> ~(x ^ y)
13972 return DAG.getNode(ISD::XOR, dl, VT,
13973 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13974 DAG.getConstant(-1, dl, VT));
13976 // (x != y) -> (x ^ y)
13977 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13980 // (x > y) -> (x & ~y)
13981 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13984 // (x < y) -> (~x & y)
13985 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13988 // (x <= y) -> (~x | y)
13989 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13992 // (x >=y) -> (x | ~y)
13993 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13997 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13998 const X86Subtarget *Subtarget) {
13999 SDValue Op0 = Op.getOperand(0);
14000 SDValue Op1 = Op.getOperand(1);
14001 SDValue CC = Op.getOperand(2);
14002 MVT VT = Op.getSimpleValueType();
14005 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
14006 Op.getValueType().getScalarType() == MVT::i1 &&
14007 "Cannot set masked compare for this operation");
14009 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14011 bool Unsigned = false;
14014 switch (SetCCOpcode) {
14015 default: llvm_unreachable("Unexpected SETCC condition");
14016 case ISD::SETNE: SSECC = 4; break;
14017 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
14018 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14019 case ISD::SETLT: Swap = true; //fall-through
14020 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
14021 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14022 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14023 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
14024 case ISD::SETULE: Unsigned = true; //fall-through
14025 case ISD::SETLE: SSECC = 2; break;
14029 std::swap(Op0, Op1);
14031 return DAG.getNode(Opc, dl, VT, Op0, Op1);
14032 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14033 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14034 DAG.getConstant(SSECC, dl, MVT::i8));
14037 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14038 /// operand \p Op1. If non-trivial (for example because it's not constant)
14039 /// return an empty value.
14040 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14042 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14046 MVT VT = Op1.getSimpleValueType();
14047 MVT EVT = VT.getVectorElementType();
14048 unsigned n = VT.getVectorNumElements();
14049 SmallVector<SDValue, 8> ULTOp1;
14051 for (unsigned i = 0; i < n; ++i) {
14052 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14053 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
14056 // Avoid underflow.
14057 APInt Val = Elt->getAPIntValue();
14061 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14064 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14067 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14068 SelectionDAG &DAG) {
14069 SDValue Op0 = Op.getOperand(0);
14070 SDValue Op1 = Op.getOperand(1);
14071 SDValue CC = Op.getOperand(2);
14072 MVT VT = Op.getSimpleValueType();
14073 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14074 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14079 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14080 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14083 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14084 unsigned Opc = X86ISD::CMPP;
14085 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14086 assert(VT.getVectorNumElements() <= 16);
14087 Opc = X86ISD::CMPM;
14089 // In the two special cases we can't handle, emit two comparisons.
14092 unsigned CombineOpc;
14093 if (SetCCOpcode == ISD::SETUEQ) {
14094 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14096 assert(SetCCOpcode == ISD::SETONE);
14097 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14100 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14101 DAG.getConstant(CC0, dl, MVT::i8));
14102 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14103 DAG.getConstant(CC1, dl, MVT::i8));
14104 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14106 // Handle all other FP comparisons here.
14107 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14108 DAG.getConstant(SSECC, dl, MVT::i8));
14111 // Break 256-bit integer vector compare into smaller ones.
14112 if (VT.is256BitVector() && !Subtarget->hasInt256())
14113 return Lower256IntVSETCC(Op, DAG);
14115 EVT OpVT = Op1.getValueType();
14116 if (OpVT.getVectorElementType() == MVT::i1)
14117 return LowerBoolVSETCC_AVX512(Op, DAG);
14119 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14120 if (Subtarget->hasAVX512()) {
14121 if (Op1.getValueType().is512BitVector() ||
14122 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14123 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14124 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14126 // In AVX-512 architecture setcc returns mask with i1 elements,
14127 // But there is no compare instruction for i8 and i16 elements in KNL.
14128 // We are not talking about 512-bit operands in this case, these
14129 // types are illegal.
14131 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14132 OpVT.getVectorElementType().getSizeInBits() >= 8))
14133 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14134 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14137 // We are handling one of the integer comparisons here. Since SSE only has
14138 // GT and EQ comparisons for integer, swapping operands and multiple
14139 // operations may be required for some comparisons.
14141 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14142 bool Subus = false;
14144 switch (SetCCOpcode) {
14145 default: llvm_unreachable("Unexpected SETCC condition");
14146 case ISD::SETNE: Invert = true;
14147 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
14148 case ISD::SETLT: Swap = true;
14149 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
14150 case ISD::SETGE: Swap = true;
14151 case ISD::SETLE: Opc = X86ISD::PCMPGT;
14152 Invert = true; break;
14153 case ISD::SETULT: Swap = true;
14154 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14155 FlipSigns = true; break;
14156 case ISD::SETUGE: Swap = true;
14157 case ISD::SETULE: Opc = X86ISD::PCMPGT;
14158 FlipSigns = true; Invert = true; break;
14161 // Special case: Use min/max operations for SETULE/SETUGE
14162 MVT VET = VT.getVectorElementType();
14164 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14165 || (Subtarget->hasSSE2() && (VET == MVT::i8));
14168 switch (SetCCOpcode) {
14170 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14171 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14174 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14177 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14178 if (!MinMax && hasSubus) {
14179 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14181 // t = psubus Op0, Op1
14182 // pcmpeq t, <0..0>
14183 switch (SetCCOpcode) {
14185 case ISD::SETULT: {
14186 // If the comparison is against a constant we can turn this into a
14187 // setule. With psubus, setule does not require a swap. This is
14188 // beneficial because the constant in the register is no longer
14189 // destructed as the destination so it can be hoisted out of a loop.
14190 // Only do this pre-AVX since vpcmp* is no longer destructive.
14191 if (Subtarget->hasAVX())
14193 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14194 if (ULEOp1.getNode()) {
14196 Subus = true; Invert = false; Swap = false;
14200 // Psubus is better than flip-sign because it requires no inversion.
14201 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
14202 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14206 Opc = X86ISD::SUBUS;
14212 std::swap(Op0, Op1);
14214 // Check that the operation in question is available (most are plain SSE2,
14215 // but PCMPGTQ and PCMPEQQ have different requirements).
14216 if (VT == MVT::v2i64) {
14217 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14218 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14220 // First cast everything to the right type.
14221 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14222 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14224 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14225 // bits of the inputs before performing those operations. The lower
14226 // compare is always unsigned.
14229 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14231 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14232 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14233 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14234 Sign, Zero, Sign, Zero);
14236 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14237 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14239 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14240 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14241 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14243 // Create masks for only the low parts/high parts of the 64 bit integers.
14244 static const int MaskHi[] = { 1, 1, 3, 3 };
14245 static const int MaskLo[] = { 0, 0, 2, 2 };
14246 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14247 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14248 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14250 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14251 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14254 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14256 return DAG.getBitcast(VT, Result);
14259 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14260 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14261 // pcmpeqd + pshufd + pand.
14262 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14264 // First cast everything to the right type.
14265 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14266 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14269 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14271 // Make sure the lower and upper halves are both all-ones.
14272 static const int Mask[] = { 1, 0, 3, 2 };
14273 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14274 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14277 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14279 return DAG.getBitcast(VT, Result);
14283 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14284 // bits of the inputs before performing those operations.
14286 EVT EltVT = VT.getVectorElementType();
14287 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14289 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14290 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14293 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14295 // If the logical-not of the result is required, perform that now.
14297 Result = DAG.getNOT(dl, Result, VT);
14300 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14303 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14304 getZeroVector(VT, Subtarget, DAG, dl));
14309 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14311 MVT VT = Op.getSimpleValueType();
14313 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14315 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14316 && "SetCC type must be 8-bit or 1-bit integer");
14317 SDValue Op0 = Op.getOperand(0);
14318 SDValue Op1 = Op.getOperand(1);
14320 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14322 // Optimize to BT if possible.
14323 // Lower (X & (1 << N)) == 0 to BT(X, N).
14324 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14325 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14326 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14327 Op1.getOpcode() == ISD::Constant &&
14328 cast<ConstantSDNode>(Op1)->isNullValue() &&
14329 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14330 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14331 if (NewSetCC.getNode()) {
14333 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14338 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
14340 if (Op1.getOpcode() == ISD::Constant &&
14341 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14342 cast<ConstantSDNode>(Op1)->isNullValue()) &&
14343 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14345 // If the input is a setcc, then reuse the input setcc or use a new one with
14346 // the inverted condition.
14347 if (Op0.getOpcode() == X86ISD::SETCC) {
14348 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14349 bool Invert = (CC == ISD::SETNE) ^
14350 cast<ConstantSDNode>(Op1)->isNullValue();
14354 CCode = X86::GetOppositeBranchCondition(CCode);
14355 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14356 DAG.getConstant(CCode, dl, MVT::i8),
14357 Op0.getOperand(1));
14359 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14363 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14364 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14365 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14367 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14368 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14371 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14372 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14373 if (X86CC == X86::COND_INVALID)
14376 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14377 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14378 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14379 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14381 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14385 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14386 static bool isX86LogicalCmp(SDValue Op) {
14387 unsigned Opc = Op.getNode()->getOpcode();
14388 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14389 Opc == X86ISD::SAHF)
14391 if (Op.getResNo() == 1 &&
14392 (Opc == X86ISD::ADD ||
14393 Opc == X86ISD::SUB ||
14394 Opc == X86ISD::ADC ||
14395 Opc == X86ISD::SBB ||
14396 Opc == X86ISD::SMUL ||
14397 Opc == X86ISD::UMUL ||
14398 Opc == X86ISD::INC ||
14399 Opc == X86ISD::DEC ||
14400 Opc == X86ISD::OR ||
14401 Opc == X86ISD::XOR ||
14402 Opc == X86ISD::AND))
14405 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14411 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14412 if (V.getOpcode() != ISD::TRUNCATE)
14415 SDValue VOp0 = V.getOperand(0);
14416 unsigned InBits = VOp0.getValueSizeInBits();
14417 unsigned Bits = V.getValueSizeInBits();
14418 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14421 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14422 bool addTest = true;
14423 SDValue Cond = Op.getOperand(0);
14424 SDValue Op1 = Op.getOperand(1);
14425 SDValue Op2 = Op.getOperand(2);
14427 EVT VT = Op1.getValueType();
14430 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14431 // are available or VBLENDV if AVX is available.
14432 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14433 if (Cond.getOpcode() == ISD::SETCC &&
14434 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14435 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14436 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14437 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14438 int SSECC = translateX86FSETCC(
14439 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14442 if (Subtarget->hasAVX512()) {
14443 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14444 DAG.getConstant(SSECC, DL, MVT::i8));
14445 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14448 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14449 DAG.getConstant(SSECC, DL, MVT::i8));
14451 // If we have AVX, we can use a variable vector select (VBLENDV) instead
14452 // of 3 logic instructions for size savings and potentially speed.
14453 // Unfortunately, there is no scalar form of VBLENDV.
14455 // If either operand is a constant, don't try this. We can expect to
14456 // optimize away at least one of the logic instructions later in that
14457 // case, so that sequence would be faster than a variable blend.
14459 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14460 // uses XMM0 as the selection register. That may need just as many
14461 // instructions as the AND/ANDN/OR sequence due to register moves, so
14464 if (Subtarget->hasAVX() &&
14465 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14467 // Convert to vectors, do a VSELECT, and convert back to scalar.
14468 // All of the conversions should be optimized away.
14470 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14471 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14472 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14473 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14475 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14476 VCmp = DAG.getBitcast(VCmpVT, VCmp);
14478 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14480 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14481 VSel, DAG.getIntPtrConstant(0, DL));
14483 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14484 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14485 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14489 if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14491 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14492 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14493 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14494 Op1Scalar = Op1.getOperand(0);
14496 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14497 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14498 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14499 Op2Scalar = Op2.getOperand(0);
14500 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14501 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14502 Op1Scalar.getValueType(),
14503 Cond, Op1Scalar, Op2Scalar);
14504 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14505 return DAG.getBitcast(VT, newSelect);
14506 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14507 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14508 DAG.getIntPtrConstant(0, DL));
14512 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14513 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14514 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14515 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14516 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14517 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14518 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14520 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14523 if (Cond.getOpcode() == ISD::SETCC) {
14524 SDValue NewCond = LowerSETCC(Cond, DAG);
14525 if (NewCond.getNode())
14529 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14530 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14531 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14532 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14533 if (Cond.getOpcode() == X86ISD::SETCC &&
14534 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14535 isZero(Cond.getOperand(1).getOperand(1))) {
14536 SDValue Cmp = Cond.getOperand(1);
14538 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14540 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14541 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14542 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14544 SDValue CmpOp0 = Cmp.getOperand(0);
14545 // Apply further optimizations for special cases
14546 // (select (x != 0), -1, 0) -> neg & sbb
14547 // (select (x == 0), 0, -1) -> neg & sbb
14548 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14549 if (YC->isNullValue() &&
14550 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14551 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14552 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14553 DAG.getConstant(0, DL,
14554 CmpOp0.getValueType()),
14556 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14557 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14558 SDValue(Neg.getNode(), 1));
14562 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14563 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14564 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14566 SDValue Res = // Res = 0 or -1.
14567 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14568 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14570 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14571 Res = DAG.getNOT(DL, Res, Res.getValueType());
14573 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14574 if (!N2C || !N2C->isNullValue())
14575 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14580 // Look past (and (setcc_carry (cmp ...)), 1).
14581 if (Cond.getOpcode() == ISD::AND &&
14582 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14583 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14584 if (C && C->getAPIntValue() == 1)
14585 Cond = Cond.getOperand(0);
14588 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14589 // setting operand in place of the X86ISD::SETCC.
14590 unsigned CondOpcode = Cond.getOpcode();
14591 if (CondOpcode == X86ISD::SETCC ||
14592 CondOpcode == X86ISD::SETCC_CARRY) {
14593 CC = Cond.getOperand(0);
14595 SDValue Cmp = Cond.getOperand(1);
14596 unsigned Opc = Cmp.getOpcode();
14597 MVT VT = Op.getSimpleValueType();
14599 bool IllegalFPCMov = false;
14600 if (VT.isFloatingPoint() && !VT.isVector() &&
14601 !isScalarFPTypeInSSEReg(VT)) // FPStack?
14602 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14604 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14605 Opc == X86ISD::BT) { // FIXME
14609 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14610 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14611 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14612 Cond.getOperand(0).getValueType() != MVT::i8)) {
14613 SDValue LHS = Cond.getOperand(0);
14614 SDValue RHS = Cond.getOperand(1);
14615 unsigned X86Opcode;
14618 switch (CondOpcode) {
14619 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14620 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14621 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14622 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14623 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14624 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14625 default: llvm_unreachable("unexpected overflowing operator");
14627 if (CondOpcode == ISD::UMULO)
14628 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14631 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14633 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14635 if (CondOpcode == ISD::UMULO)
14636 Cond = X86Op.getValue(2);
14638 Cond = X86Op.getValue(1);
14640 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14645 // Look past the truncate if the high bits are known zero.
14646 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14647 Cond = Cond.getOperand(0);
14649 // We know the result of AND is compared against zero. Try to match
14651 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14652 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14653 if (NewSetCC.getNode()) {
14654 CC = NewSetCC.getOperand(0);
14655 Cond = NewSetCC.getOperand(1);
14662 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14663 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14666 // a < b ? -1 : 0 -> RES = ~setcc_carry
14667 // a < b ? 0 : -1 -> RES = setcc_carry
14668 // a >= b ? -1 : 0 -> RES = setcc_carry
14669 // a >= b ? 0 : -1 -> RES = ~setcc_carry
14670 if (Cond.getOpcode() == X86ISD::SUB) {
14671 Cond = ConvertCmpIfNecessary(Cond, DAG);
14672 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14674 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14675 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14676 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14677 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14679 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14680 return DAG.getNOT(DL, Res, Res.getValueType());
14685 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14686 // widen the cmov and push the truncate through. This avoids introducing a new
14687 // branch during isel and doesn't add any extensions.
14688 if (Op.getValueType() == MVT::i8 &&
14689 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14690 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14691 if (T1.getValueType() == T2.getValueType() &&
14692 // Blacklist CopyFromReg to avoid partial register stalls.
14693 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14694 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14695 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14696 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14700 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14701 // condition is true.
14702 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14703 SDValue Ops[] = { Op2, Op1, CC, Cond };
14704 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14707 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14708 const X86Subtarget *Subtarget,
14709 SelectionDAG &DAG) {
14710 MVT VT = Op->getSimpleValueType(0);
14711 SDValue In = Op->getOperand(0);
14712 MVT InVT = In.getSimpleValueType();
14713 MVT VTElt = VT.getVectorElementType();
14714 MVT InVTElt = InVT.getVectorElementType();
14718 if ((InVTElt == MVT::i1) &&
14719 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14720 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14722 ((Subtarget->hasBWI() && VT.is512BitVector() &&
14723 VTElt.getSizeInBits() <= 16)) ||
14725 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14726 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14728 ((Subtarget->hasDQI() && VT.is512BitVector() &&
14729 VTElt.getSizeInBits() >= 32))))
14730 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14732 unsigned int NumElts = VT.getVectorNumElements();
14734 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14737 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14738 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14739 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14740 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14743 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14744 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14746 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14749 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14751 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14752 if (VT.is512BitVector())
14754 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14757 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14758 const X86Subtarget *Subtarget,
14759 SelectionDAG &DAG) {
14760 SDValue In = Op->getOperand(0);
14761 MVT VT = Op->getSimpleValueType(0);
14762 MVT InVT = In.getSimpleValueType();
14763 assert(VT.getSizeInBits() == InVT.getSizeInBits());
14765 MVT InSVT = InVT.getScalarType();
14766 assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14768 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14770 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14775 // SSE41 targets can use the pmovsx* instructions directly.
14776 if (Subtarget->hasSSE41())
14777 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14779 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14783 // As SRAI is only available on i16/i32 types, we expand only up to i32
14784 // and handle i64 separately.
14785 while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14786 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14787 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14788 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14789 Curr = DAG.getBitcast(CurrVT, Curr);
14792 SDValue SignExt = Curr;
14793 if (CurrVT != InVT) {
14794 unsigned SignExtShift =
14795 CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14796 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14797 DAG.getConstant(SignExtShift, dl, MVT::i8));
14803 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14804 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14805 DAG.getConstant(31, dl, MVT::i8));
14806 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14807 return DAG.getBitcast(VT, Ext);
14813 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14814 SelectionDAG &DAG) {
14815 MVT VT = Op->getSimpleValueType(0);
14816 SDValue In = Op->getOperand(0);
14817 MVT InVT = In.getSimpleValueType();
14820 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14821 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14823 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14824 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14825 (VT != MVT::v16i16 || InVT != MVT::v16i8))
14828 if (Subtarget->hasInt256())
14829 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14831 // Optimize vectors in AVX mode
14832 // Sign extend v8i16 to v8i32 and
14835 // Divide input vector into two parts
14836 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14837 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14838 // concat the vectors to original VT
14840 unsigned NumElems = InVT.getVectorNumElements();
14841 SDValue Undef = DAG.getUNDEF(InVT);
14843 SmallVector<int,8> ShufMask1(NumElems, -1);
14844 for (unsigned i = 0; i != NumElems/2; ++i)
14847 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14849 SmallVector<int,8> ShufMask2(NumElems, -1);
14850 for (unsigned i = 0; i != NumElems/2; ++i)
14851 ShufMask2[i] = i + NumElems/2;
14853 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14855 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14856 VT.getVectorNumElements()/2);
14858 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14859 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14861 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14864 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14865 // may emit an illegal shuffle but the expansion is still better than scalar
14866 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14867 // we'll emit a shuffle and a arithmetic shift.
14868 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14869 // TODO: It is possible to support ZExt by zeroing the undef values during
14870 // the shuffle phase or after the shuffle.
14871 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14872 SelectionDAG &DAG) {
14873 MVT RegVT = Op.getSimpleValueType();
14874 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14875 assert(RegVT.isInteger() &&
14876 "We only custom lower integer vector sext loads.");
14878 // Nothing useful we can do without SSE2 shuffles.
14879 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14881 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14883 EVT MemVT = Ld->getMemoryVT();
14884 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14885 unsigned RegSz = RegVT.getSizeInBits();
14887 ISD::LoadExtType Ext = Ld->getExtensionType();
14889 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14890 && "Only anyext and sext are currently implemented.");
14891 assert(MemVT != RegVT && "Cannot extend to the same type");
14892 assert(MemVT.isVector() && "Must load a vector from memory");
14894 unsigned NumElems = RegVT.getVectorNumElements();
14895 unsigned MemSz = MemVT.getSizeInBits();
14896 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14898 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14899 // The only way in which we have a legal 256-bit vector result but not the
14900 // integer 256-bit operations needed to directly lower a sextload is if we
14901 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14902 // a 128-bit vector and a normal sign_extend to 256-bits that should get
14903 // correctly legalized. We do this late to allow the canonical form of
14904 // sextload to persist throughout the rest of the DAG combiner -- it wants
14905 // to fold together any extensions it can, and so will fuse a sign_extend
14906 // of an sextload into a sextload targeting a wider value.
14908 if (MemSz == 128) {
14909 // Just switch this to a normal load.
14910 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14911 "it must be a legal 128-bit vector "
14913 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14914 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14915 Ld->isInvariant(), Ld->getAlignment());
14917 assert(MemSz < 128 &&
14918 "Can't extend a type wider than 128 bits to a 256 bit vector!");
14919 // Do an sext load to a 128-bit vector type. We want to use the same
14920 // number of elements, but elements half as wide. This will end up being
14921 // recursively lowered by this routine, but will succeed as we definitely
14922 // have all the necessary features if we're using AVX1.
14924 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14925 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14927 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14928 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14929 Ld->isNonTemporal(), Ld->isInvariant(),
14930 Ld->getAlignment());
14933 // Replace chain users with the new chain.
14934 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14935 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14937 // Finally, do a normal sign-extend to the desired register.
14938 return DAG.getSExtOrTrunc(Load, dl, RegVT);
14941 // All sizes must be a power of two.
14942 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14943 "Non-power-of-two elements are not custom lowered!");
14945 // Attempt to load the original value using scalar loads.
14946 // Find the largest scalar type that divides the total loaded size.
14947 MVT SclrLoadTy = MVT::i8;
14948 for (MVT Tp : MVT::integer_valuetypes()) {
14949 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14954 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14955 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14957 SclrLoadTy = MVT::f64;
14959 // Calculate the number of scalar loads that we need to perform
14960 // in order to load our vector from memory.
14961 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14963 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14964 "Can only lower sext loads with a single scalar load!");
14966 unsigned loadRegZize = RegSz;
14967 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14970 // Represent our vector as a sequence of elements which are the
14971 // largest scalar that we can load.
14972 EVT LoadUnitVecVT = EVT::getVectorVT(
14973 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14975 // Represent the data using the same element type that is stored in
14976 // memory. In practice, we ''widen'' MemVT.
14978 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14979 loadRegZize / MemVT.getScalarType().getSizeInBits());
14981 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14982 "Invalid vector type");
14984 // We can't shuffle using an illegal type.
14985 assert(TLI.isTypeLegal(WideVecVT) &&
14986 "We only lower types that form legal widened vector types");
14988 SmallVector<SDValue, 8> Chains;
14989 SDValue Ptr = Ld->getBasePtr();
14990 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14991 TLI.getPointerTy(DAG.getDataLayout()));
14992 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14994 for (unsigned i = 0; i < NumLoads; ++i) {
14995 // Perform a single load.
14996 SDValue ScalarLoad =
14997 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14998 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14999 Ld->getAlignment());
15000 Chains.push_back(ScalarLoad.getValue(1));
15001 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15002 // another round of DAGCombining.
15004 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15006 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15007 ScalarLoad, DAG.getIntPtrConstant(i, dl));
15009 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15012 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15014 // Bitcast the loaded value to a vector of the original element type, in
15015 // the size of the target vector type.
15016 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15017 unsigned SizeRatio = RegSz / MemSz;
15019 if (Ext == ISD::SEXTLOAD) {
15020 // If we have SSE4.1, we can directly emit a VSEXT node.
15021 if (Subtarget->hasSSE41()) {
15022 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15023 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15027 // Otherwise we'll shuffle the small elements in the high bits of the
15028 // larger type and perform an arithmetic shift. If the shift is not legal
15029 // it's better to scalarize.
15030 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
15031 "We can't implement a sext load without an arithmetic right shift!");
15033 // Redistribute the loaded elements into the different locations.
15034 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15035 for (unsigned i = 0; i != NumElems; ++i)
15036 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
15038 SDValue Shuff = DAG.getVectorShuffle(
15039 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15041 Shuff = DAG.getBitcast(RegVT, Shuff);
15043 // Build the arithmetic shift.
15044 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
15045 MemVT.getVectorElementType().getSizeInBits();
15047 DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
15048 DAG.getConstant(Amt, dl, RegVT));
15050 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15054 // Redistribute the loaded elements into the different locations.
15055 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15056 for (unsigned i = 0; i != NumElems; ++i)
15057 ShuffleVec[i * SizeRatio] = i;
15059 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15060 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15062 // Bitcast to the requested type.
15063 Shuff = DAG.getBitcast(RegVT, Shuff);
15064 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15068 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15069 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15070 // from the AND / OR.
15071 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15072 Opc = Op.getOpcode();
15073 if (Opc != ISD::OR && Opc != ISD::AND)
15075 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15076 Op.getOperand(0).hasOneUse() &&
15077 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15078 Op.getOperand(1).hasOneUse());
15081 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15082 // 1 and that the SETCC node has a single use.
15083 static bool isXor1OfSetCC(SDValue Op) {
15084 if (Op.getOpcode() != ISD::XOR)
15086 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15087 if (N1C && N1C->getAPIntValue() == 1) {
15088 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15089 Op.getOperand(0).hasOneUse();
15094 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15095 bool addTest = true;
15096 SDValue Chain = Op.getOperand(0);
15097 SDValue Cond = Op.getOperand(1);
15098 SDValue Dest = Op.getOperand(2);
15101 bool Inverted = false;
15103 if (Cond.getOpcode() == ISD::SETCC) {
15104 // Check for setcc([su]{add,sub,mul}o == 0).
15105 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15106 isa<ConstantSDNode>(Cond.getOperand(1)) &&
15107 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
15108 Cond.getOperand(0).getResNo() == 1 &&
15109 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15110 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15111 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15112 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15113 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15114 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15116 Cond = Cond.getOperand(0);
15118 SDValue NewCond = LowerSETCC(Cond, DAG);
15119 if (NewCond.getNode())
15124 // FIXME: LowerXALUO doesn't handle these!!
15125 else if (Cond.getOpcode() == X86ISD::ADD ||
15126 Cond.getOpcode() == X86ISD::SUB ||
15127 Cond.getOpcode() == X86ISD::SMUL ||
15128 Cond.getOpcode() == X86ISD::UMUL)
15129 Cond = LowerXALUO(Cond, DAG);
15132 // Look pass (and (setcc_carry (cmp ...)), 1).
15133 if (Cond.getOpcode() == ISD::AND &&
15134 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
15135 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
15136 if (C && C->getAPIntValue() == 1)
15137 Cond = Cond.getOperand(0);
15140 // If condition flag is set by a X86ISD::CMP, then use it as the condition
15141 // setting operand in place of the X86ISD::SETCC.
15142 unsigned CondOpcode = Cond.getOpcode();
15143 if (CondOpcode == X86ISD::SETCC ||
15144 CondOpcode == X86ISD::SETCC_CARRY) {
15145 CC = Cond.getOperand(0);
15147 SDValue Cmp = Cond.getOperand(1);
15148 unsigned Opc = Cmp.getOpcode();
15149 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15150 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15154 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15158 // These can only come from an arithmetic instruction with overflow,
15159 // e.g. SADDO, UADDO.
15160 Cond = Cond.getNode()->getOperand(1);
15166 CondOpcode = Cond.getOpcode();
15167 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15168 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15169 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15170 Cond.getOperand(0).getValueType() != MVT::i8)) {
15171 SDValue LHS = Cond.getOperand(0);
15172 SDValue RHS = Cond.getOperand(1);
15173 unsigned X86Opcode;
15176 // Keep this in sync with LowerXALUO, otherwise we might create redundant
15177 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15179 switch (CondOpcode) {
15180 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15182 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15184 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15187 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15188 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15190 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15192 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15195 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15196 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15197 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15198 default: llvm_unreachable("unexpected overflowing operator");
15201 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15202 if (CondOpcode == ISD::UMULO)
15203 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15206 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15208 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15210 if (CondOpcode == ISD::UMULO)
15211 Cond = X86Op.getValue(2);
15213 Cond = X86Op.getValue(1);
15215 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15219 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15220 SDValue Cmp = Cond.getOperand(0).getOperand(1);
15221 if (CondOpc == ISD::OR) {
15222 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15223 // two branches instead of an explicit OR instruction with a
15225 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15226 isX86LogicalCmp(Cmp)) {
15227 CC = Cond.getOperand(0).getOperand(0);
15228 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15229 Chain, Dest, CC, Cmp);
15230 CC = Cond.getOperand(1).getOperand(0);
15234 } else { // ISD::AND
15235 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15236 // two branches instead of an explicit AND instruction with a
15237 // separate test. However, we only do this if this block doesn't
15238 // have a fall-through edge, because this requires an explicit
15239 // jmp when the condition is false.
15240 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15241 isX86LogicalCmp(Cmp) &&
15242 Op.getNode()->hasOneUse()) {
15243 X86::CondCode CCode =
15244 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15245 CCode = X86::GetOppositeBranchCondition(CCode);
15246 CC = DAG.getConstant(CCode, dl, MVT::i8);
15247 SDNode *User = *Op.getNode()->use_begin();
15248 // Look for an unconditional branch following this conditional branch.
15249 // We need this because we need to reverse the successors in order
15250 // to implement FCMP_OEQ.
15251 if (User->getOpcode() == ISD::BR) {
15252 SDValue FalseBB = User->getOperand(1);
15254 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15255 assert(NewBR == User);
15259 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15260 Chain, Dest, CC, Cmp);
15261 X86::CondCode CCode =
15262 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15263 CCode = X86::GetOppositeBranchCondition(CCode);
15264 CC = DAG.getConstant(CCode, dl, MVT::i8);
15270 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15271 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15272 // It should be transformed during dag combiner except when the condition
15273 // is set by a arithmetics with overflow node.
15274 X86::CondCode CCode =
15275 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15276 CCode = X86::GetOppositeBranchCondition(CCode);
15277 CC = DAG.getConstant(CCode, dl, MVT::i8);
15278 Cond = Cond.getOperand(0).getOperand(1);
15280 } else if (Cond.getOpcode() == ISD::SETCC &&
15281 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15282 // For FCMP_OEQ, we can emit
15283 // two branches instead of an explicit AND instruction with a
15284 // separate test. However, we only do this if this block doesn't
15285 // have a fall-through edge, because this requires an explicit
15286 // jmp when the condition is false.
15287 if (Op.getNode()->hasOneUse()) {
15288 SDNode *User = *Op.getNode()->use_begin();
15289 // Look for an unconditional branch following this conditional branch.
15290 // We need this because we need to reverse the successors in order
15291 // to implement FCMP_OEQ.
15292 if (User->getOpcode() == ISD::BR) {
15293 SDValue FalseBB = User->getOperand(1);
15295 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15296 assert(NewBR == User);
15300 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15301 Cond.getOperand(0), Cond.getOperand(1));
15302 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15303 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15304 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15305 Chain, Dest, CC, Cmp);
15306 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15311 } else if (Cond.getOpcode() == ISD::SETCC &&
15312 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15313 // For FCMP_UNE, we can emit
15314 // two branches instead of an explicit AND instruction with a
15315 // separate test. However, we only do this if this block doesn't
15316 // have a fall-through edge, because this requires an explicit
15317 // jmp when the condition is false.
15318 if (Op.getNode()->hasOneUse()) {
15319 SDNode *User = *Op.getNode()->use_begin();
15320 // Look for an unconditional branch following this conditional branch.
15321 // We need this because we need to reverse the successors in order
15322 // to implement FCMP_UNE.
15323 if (User->getOpcode() == ISD::BR) {
15324 SDValue FalseBB = User->getOperand(1);
15326 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15327 assert(NewBR == User);
15330 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15331 Cond.getOperand(0), Cond.getOperand(1));
15332 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15333 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15334 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15335 Chain, Dest, CC, Cmp);
15336 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15346 // Look pass the truncate if the high bits are known zero.
15347 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15348 Cond = Cond.getOperand(0);
15350 // We know the result of AND is compared against zero. Try to match
15352 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15353 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15354 if (NewSetCC.getNode()) {
15355 CC = NewSetCC.getOperand(0);
15356 Cond = NewSetCC.getOperand(1);
15363 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15364 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15365 Cond = EmitTest(Cond, X86Cond, dl, DAG);
15367 Cond = ConvertCmpIfNecessary(Cond, DAG);
15368 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15369 Chain, Dest, CC, Cond);
15372 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15373 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15374 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15375 // that the guard pages used by the OS virtual memory manager are allocated in
15376 // correct sequence.
15378 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15379 SelectionDAG &DAG) const {
15380 MachineFunction &MF = DAG.getMachineFunction();
15381 bool SplitStack = MF.shouldSplitStack();
15382 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15387 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15388 SDNode* Node = Op.getNode();
15390 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15391 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15392 " not tell us which reg is the stack pointer!");
15393 EVT VT = Node->getValueType(0);
15394 SDValue Tmp1 = SDValue(Node, 0);
15395 SDValue Tmp2 = SDValue(Node, 1);
15396 SDValue Tmp3 = Node->getOperand(2);
15397 SDValue Chain = Tmp1.getOperand(0);
15399 // Chain the dynamic stack allocation so that it doesn't modify the stack
15400 // pointer when other instructions are using the stack.
15401 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15404 SDValue Size = Tmp2.getOperand(1);
15405 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15406 Chain = SP.getValue(1);
15407 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15408 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15409 unsigned StackAlign = TFI.getStackAlignment();
15410 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15411 if (Align > StackAlign)
15412 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15413 DAG.getConstant(-(uint64_t)Align, dl, VT));
15414 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15416 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15417 DAG.getIntPtrConstant(0, dl, true), SDValue(),
15420 SDValue Ops[2] = { Tmp1, Tmp2 };
15421 return DAG.getMergeValues(Ops, dl);
15425 SDValue Chain = Op.getOperand(0);
15426 SDValue Size = Op.getOperand(1);
15427 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15428 EVT VT = Op.getNode()->getValueType(0);
15430 bool Is64Bit = Subtarget->is64Bit();
15431 MVT SPTy = getPointerTy(DAG.getDataLayout());
15434 MachineRegisterInfo &MRI = MF.getRegInfo();
15437 // The 64 bit implementation of segmented stacks needs to clobber both r10
15438 // r11. This makes it impossible to use it along with nested parameters.
15439 const Function *F = MF.getFunction();
15441 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15443 if (I->hasNestAttr())
15444 report_fatal_error("Cannot use segmented stacks with functions that "
15445 "have nested arguments.");
15448 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15449 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15450 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15451 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15452 DAG.getRegister(Vreg, SPTy));
15453 SDValue Ops1[2] = { Value, Chain };
15454 return DAG.getMergeValues(Ops1, dl);
15457 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15459 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15460 Flag = Chain.getValue(1);
15461 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15463 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15465 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15466 unsigned SPReg = RegInfo->getStackRegister();
15467 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15468 Chain = SP.getValue(1);
15471 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15472 DAG.getConstant(-(uint64_t)Align, dl, VT));
15473 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15476 SDValue Ops1[2] = { SP, Chain };
15477 return DAG.getMergeValues(Ops1, dl);
15481 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15482 MachineFunction &MF = DAG.getMachineFunction();
15483 auto PtrVT = getPointerTy(MF.getDataLayout());
15484 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15486 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15489 if (!Subtarget->is64Bit() ||
15490 Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15491 // vastart just stores the address of the VarArgsFrameIndex slot into the
15492 // memory location argument.
15493 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15494 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15495 MachinePointerInfo(SV), false, false, 0);
15499 // gp_offset (0 - 6 * 8)
15500 // fp_offset (48 - 48 + 8 * 16)
15501 // overflow_arg_area (point to parameters coming in memory).
15503 SmallVector<SDValue, 8> MemOps;
15504 SDValue FIN = Op.getOperand(1);
15506 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15507 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15509 FIN, MachinePointerInfo(SV), false, false, 0);
15510 MemOps.push_back(Store);
15513 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15514 Store = DAG.getStore(Op.getOperand(0), DL,
15515 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15517 FIN, MachinePointerInfo(SV, 4), false, false, 0);
15518 MemOps.push_back(Store);
15520 // Store ptr to overflow_arg_area
15521 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15522 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15523 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15524 MachinePointerInfo(SV, 8),
15526 MemOps.push_back(Store);
15528 // Store ptr to reg_save_area.
15529 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15530 Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15531 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15532 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15533 SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15534 MemOps.push_back(Store);
15535 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15538 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15539 assert(Subtarget->is64Bit() &&
15540 "LowerVAARG only handles 64-bit va_arg!");
15541 assert(Op.getNode()->getNumOperands() == 4);
15543 MachineFunction &MF = DAG.getMachineFunction();
15544 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15545 // The Win64 ABI uses char* instead of a structure.
15546 return DAG.expandVAArg(Op.getNode());
15548 SDValue Chain = Op.getOperand(0);
15549 SDValue SrcPtr = Op.getOperand(1);
15550 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15551 unsigned Align = Op.getConstantOperandVal(3);
15554 EVT ArgVT = Op.getNode()->getValueType(0);
15555 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15556 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15559 // Decide which area this value should be read from.
15560 // TODO: Implement the AMD64 ABI in its entirety. This simple
15561 // selection mechanism works only for the basic types.
15562 if (ArgVT == MVT::f80) {
15563 llvm_unreachable("va_arg for f80 not yet implemented");
15564 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15565 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
15566 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15567 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
15569 llvm_unreachable("Unhandled argument type in LowerVAARG");
15572 if (ArgMode == 2) {
15573 // Sanity Check: Make sure using fp_offset makes sense.
15574 assert(!Subtarget->useSoftFloat() &&
15575 !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15576 Subtarget->hasSSE1());
15579 // Insert VAARG_64 node into the DAG
15580 // VAARG_64 returns two values: Variable Argument Address, Chain
15581 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15582 DAG.getConstant(ArgMode, dl, MVT::i8),
15583 DAG.getConstant(Align, dl, MVT::i32)};
15584 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15585 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15586 VTs, InstOps, MVT::i64,
15587 MachinePointerInfo(SV),
15589 /*Volatile=*/false,
15591 /*WriteMem=*/true);
15592 Chain = VAARG.getValue(1);
15594 // Load the next argument and return it
15595 return DAG.getLoad(ArgVT, dl,
15598 MachinePointerInfo(),
15599 false, false, false, 0);
15602 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15603 SelectionDAG &DAG) {
15604 // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15605 // where a va_list is still an i8*.
15606 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15607 if (Subtarget->isCallingConvWin64(
15608 DAG.getMachineFunction().getFunction()->getCallingConv()))
15609 // Probably a Win64 va_copy.
15610 return DAG.expandVACopy(Op.getNode());
15612 SDValue Chain = Op.getOperand(0);
15613 SDValue DstPtr = Op.getOperand(1);
15614 SDValue SrcPtr = Op.getOperand(2);
15615 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15616 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15619 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15620 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15622 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15625 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15626 // amount is a constant. Takes immediate version of shift as input.
15627 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15628 SDValue SrcOp, uint64_t ShiftAmt,
15629 SelectionDAG &DAG) {
15630 MVT ElementType = VT.getVectorElementType();
15632 // Fold this packed shift into its first operand if ShiftAmt is 0.
15636 // Check for ShiftAmt >= element width
15637 if (ShiftAmt >= ElementType.getSizeInBits()) {
15638 if (Opc == X86ISD::VSRAI)
15639 ShiftAmt = ElementType.getSizeInBits() - 1;
15641 return DAG.getConstant(0, dl, VT);
15644 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15645 && "Unknown target vector shift-by-constant node");
15647 // Fold this packed vector shift into a build vector if SrcOp is a
15648 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15649 if (VT == SrcOp.getSimpleValueType() &&
15650 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15651 SmallVector<SDValue, 8> Elts;
15652 unsigned NumElts = SrcOp->getNumOperands();
15653 ConstantSDNode *ND;
15656 default: llvm_unreachable(nullptr);
15657 case X86ISD::VSHLI:
15658 for (unsigned i=0; i!=NumElts; ++i) {
15659 SDValue CurrentOp = SrcOp->getOperand(i);
15660 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15661 Elts.push_back(CurrentOp);
15664 ND = cast<ConstantSDNode>(CurrentOp);
15665 const APInt &C = ND->getAPIntValue();
15666 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15669 case X86ISD::VSRLI:
15670 for (unsigned i=0; i!=NumElts; ++i) {
15671 SDValue CurrentOp = SrcOp->getOperand(i);
15672 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15673 Elts.push_back(CurrentOp);
15676 ND = cast<ConstantSDNode>(CurrentOp);
15677 const APInt &C = ND->getAPIntValue();
15678 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15681 case X86ISD::VSRAI:
15682 for (unsigned i=0; i!=NumElts; ++i) {
15683 SDValue CurrentOp = SrcOp->getOperand(i);
15684 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15685 Elts.push_back(CurrentOp);
15688 ND = cast<ConstantSDNode>(CurrentOp);
15689 const APInt &C = ND->getAPIntValue();
15690 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15695 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15698 return DAG.getNode(Opc, dl, VT, SrcOp,
15699 DAG.getConstant(ShiftAmt, dl, MVT::i8));
15702 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15703 // may or may not be a constant. Takes immediate version of shift as input.
15704 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15705 SDValue SrcOp, SDValue ShAmt,
15706 SelectionDAG &DAG) {
15707 MVT SVT = ShAmt.getSimpleValueType();
15708 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15710 // Catch shift-by-constant.
15711 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15712 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15713 CShAmt->getZExtValue(), DAG);
15715 // Change opcode to non-immediate version
15717 default: llvm_unreachable("Unknown target vector shift node");
15718 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15719 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15720 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15723 const X86Subtarget &Subtarget =
15724 static_cast<const X86Subtarget &>(DAG.getSubtarget());
15725 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15726 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15727 // Let the shuffle legalizer expand this shift amount node.
15728 SDValue Op0 = ShAmt.getOperand(0);
15729 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15730 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15732 // Need to build a vector containing shift amount.
15733 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15734 SmallVector<SDValue, 4> ShOps;
15735 ShOps.push_back(ShAmt);
15736 if (SVT == MVT::i32) {
15737 ShOps.push_back(DAG.getConstant(0, dl, SVT));
15738 ShOps.push_back(DAG.getUNDEF(SVT));
15740 ShOps.push_back(DAG.getUNDEF(SVT));
15742 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15743 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15746 // The return type has to be a 128-bit type with the same element
15747 // type as the input type.
15748 MVT EltVT = VT.getVectorElementType();
15749 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15751 ShAmt = DAG.getBitcast(ShVT, ShAmt);
15752 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15755 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15756 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15757 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15758 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15759 SDValue PreservedSrc,
15760 const X86Subtarget *Subtarget,
15761 SelectionDAG &DAG) {
15762 EVT VT = Op.getValueType();
15763 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15764 MVT::i1, VT.getVectorNumElements());
15765 SDValue VMask = SDValue();
15766 unsigned OpcodeSelect = ISD::VSELECT;
15769 assert(MaskVT.isSimple() && "invalid mask type");
15771 if (isAllOnes(Mask))
15774 if (MaskVT.bitsGT(Mask.getValueType())) {
15775 EVT newMaskVT = EVT::getIntegerVT(*DAG.getContext(),
15776 MaskVT.getSizeInBits());
15777 VMask = DAG.getBitcast(MaskVT,
15778 DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15780 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15781 Mask.getValueType().getSizeInBits());
15782 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15783 // are extracted by EXTRACT_SUBVECTOR.
15784 VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15785 DAG.getBitcast(BitcastVT, Mask),
15786 DAG.getIntPtrConstant(0, dl));
15789 switch (Op.getOpcode()) {
15791 case X86ISD::PCMPEQM:
15792 case X86ISD::PCMPGTM:
15794 case X86ISD::CMPMU:
15795 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15796 case X86ISD::VFPCLASS:
15797 return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
15798 case X86ISD::VTRUNC:
15799 case X86ISD::VTRUNCS:
15800 case X86ISD::VTRUNCUS:
15801 // We can't use ISD::VSELECT here because it is not always "Legal"
15802 // for the destination type. For example vpmovqb require only AVX512
15803 // and vselect that can operate on byte element type require BWI
15804 OpcodeSelect = X86ISD::SELECT;
15807 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15808 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15809 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15812 /// \brief Creates an SDNode for a predicated scalar operation.
15813 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15814 /// The mask is coming as MVT::i8 and it should be truncated
15815 /// to MVT::i1 while lowering masking intrinsics.
15816 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15817 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15818 /// for a scalar instruction.
15819 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15820 SDValue PreservedSrc,
15821 const X86Subtarget *Subtarget,
15822 SelectionDAG &DAG) {
15823 if (isAllOnes(Mask))
15826 EVT VT = Op.getValueType();
15828 // The mask should be of type MVT::i1
15829 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15831 if (Op.getOpcode() == X86ISD::FSETCC)
15832 return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
15834 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15835 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15836 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15839 static int getSEHRegistrationNodeSize(const Function *Fn) {
15840 if (!Fn->hasPersonalityFn())
15841 report_fatal_error(
15842 "querying registration node size for function without personality");
15843 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15844 // WinEHStatePass for the full struct definition.
15845 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15846 case EHPersonality::MSVC_X86SEH: return 24;
15847 case EHPersonality::MSVC_CXX: return 16;
15850 report_fatal_error("can only recover FP for MSVC EH personality functions");
15853 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15854 /// function or when returning to a parent frame after catching an exception, we
15855 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15856 /// Here's the math:
15857 /// RegNodeBase = EntryEBP - RegNodeSize
15858 /// ParentFP = RegNodeBase - RegNodeFrameOffset
15859 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15860 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15861 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15862 SDValue EntryEBP) {
15863 MachineFunction &MF = DAG.getMachineFunction();
15866 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15867 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15869 // It's possible that the parent function no longer has a personality function
15870 // if the exceptional code was optimized away, in which case we just return
15871 // the incoming EBP.
15872 if (!Fn->hasPersonalityFn())
15875 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15877 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15879 MCSymbol *OffsetSym =
15880 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15881 GlobalValue::getRealLinkageName(Fn->getName()));
15882 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15883 SDValue RegNodeFrameOffset =
15884 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15886 // RegNodeBase = EntryEBP - RegNodeSize
15887 // ParentFP = RegNodeBase - RegNodeFrameOffset
15888 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15889 DAG.getConstant(RegNodeSize, dl, PtrVT));
15890 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15893 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15894 SelectionDAG &DAG) {
15896 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15897 EVT VT = Op.getValueType();
15898 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15900 switch(IntrData->Type) {
15901 case INTR_TYPE_1OP:
15902 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15903 case INTR_TYPE_2OP:
15904 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15906 case INTR_TYPE_2OP_IMM8:
15907 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15908 DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
15909 case INTR_TYPE_3OP:
15910 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15911 Op.getOperand(2), Op.getOperand(3));
15912 case INTR_TYPE_4OP:
15913 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15914 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15915 case INTR_TYPE_1OP_MASK_RM: {
15916 SDValue Src = Op.getOperand(1);
15917 SDValue PassThru = Op.getOperand(2);
15918 SDValue Mask = Op.getOperand(3);
15919 SDValue RoundingMode;
15920 // We allways add rounding mode to the Node.
15921 // If the rounding mode is not specified, we add the
15922 // "current direction" mode.
15923 if (Op.getNumOperands() == 4)
15925 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15927 RoundingMode = Op.getOperand(4);
15928 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15929 if (IntrWithRoundingModeOpcode != 0)
15930 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15931 X86::STATIC_ROUNDING::CUR_DIRECTION)
15932 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15933 dl, Op.getValueType(), Src, RoundingMode),
15934 Mask, PassThru, Subtarget, DAG);
15935 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15937 Mask, PassThru, Subtarget, DAG);
15939 case INTR_TYPE_1OP_MASK: {
15940 SDValue Src = Op.getOperand(1);
15941 SDValue PassThru = Op.getOperand(2);
15942 SDValue Mask = Op.getOperand(3);
15943 // We add rounding mode to the Node when
15944 // - RM Opcode is specified and
15945 // - RM is not "current direction".
15946 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15947 if (IntrWithRoundingModeOpcode != 0) {
15948 SDValue Rnd = Op.getOperand(4);
15949 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15950 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15951 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15952 dl, Op.getValueType(),
15954 Mask, PassThru, Subtarget, DAG);
15957 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15958 Mask, PassThru, Subtarget, DAG);
15960 case INTR_TYPE_SCALAR_MASK: {
15961 SDValue Src1 = Op.getOperand(1);
15962 SDValue Src2 = Op.getOperand(2);
15963 SDValue passThru = Op.getOperand(3);
15964 SDValue Mask = Op.getOperand(4);
15965 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
15966 Mask, passThru, Subtarget, DAG);
15968 case INTR_TYPE_SCALAR_MASK_RM: {
15969 SDValue Src1 = Op.getOperand(1);
15970 SDValue Src2 = Op.getOperand(2);
15971 SDValue Src0 = Op.getOperand(3);
15972 SDValue Mask = Op.getOperand(4);
15973 // There are 2 kinds of intrinsics in this group:
15974 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15975 // (2) With rounding mode and sae - 7 operands.
15976 if (Op.getNumOperands() == 6) {
15977 SDValue Sae = Op.getOperand(5);
15978 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15979 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15981 Mask, Src0, Subtarget, DAG);
15983 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15984 SDValue RoundingMode = Op.getOperand(5);
15985 SDValue Sae = Op.getOperand(6);
15986 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15987 RoundingMode, Sae),
15988 Mask, Src0, Subtarget, DAG);
15990 case INTR_TYPE_2OP_MASK: {
15991 SDValue Src1 = Op.getOperand(1);
15992 SDValue Src2 = Op.getOperand(2);
15993 SDValue PassThru = Op.getOperand(3);
15994 SDValue Mask = Op.getOperand(4);
15995 // We specify 2 possible opcodes for intrinsics with rounding modes.
15996 // First, we check if the intrinsic may have non-default rounding mode,
15997 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15998 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15999 if (IntrWithRoundingModeOpcode != 0) {
16000 SDValue Rnd = Op.getOperand(5);
16001 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16002 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16003 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16004 dl, Op.getValueType(),
16006 Mask, PassThru, Subtarget, DAG);
16009 // TODO: Intrinsics should have fast-math-flags to propagate.
16010 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16011 Mask, PassThru, Subtarget, DAG);
16013 case INTR_TYPE_2OP_MASK_RM: {
16014 SDValue Src1 = Op.getOperand(1);
16015 SDValue Src2 = Op.getOperand(2);
16016 SDValue PassThru = Op.getOperand(3);
16017 SDValue Mask = Op.getOperand(4);
16018 // We specify 2 possible modes for intrinsics, with/without rounding
16020 // First, we check if the intrinsic have rounding mode (6 operands),
16021 // if not, we set rounding mode to "current".
16023 if (Op.getNumOperands() == 6)
16024 Rnd = Op.getOperand(5);
16026 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16027 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16029 Mask, PassThru, Subtarget, DAG);
16031 case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16032 SDValue Src1 = Op.getOperand(1);
16033 SDValue Src2 = Op.getOperand(2);
16034 SDValue Src3 = Op.getOperand(3);
16035 SDValue PassThru = Op.getOperand(4);
16036 SDValue Mask = Op.getOperand(5);
16037 SDValue Sae = Op.getOperand(6);
16039 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16041 Mask, PassThru, Subtarget, DAG);
16043 case INTR_TYPE_3OP_MASK_RM: {
16044 SDValue Src1 = Op.getOperand(1);
16045 SDValue Src2 = Op.getOperand(2);
16046 SDValue Imm = Op.getOperand(3);
16047 SDValue PassThru = Op.getOperand(4);
16048 SDValue Mask = Op.getOperand(5);
16049 // We specify 2 possible modes for intrinsics, with/without rounding
16051 // First, we check if the intrinsic have rounding mode (7 operands),
16052 // if not, we set rounding mode to "current".
16054 if (Op.getNumOperands() == 7)
16055 Rnd = Op.getOperand(6);
16057 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16058 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16059 Src1, Src2, Imm, Rnd),
16060 Mask, PassThru, Subtarget, DAG);
16062 case INTR_TYPE_3OP_IMM8_MASK:
16063 case INTR_TYPE_3OP_MASK:
16064 case INSERT_SUBVEC: {
16065 SDValue Src1 = Op.getOperand(1);
16066 SDValue Src2 = Op.getOperand(2);
16067 SDValue Src3 = Op.getOperand(3);
16068 SDValue PassThru = Op.getOperand(4);
16069 SDValue Mask = Op.getOperand(5);
16071 if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16072 Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16073 else if (IntrData->Type == INSERT_SUBVEC) {
16074 // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16075 assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16076 unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16077 Imm *= Src2.getValueType().getVectorNumElements();
16078 Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16081 // We specify 2 possible opcodes for intrinsics with rounding modes.
16082 // First, we check if the intrinsic may have non-default rounding mode,
16083 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16084 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16085 if (IntrWithRoundingModeOpcode != 0) {
16086 SDValue Rnd = Op.getOperand(6);
16087 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16088 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16089 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16090 dl, Op.getValueType(),
16091 Src1, Src2, Src3, Rnd),
16092 Mask, PassThru, Subtarget, DAG);
16095 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16097 Mask, PassThru, Subtarget, DAG);
16099 case VPERM_3OP_MASKZ:
16100 case VPERM_3OP_MASK:
16103 case FMA_OP_MASK: {
16104 SDValue Src1 = Op.getOperand(1);
16105 SDValue Src2 = Op.getOperand(2);
16106 SDValue Src3 = Op.getOperand(3);
16107 SDValue Mask = Op.getOperand(4);
16108 EVT VT = Op.getValueType();
16109 SDValue PassThru = SDValue();
16111 // set PassThru element
16112 if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
16113 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16114 else if (IntrData->Type == FMA_OP_MASK3)
16119 // We specify 2 possible opcodes for intrinsics with rounding modes.
16120 // First, we check if the intrinsic may have non-default rounding mode,
16121 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16122 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16123 if (IntrWithRoundingModeOpcode != 0) {
16124 SDValue Rnd = Op.getOperand(5);
16125 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16126 X86::STATIC_ROUNDING::CUR_DIRECTION)
16127 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16128 dl, Op.getValueType(),
16129 Src1, Src2, Src3, Rnd),
16130 Mask, PassThru, Subtarget, DAG);
16132 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16133 dl, Op.getValueType(),
16135 Mask, PassThru, Subtarget, DAG);
16138 // FPclass intrinsics with mask
16139 SDValue Src1 = Op.getOperand(1);
16140 EVT VT = Src1.getValueType();
16141 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16142 VT.getVectorNumElements());
16143 SDValue Imm = Op.getOperand(2);
16144 SDValue Mask = Op.getOperand(3);
16145 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16146 Mask.getValueType().getSizeInBits());
16147 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16148 SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16149 DAG.getTargetConstant(0, dl, MaskVT),
16151 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16152 DAG.getUNDEF(BitcastVT), FPclassMask,
16153 DAG.getIntPtrConstant(0, dl));
16154 return DAG.getBitcast(Op.getValueType(), Res);
16157 case CMP_MASK_CC: {
16158 // Comparison intrinsics with masks.
16159 // Example of transformation:
16160 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16161 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16163 // (v8i1 (insert_subvector undef,
16164 // (v2i1 (and (PCMPEQM %a, %b),
16165 // (extract_subvector
16166 // (v8i1 (bitcast %mask)), 0))), 0))))
16167 EVT VT = Op.getOperand(1).getValueType();
16168 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16169 VT.getVectorNumElements());
16170 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16171 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16172 Mask.getValueType().getSizeInBits());
16174 if (IntrData->Type == CMP_MASK_CC) {
16175 SDValue CC = Op.getOperand(3);
16176 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16177 // We specify 2 possible opcodes for intrinsics with rounding modes.
16178 // First, we check if the intrinsic may have non-default rounding mode,
16179 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16180 if (IntrData->Opc1 != 0) {
16181 SDValue Rnd = Op.getOperand(5);
16182 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16183 X86::STATIC_ROUNDING::CUR_DIRECTION)
16184 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16185 Op.getOperand(2), CC, Rnd);
16187 //default rounding mode
16189 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16190 Op.getOperand(2), CC);
16193 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16194 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16197 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16198 DAG.getTargetConstant(0, dl,
16201 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16202 DAG.getUNDEF(BitcastVT), CmpMask,
16203 DAG.getIntPtrConstant(0, dl));
16204 return DAG.getBitcast(Op.getValueType(), Res);
16206 case CMP_MASK_SCALAR_CC: {
16207 SDValue Src1 = Op.getOperand(1);
16208 SDValue Src2 = Op.getOperand(2);
16209 SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16210 SDValue Mask = Op.getOperand(4);
16213 if (IntrData->Opc1 != 0) {
16214 SDValue Rnd = Op.getOperand(5);
16215 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16216 X86::STATIC_ROUNDING::CUR_DIRECTION)
16217 Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16219 //default rounding mode
16221 Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16223 SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16224 DAG.getTargetConstant(0, dl,
16228 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16229 DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16230 DAG.getValueType(MVT::i1));
16232 case COMI: { // Comparison intrinsics
16233 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16234 SDValue LHS = Op.getOperand(1);
16235 SDValue RHS = Op.getOperand(2);
16236 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16237 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16238 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16239 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16240 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16241 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16244 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16245 Op.getOperand(1), Op.getOperand(2), DAG);
16247 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16248 Op.getSimpleValueType(),
16250 Op.getOperand(2), DAG),
16251 Op.getOperand(4), Op.getOperand(3), Subtarget,
16253 case COMPRESS_EXPAND_IN_REG: {
16254 SDValue Mask = Op.getOperand(3);
16255 SDValue DataToCompress = Op.getOperand(1);
16256 SDValue PassThru = Op.getOperand(2);
16257 if (isAllOnes(Mask)) // return data as is
16258 return Op.getOperand(1);
16260 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16262 Mask, PassThru, Subtarget, DAG);
16265 SDValue Mask = Op.getOperand(3);
16266 EVT VT = Op.getValueType();
16267 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16268 VT.getVectorNumElements());
16269 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16270 Mask.getValueType().getSizeInBits());
16272 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16273 DAG.getBitcast(BitcastVT, Mask),
16274 DAG.getIntPtrConstant(0, dl));
16275 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16284 default: return SDValue(); // Don't custom lower most intrinsics.
16286 case Intrinsic::x86_avx2_permd:
16287 case Intrinsic::x86_avx2_permps:
16288 // Operands intentionally swapped. Mask is last operand to intrinsic,
16289 // but second operand for node/instruction.
16290 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16291 Op.getOperand(2), Op.getOperand(1));
16293 // ptest and testp intrinsics. The intrinsic these come from are designed to
16294 // return an integer value, not just an instruction so lower it to the ptest
16295 // or testp pattern and a setcc for the result.
16296 case Intrinsic::x86_sse41_ptestz:
16297 case Intrinsic::x86_sse41_ptestc:
16298 case Intrinsic::x86_sse41_ptestnzc:
16299 case Intrinsic::x86_avx_ptestz_256:
16300 case Intrinsic::x86_avx_ptestc_256:
16301 case Intrinsic::x86_avx_ptestnzc_256:
16302 case Intrinsic::x86_avx_vtestz_ps:
16303 case Intrinsic::x86_avx_vtestc_ps:
16304 case Intrinsic::x86_avx_vtestnzc_ps:
16305 case Intrinsic::x86_avx_vtestz_pd:
16306 case Intrinsic::x86_avx_vtestc_pd:
16307 case Intrinsic::x86_avx_vtestnzc_pd:
16308 case Intrinsic::x86_avx_vtestz_ps_256:
16309 case Intrinsic::x86_avx_vtestc_ps_256:
16310 case Intrinsic::x86_avx_vtestnzc_ps_256:
16311 case Intrinsic::x86_avx_vtestz_pd_256:
16312 case Intrinsic::x86_avx_vtestc_pd_256:
16313 case Intrinsic::x86_avx_vtestnzc_pd_256: {
16314 bool IsTestPacked = false;
16317 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16318 case Intrinsic::x86_avx_vtestz_ps:
16319 case Intrinsic::x86_avx_vtestz_pd:
16320 case Intrinsic::x86_avx_vtestz_ps_256:
16321 case Intrinsic::x86_avx_vtestz_pd_256:
16322 IsTestPacked = true; // Fallthrough
16323 case Intrinsic::x86_sse41_ptestz:
16324 case Intrinsic::x86_avx_ptestz_256:
16326 X86CC = X86::COND_E;
16328 case Intrinsic::x86_avx_vtestc_ps:
16329 case Intrinsic::x86_avx_vtestc_pd:
16330 case Intrinsic::x86_avx_vtestc_ps_256:
16331 case Intrinsic::x86_avx_vtestc_pd_256:
16332 IsTestPacked = true; // Fallthrough
16333 case Intrinsic::x86_sse41_ptestc:
16334 case Intrinsic::x86_avx_ptestc_256:
16336 X86CC = X86::COND_B;
16338 case Intrinsic::x86_avx_vtestnzc_ps:
16339 case Intrinsic::x86_avx_vtestnzc_pd:
16340 case Intrinsic::x86_avx_vtestnzc_ps_256:
16341 case Intrinsic::x86_avx_vtestnzc_pd_256:
16342 IsTestPacked = true; // Fallthrough
16343 case Intrinsic::x86_sse41_ptestnzc:
16344 case Intrinsic::x86_avx_ptestnzc_256:
16346 X86CC = X86::COND_A;
16350 SDValue LHS = Op.getOperand(1);
16351 SDValue RHS = Op.getOperand(2);
16352 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16353 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16354 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16355 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16356 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16358 case Intrinsic::x86_avx512_kortestz_w:
16359 case Intrinsic::x86_avx512_kortestc_w: {
16360 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16361 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16362 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16363 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16364 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16365 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16366 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16369 case Intrinsic::x86_sse42_pcmpistria128:
16370 case Intrinsic::x86_sse42_pcmpestria128:
16371 case Intrinsic::x86_sse42_pcmpistric128:
16372 case Intrinsic::x86_sse42_pcmpestric128:
16373 case Intrinsic::x86_sse42_pcmpistrio128:
16374 case Intrinsic::x86_sse42_pcmpestrio128:
16375 case Intrinsic::x86_sse42_pcmpistris128:
16376 case Intrinsic::x86_sse42_pcmpestris128:
16377 case Intrinsic::x86_sse42_pcmpistriz128:
16378 case Intrinsic::x86_sse42_pcmpestriz128: {
16382 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16383 case Intrinsic::x86_sse42_pcmpistria128:
16384 Opcode = X86ISD::PCMPISTRI;
16385 X86CC = X86::COND_A;
16387 case Intrinsic::x86_sse42_pcmpestria128:
16388 Opcode = X86ISD::PCMPESTRI;
16389 X86CC = X86::COND_A;
16391 case Intrinsic::x86_sse42_pcmpistric128:
16392 Opcode = X86ISD::PCMPISTRI;
16393 X86CC = X86::COND_B;
16395 case Intrinsic::x86_sse42_pcmpestric128:
16396 Opcode = X86ISD::PCMPESTRI;
16397 X86CC = X86::COND_B;
16399 case Intrinsic::x86_sse42_pcmpistrio128:
16400 Opcode = X86ISD::PCMPISTRI;
16401 X86CC = X86::COND_O;
16403 case Intrinsic::x86_sse42_pcmpestrio128:
16404 Opcode = X86ISD::PCMPESTRI;
16405 X86CC = X86::COND_O;
16407 case Intrinsic::x86_sse42_pcmpistris128:
16408 Opcode = X86ISD::PCMPISTRI;
16409 X86CC = X86::COND_S;
16411 case Intrinsic::x86_sse42_pcmpestris128:
16412 Opcode = X86ISD::PCMPESTRI;
16413 X86CC = X86::COND_S;
16415 case Intrinsic::x86_sse42_pcmpistriz128:
16416 Opcode = X86ISD::PCMPISTRI;
16417 X86CC = X86::COND_E;
16419 case Intrinsic::x86_sse42_pcmpestriz128:
16420 Opcode = X86ISD::PCMPESTRI;
16421 X86CC = X86::COND_E;
16424 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16425 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16426 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16427 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16428 DAG.getConstant(X86CC, dl, MVT::i8),
16429 SDValue(PCMP.getNode(), 1));
16430 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16433 case Intrinsic::x86_sse42_pcmpistri128:
16434 case Intrinsic::x86_sse42_pcmpestri128: {
16436 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16437 Opcode = X86ISD::PCMPISTRI;
16439 Opcode = X86ISD::PCMPESTRI;
16441 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16442 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16443 return DAG.getNode(Opcode, dl, VTs, NewOps);
16446 case Intrinsic::x86_seh_lsda: {
16447 // Compute the symbol for the LSDA. We know it'll get emitted later.
16448 MachineFunction &MF = DAG.getMachineFunction();
16449 SDValue Op1 = Op.getOperand(1);
16450 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16451 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16452 GlobalValue::getRealLinkageName(Fn->getName()));
16454 // Generate a simple absolute symbol reference. This intrinsic is only
16455 // supported on 32-bit Windows, which isn't PIC.
16456 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16457 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16460 case Intrinsic::x86_seh_recoverfp: {
16461 SDValue FnOp = Op.getOperand(1);
16462 SDValue IncomingFPOp = Op.getOperand(2);
16463 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16464 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16466 report_fatal_error(
16467 "llvm.x86.seh.recoverfp must take a function as the first argument");
16468 return recoverFramePointer(DAG, Fn, IncomingFPOp);
16471 case Intrinsic::localaddress: {
16472 // Returns one of the stack, base, or frame pointer registers, depending on
16473 // which is used to reference local variables.
16474 MachineFunction &MF = DAG.getMachineFunction();
16475 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16477 if (RegInfo->hasBasePointer(MF))
16478 Reg = RegInfo->getBaseRegister();
16479 else // This function handles the SP or FP case.
16480 Reg = RegInfo->getPtrSizedFrameRegister(MF);
16481 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16486 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16487 SDValue Src, SDValue Mask, SDValue Base,
16488 SDValue Index, SDValue ScaleOp, SDValue Chain,
16489 const X86Subtarget * Subtarget) {
16491 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16493 llvm_unreachable("Invalid scale type");
16494 unsigned ScaleVal = C->getZExtValue();
16495 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16496 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16498 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16499 EVT MaskVT = MVT::getVectorVT(MVT::i1,
16500 Index.getSimpleValueType().getVectorNumElements());
16502 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16504 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16506 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16507 Mask.getValueType().getSizeInBits());
16509 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16510 // are extracted by EXTRACT_SUBVECTOR.
16511 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16512 DAG.getBitcast(BitcastVT, Mask),
16513 DAG.getIntPtrConstant(0, dl));
16515 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16516 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16517 SDValue Segment = DAG.getRegister(0, MVT::i32);
16518 if (Src.getOpcode() == ISD::UNDEF)
16519 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16520 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16521 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16522 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16523 return DAG.getMergeValues(RetOps, dl);
16526 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16527 SDValue Src, SDValue Mask, SDValue Base,
16528 SDValue Index, SDValue ScaleOp, SDValue Chain) {
16530 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16532 llvm_unreachable("Invalid scale type");
16533 unsigned ScaleVal = C->getZExtValue();
16534 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16535 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16537 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16538 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16539 SDValue Segment = DAG.getRegister(0, MVT::i32);
16540 EVT MaskVT = MVT::getVectorVT(MVT::i1,
16541 Index.getSimpleValueType().getVectorNumElements());
16543 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16545 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16547 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16548 Mask.getValueType().getSizeInBits());
16550 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16551 // are extracted by EXTRACT_SUBVECTOR.
16552 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16553 DAG.getBitcast(BitcastVT, Mask),
16554 DAG.getIntPtrConstant(0, dl));
16556 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16557 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16558 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16559 return SDValue(Res, 1);
16562 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16563 SDValue Mask, SDValue Base, SDValue Index,
16564 SDValue ScaleOp, SDValue Chain) {
16566 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16567 assert(C && "Invalid scale type");
16568 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16569 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16570 SDValue Segment = DAG.getRegister(0, MVT::i32);
16572 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16574 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16576 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16578 MaskInReg = DAG.getBitcast(MaskVT, Mask);
16579 //SDVTList VTs = DAG.getVTList(MVT::Other);
16580 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16581 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16582 return SDValue(Res, 0);
16585 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16586 // read performance monitor counters (x86_rdpmc).
16587 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16588 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16589 SmallVectorImpl<SDValue> &Results) {
16590 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16591 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16594 // The ECX register is used to select the index of the performance counter
16596 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16598 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16600 // Reads the content of a 64-bit performance counter and returns it in the
16601 // registers EDX:EAX.
16602 if (Subtarget->is64Bit()) {
16603 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16604 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16607 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16608 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16611 Chain = HI.getValue(1);
16613 if (Subtarget->is64Bit()) {
16614 // The EAX register is loaded with the low-order 32 bits. The EDX register
16615 // is loaded with the supported high-order bits of the counter.
16616 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16617 DAG.getConstant(32, DL, MVT::i8));
16618 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16619 Results.push_back(Chain);
16623 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16624 SDValue Ops[] = { LO, HI };
16625 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16626 Results.push_back(Pair);
16627 Results.push_back(Chain);
16630 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16631 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16632 // also used to custom lower READCYCLECOUNTER nodes.
16633 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16634 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16635 SmallVectorImpl<SDValue> &Results) {
16636 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16637 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16640 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16641 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16642 // and the EAX register is loaded with the low-order 32 bits.
16643 if (Subtarget->is64Bit()) {
16644 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16645 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16648 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16649 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16652 SDValue Chain = HI.getValue(1);
16654 if (Opcode == X86ISD::RDTSCP_DAG) {
16655 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16657 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16658 // the ECX register. Add 'ecx' explicitly to the chain.
16659 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16661 // Explicitly store the content of ECX at the location passed in input
16662 // to the 'rdtscp' intrinsic.
16663 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16664 MachinePointerInfo(), false, false, 0);
16667 if (Subtarget->is64Bit()) {
16668 // The EDX register is loaded with the high-order 32 bits of the MSR, and
16669 // the EAX register is loaded with the low-order 32 bits.
16670 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16671 DAG.getConstant(32, DL, MVT::i8));
16672 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16673 Results.push_back(Chain);
16677 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16678 SDValue Ops[] = { LO, HI };
16679 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16680 Results.push_back(Pair);
16681 Results.push_back(Chain);
16684 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16685 SelectionDAG &DAG) {
16686 SmallVector<SDValue, 2> Results;
16688 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16690 return DAG.getMergeValues(Results, DL);
16693 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16694 SelectionDAG &DAG) {
16695 MachineFunction &MF = DAG.getMachineFunction();
16696 const Function *Fn = MF.getFunction();
16698 SDValue Chain = Op.getOperand(0);
16700 assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16701 "using llvm.x86.seh.restoreframe requires a frame pointer");
16703 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16704 MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16706 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16707 unsigned FrameReg =
16708 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16709 unsigned SPReg = RegInfo->getStackRegister();
16710 unsigned SlotSize = RegInfo->getSlotSize();
16712 // Get incoming EBP.
16713 SDValue IncomingEBP =
16714 DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16716 // SP is saved in the first field of every registration node, so load
16717 // [EBP-RegNodeSize] into SP.
16718 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16719 SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16720 DAG.getConstant(-RegNodeSize, dl, VT));
16722 DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16723 false, VT.getScalarSizeInBits() / 8);
16724 Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16726 if (!RegInfo->needsStackRealignment(MF)) {
16727 // Adjust EBP to point back to the original frame position.
16728 SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16729 Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16731 assert(RegInfo->hasBasePointer(MF) &&
16732 "functions with Win32 EH must use frame or base pointer register");
16734 // Reload the base pointer (ESI) with the adjusted incoming EBP.
16735 SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16736 Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16738 // Reload the spilled EBP value, now that the stack and base pointers are
16740 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16741 X86FI->setHasSEHFramePtrSave(true);
16742 int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16743 X86FI->setSEHFramePtrSaveIndex(FI);
16744 SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16745 MachinePointerInfo(), false, false, false,
16746 VT.getScalarSizeInBits() / 8);
16747 Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16753 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16754 /// return truncate Store/MaskedStore Node
16755 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16759 SDValue Mask = Op.getOperand(4);
16760 SDValue DataToTruncate = Op.getOperand(3);
16761 SDValue Addr = Op.getOperand(2);
16762 SDValue Chain = Op.getOperand(0);
16764 EVT VT = DataToTruncate.getValueType();
16765 EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16766 ElementType, VT.getVectorNumElements());
16768 if (isAllOnes(Mask)) // return just a truncate store
16769 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16770 MachinePointerInfo(), SVT, false, false,
16771 SVT.getScalarSizeInBits()/8);
16773 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16774 MVT::i1, VT.getVectorNumElements());
16775 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16776 Mask.getValueType().getSizeInBits());
16777 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16778 // are extracted by EXTRACT_SUBVECTOR.
16779 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16780 DAG.getBitcast(BitcastVT, Mask),
16781 DAG.getIntPtrConstant(0, dl));
16783 MachineMemOperand *MMO = DAG.getMachineFunction().
16784 getMachineMemOperand(MachinePointerInfo(),
16785 MachineMemOperand::MOStore, SVT.getStoreSize(),
16786 SVT.getScalarSizeInBits()/8);
16788 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16789 VMask, SVT, MMO, true);
16792 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16793 SelectionDAG &DAG) {
16794 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16796 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16798 if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16799 return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16804 switch(IntrData->Type) {
16806 llvm_unreachable("Unknown Intrinsic Type");
16810 // Emit the node with the right value type.
16811 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16812 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16814 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16815 // Otherwise return the value from Rand, which is always 0, casted to i32.
16816 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16817 DAG.getConstant(1, dl, Op->getValueType(1)),
16818 DAG.getConstant(X86::COND_B, dl, MVT::i32),
16819 SDValue(Result.getNode(), 1) };
16820 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16821 DAG.getVTList(Op->getValueType(1), MVT::Glue),
16824 // Return { result, isValid, chain }.
16825 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16826 SDValue(Result.getNode(), 2));
16829 //gather(v1, mask, index, base, scale);
16830 SDValue Chain = Op.getOperand(0);
16831 SDValue Src = Op.getOperand(2);
16832 SDValue Base = Op.getOperand(3);
16833 SDValue Index = Op.getOperand(4);
16834 SDValue Mask = Op.getOperand(5);
16835 SDValue Scale = Op.getOperand(6);
16836 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16840 //scatter(base, mask, index, v1, scale);
16841 SDValue Chain = Op.getOperand(0);
16842 SDValue Base = Op.getOperand(2);
16843 SDValue Mask = Op.getOperand(3);
16844 SDValue Index = Op.getOperand(4);
16845 SDValue Src = Op.getOperand(5);
16846 SDValue Scale = Op.getOperand(6);
16847 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16851 SDValue Hint = Op.getOperand(6);
16852 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16853 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16854 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16855 SDValue Chain = Op.getOperand(0);
16856 SDValue Mask = Op.getOperand(2);
16857 SDValue Index = Op.getOperand(3);
16858 SDValue Base = Op.getOperand(4);
16859 SDValue Scale = Op.getOperand(5);
16860 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16862 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16864 SmallVector<SDValue, 2> Results;
16865 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16867 return DAG.getMergeValues(Results, dl);
16869 // Read Performance Monitoring Counters.
16871 SmallVector<SDValue, 2> Results;
16872 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16873 return DAG.getMergeValues(Results, dl);
16875 // XTEST intrinsics.
16877 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16878 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16879 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16880 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16882 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16883 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16884 Ret, SDValue(InTrans.getNode(), 1));
16888 SmallVector<SDValue, 2> Results;
16889 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16890 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16891 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16892 DAG.getConstant(-1, dl, MVT::i8));
16893 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16894 Op.getOperand(4), GenCF.getValue(1));
16895 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16896 Op.getOperand(5), MachinePointerInfo(),
16898 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16899 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16901 Results.push_back(SetCC);
16902 Results.push_back(Store);
16903 return DAG.getMergeValues(Results, dl);
16905 case COMPRESS_TO_MEM: {
16907 SDValue Mask = Op.getOperand(4);
16908 SDValue DataToCompress = Op.getOperand(3);
16909 SDValue Addr = Op.getOperand(2);
16910 SDValue Chain = Op.getOperand(0);
16912 EVT VT = DataToCompress.getValueType();
16913 if (isAllOnes(Mask)) // return just a store
16914 return DAG.getStore(Chain, dl, DataToCompress, Addr,
16915 MachinePointerInfo(), false, false,
16916 VT.getScalarSizeInBits()/8);
16918 SDValue Compressed =
16919 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16920 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16921 return DAG.getStore(Chain, dl, Compressed, Addr,
16922 MachinePointerInfo(), false, false,
16923 VT.getScalarSizeInBits()/8);
16925 case TRUNCATE_TO_MEM_VI8:
16926 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16927 case TRUNCATE_TO_MEM_VI16:
16928 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16929 case TRUNCATE_TO_MEM_VI32:
16930 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16931 case EXPAND_FROM_MEM: {
16933 SDValue Mask = Op.getOperand(4);
16934 SDValue PassThru = Op.getOperand(3);
16935 SDValue Addr = Op.getOperand(2);
16936 SDValue Chain = Op.getOperand(0);
16937 EVT VT = Op.getValueType();
16939 if (isAllOnes(Mask)) // return just a load
16940 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16941 false, VT.getScalarSizeInBits()/8);
16943 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16944 false, false, false,
16945 VT.getScalarSizeInBits()/8);
16947 SDValue Results[] = {
16948 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16949 Mask, PassThru, Subtarget, DAG), Chain};
16950 return DAG.getMergeValues(Results, dl);
16955 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16956 SelectionDAG &DAG) const {
16957 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16958 MFI->setReturnAddressIsTaken(true);
16960 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16963 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16965 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16968 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16969 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16970 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16971 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16972 DAG.getNode(ISD::ADD, dl, PtrVT,
16973 FrameAddr, Offset),
16974 MachinePointerInfo(), false, false, false, 0);
16977 // Just load the return address.
16978 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16979 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16980 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16983 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16984 MachineFunction &MF = DAG.getMachineFunction();
16985 MachineFrameInfo *MFI = MF.getFrameInfo();
16986 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16987 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16988 EVT VT = Op.getValueType();
16990 MFI->setFrameAddressIsTaken(true);
16992 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16993 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
16994 // is not possible to crawl up the stack without looking at the unwind codes
16996 int FrameAddrIndex = FuncInfo->getFAIndex();
16997 if (!FrameAddrIndex) {
16998 // Set up a frame object for the return address.
16999 unsigned SlotSize = RegInfo->getSlotSize();
17000 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17001 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17002 FuncInfo->setFAIndex(FrameAddrIndex);
17004 return DAG.getFrameIndex(FrameAddrIndex, VT);
17007 unsigned FrameReg =
17008 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17009 SDLoc dl(Op); // FIXME probably not meaningful
17010 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17011 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17012 (FrameReg == X86::EBP && VT == MVT::i32)) &&
17013 "Invalid Frame Register!");
17014 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17016 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17017 MachinePointerInfo(),
17018 false, false, false, 0);
17022 // FIXME? Maybe this could be a TableGen attribute on some registers and
17023 // this table could be generated automatically from RegInfo.
17024 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17025 SelectionDAG &DAG) const {
17026 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17027 const MachineFunction &MF = DAG.getMachineFunction();
17029 unsigned Reg = StringSwitch<unsigned>(RegName)
17030 .Case("esp", X86::ESP)
17031 .Case("rsp", X86::RSP)
17032 .Case("ebp", X86::EBP)
17033 .Case("rbp", X86::RBP)
17036 if (Reg == X86::EBP || Reg == X86::RBP) {
17037 if (!TFI.hasFP(MF))
17038 report_fatal_error("register " + StringRef(RegName) +
17039 " is allocatable: function has no frame pointer");
17042 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17043 unsigned FrameReg =
17044 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17045 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17046 "Invalid Frame Register!");
17054 report_fatal_error("Invalid register name global variable");
17057 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17058 SelectionDAG &DAG) const {
17059 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17060 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17063 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17064 SDValue Chain = Op.getOperand(0);
17065 SDValue Offset = Op.getOperand(1);
17066 SDValue Handler = Op.getOperand(2);
17069 EVT PtrVT = getPointerTy(DAG.getDataLayout());
17070 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17071 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17072 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17073 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17074 "Invalid Frame Register!");
17075 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17076 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17078 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17079 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17081 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17082 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17084 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17086 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17087 DAG.getRegister(StoreAddrReg, PtrVT));
17090 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17091 SelectionDAG &DAG) const {
17093 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17094 DAG.getVTList(MVT::i32, MVT::Other),
17095 Op.getOperand(0), Op.getOperand(1));
17098 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17099 SelectionDAG &DAG) const {
17101 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17102 Op.getOperand(0), Op.getOperand(1));
17105 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17106 return Op.getOperand(0);
17109 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17110 SelectionDAG &DAG) const {
17111 SDValue Root = Op.getOperand(0);
17112 SDValue Trmp = Op.getOperand(1); // trampoline
17113 SDValue FPtr = Op.getOperand(2); // nested function
17114 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17117 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17118 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17120 if (Subtarget->is64Bit()) {
17121 SDValue OutChains[6];
17123 // Large code-model.
17124 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
17125 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17127 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17128 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17130 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17132 // Load the pointer to the nested function into R11.
17133 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17134 SDValue Addr = Trmp;
17135 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17136 Addr, MachinePointerInfo(TrmpAddr),
17139 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17140 DAG.getConstant(2, dl, MVT::i64));
17141 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17142 MachinePointerInfo(TrmpAddr, 2),
17145 // Load the 'nest' parameter value into R10.
17146 // R10 is specified in X86CallingConv.td
17147 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17148 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17149 DAG.getConstant(10, dl, MVT::i64));
17150 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17151 Addr, MachinePointerInfo(TrmpAddr, 10),
17154 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17155 DAG.getConstant(12, dl, MVT::i64));
17156 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17157 MachinePointerInfo(TrmpAddr, 12),
17160 // Jump to the nested function.
17161 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17162 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17163 DAG.getConstant(20, dl, MVT::i64));
17164 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17165 Addr, MachinePointerInfo(TrmpAddr, 20),
17168 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17169 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17170 DAG.getConstant(22, dl, MVT::i64));
17171 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17172 Addr, MachinePointerInfo(TrmpAddr, 22),
17175 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17177 const Function *Func =
17178 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17179 CallingConv::ID CC = Func->getCallingConv();
17184 llvm_unreachable("Unsupported calling convention");
17185 case CallingConv::C:
17186 case CallingConv::X86_StdCall: {
17187 // Pass 'nest' parameter in ECX.
17188 // Must be kept in sync with X86CallingConv.td
17189 NestReg = X86::ECX;
17191 // Check that ECX wasn't needed by an 'inreg' parameter.
17192 FunctionType *FTy = Func->getFunctionType();
17193 const AttributeSet &Attrs = Func->getAttributes();
17195 if (!Attrs.isEmpty() && !Func->isVarArg()) {
17196 unsigned InRegCount = 0;
17199 for (FunctionType::param_iterator I = FTy->param_begin(),
17200 E = FTy->param_end(); I != E; ++I, ++Idx)
17201 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17202 auto &DL = DAG.getDataLayout();
17203 // FIXME: should only count parameters that are lowered to integers.
17204 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17207 if (InRegCount > 2) {
17208 report_fatal_error("Nest register in use - reduce number of inreg"
17214 case CallingConv::X86_FastCall:
17215 case CallingConv::X86_ThisCall:
17216 case CallingConv::Fast:
17217 // Pass 'nest' parameter in EAX.
17218 // Must be kept in sync with X86CallingConv.td
17219 NestReg = X86::EAX;
17223 SDValue OutChains[4];
17224 SDValue Addr, Disp;
17226 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17227 DAG.getConstant(10, dl, MVT::i32));
17228 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17230 // This is storing the opcode for MOV32ri.
17231 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17232 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17233 OutChains[0] = DAG.getStore(Root, dl,
17234 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17235 Trmp, MachinePointerInfo(TrmpAddr),
17238 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17239 DAG.getConstant(1, dl, MVT::i32));
17240 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17241 MachinePointerInfo(TrmpAddr, 1),
17244 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17245 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17246 DAG.getConstant(5, dl, MVT::i32));
17247 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17248 Addr, MachinePointerInfo(TrmpAddr, 5),
17251 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17252 DAG.getConstant(6, dl, MVT::i32));
17253 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17254 MachinePointerInfo(TrmpAddr, 6),
17257 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17261 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17262 SelectionDAG &DAG) const {
17264 The rounding mode is in bits 11:10 of FPSR, and has the following
17266 00 Round to nearest
17271 FLT_ROUNDS, on the other hand, expects the following:
17278 To perform the conversion, we do:
17279 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17282 MachineFunction &MF = DAG.getMachineFunction();
17283 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17284 unsigned StackAlignment = TFI.getStackAlignment();
17285 MVT VT = Op.getSimpleValueType();
17288 // Save FP Control Word to stack slot
17289 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17290 SDValue StackSlot =
17291 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17293 MachineMemOperand *MMO =
17294 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17295 MachineMemOperand::MOStore, 2, 2);
17297 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17298 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17299 DAG.getVTList(MVT::Other),
17300 Ops, MVT::i16, MMO);
17302 // Load FP Control Word from stack slot
17303 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17304 MachinePointerInfo(), false, false, false, 0);
17306 // Transform as necessary
17308 DAG.getNode(ISD::SRL, DL, MVT::i16,
17309 DAG.getNode(ISD::AND, DL, MVT::i16,
17310 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17311 DAG.getConstant(11, DL, MVT::i8));
17313 DAG.getNode(ISD::SRL, DL, MVT::i16,
17314 DAG.getNode(ISD::AND, DL, MVT::i16,
17315 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17316 DAG.getConstant(9, DL, MVT::i8));
17319 DAG.getNode(ISD::AND, DL, MVT::i16,
17320 DAG.getNode(ISD::ADD, DL, MVT::i16,
17321 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17322 DAG.getConstant(1, DL, MVT::i16)),
17323 DAG.getConstant(3, DL, MVT::i16));
17325 return DAG.getNode((VT.getSizeInBits() < 16 ?
17326 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17329 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
17330 MVT VT = Op.getSimpleValueType();
17332 unsigned NumBits = VT.getSizeInBits();
17335 Op = Op.getOperand(0);
17336 if (VT == MVT::i8) {
17337 // Zero extend to i32 since there is not an i8 bsr.
17339 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17342 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17343 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17344 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17346 // If src is zero (i.e. bsr sets ZF), returns NumBits.
17349 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17350 DAG.getConstant(X86::COND_E, dl, MVT::i8),
17353 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17355 // Finally xor with NumBits-1.
17356 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17357 DAG.getConstant(NumBits - 1, dl, OpVT));
17360 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17364 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17365 MVT VT = Op.getSimpleValueType();
17367 unsigned NumBits = VT.getSizeInBits();
17370 Op = Op.getOperand(0);
17371 if (VT == MVT::i8) {
17372 // Zero extend to i32 since there is not an i8 bsr.
17374 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17377 // Issue a bsr (scan bits in reverse).
17378 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17379 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17381 // And xor with NumBits-1.
17382 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17383 DAG.getConstant(NumBits - 1, dl, OpVT));
17386 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17390 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17391 MVT VT = Op.getSimpleValueType();
17392 unsigned NumBits = VT.getScalarSizeInBits();
17395 if (VT.isVector()) {
17396 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17398 SDValue N0 = Op.getOperand(0);
17399 SDValue Zero = DAG.getConstant(0, dl, VT);
17401 // lsb(x) = (x & -x)
17402 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17403 DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17405 // cttz_undef(x) = (width - 1) - ctlz(lsb)
17406 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17407 TLI.isOperationLegal(ISD::CTLZ, VT)) {
17408 SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17409 return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17410 DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17413 // cttz(x) = ctpop(lsb - 1)
17414 SDValue One = DAG.getConstant(1, dl, VT);
17415 return DAG.getNode(ISD::CTPOP, dl, VT,
17416 DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17419 assert(Op.getOpcode() == ISD::CTTZ &&
17420 "Only scalar CTTZ requires custom lowering");
17422 // Issue a bsf (scan bits forward) which also sets EFLAGS.
17423 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17424 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17426 // If src is zero (i.e. bsf sets ZF), returns NumBits.
17429 DAG.getConstant(NumBits, dl, VT),
17430 DAG.getConstant(X86::COND_E, dl, MVT::i8),
17433 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17436 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17437 // ones, and then concatenate the result back.
17438 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17439 MVT VT = Op.getSimpleValueType();
17441 assert(VT.is256BitVector() && VT.isInteger() &&
17442 "Unsupported value type for operation");
17444 unsigned NumElems = VT.getVectorNumElements();
17447 // Extract the LHS vectors
17448 SDValue LHS = Op.getOperand(0);
17449 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17450 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17452 // Extract the RHS vectors
17453 SDValue RHS = Op.getOperand(1);
17454 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17455 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17457 MVT EltVT = VT.getVectorElementType();
17458 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17460 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17461 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17462 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17465 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17466 if (Op.getValueType() == MVT::i1)
17467 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17468 Op.getOperand(0), Op.getOperand(1));
17469 assert(Op.getSimpleValueType().is256BitVector() &&
17470 Op.getSimpleValueType().isInteger() &&
17471 "Only handle AVX 256-bit vector integer operation");
17472 return Lower256IntArith(Op, DAG);
17475 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17476 if (Op.getValueType() == MVT::i1)
17477 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17478 Op.getOperand(0), Op.getOperand(1));
17479 assert(Op.getSimpleValueType().is256BitVector() &&
17480 Op.getSimpleValueType().isInteger() &&
17481 "Only handle AVX 256-bit vector integer operation");
17482 return Lower256IntArith(Op, DAG);
17485 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17486 assert(Op.getSimpleValueType().is256BitVector() &&
17487 Op.getSimpleValueType().isInteger() &&
17488 "Only handle AVX 256-bit vector integer operation");
17489 return Lower256IntArith(Op, DAG);
17492 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17493 SelectionDAG &DAG) {
17495 MVT VT = Op.getSimpleValueType();
17498 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17500 // Decompose 256-bit ops into smaller 128-bit ops.
17501 if (VT.is256BitVector() && !Subtarget->hasInt256())
17502 return Lower256IntArith(Op, DAG);
17504 SDValue A = Op.getOperand(0);
17505 SDValue B = Op.getOperand(1);
17507 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17508 // pairs, multiply and truncate.
17509 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17510 if (Subtarget->hasInt256()) {
17511 if (VT == MVT::v32i8) {
17512 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17513 SDValue Lo = DAG.getIntPtrConstant(0, dl);
17514 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17515 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17516 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17517 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17518 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17519 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17520 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17521 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17524 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17525 return DAG.getNode(
17526 ISD::TRUNCATE, dl, VT,
17527 DAG.getNode(ISD::MUL, dl, ExVT,
17528 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17529 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17532 assert(VT == MVT::v16i8 &&
17533 "Pre-AVX2 support only supports v16i8 multiplication");
17534 MVT ExVT = MVT::v8i16;
17536 // Extract the lo parts and sign extend to i16
17538 if (Subtarget->hasSSE41()) {
17539 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17540 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17542 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17543 -1, 4, -1, 5, -1, 6, -1, 7};
17544 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17545 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17546 ALo = DAG.getBitcast(ExVT, ALo);
17547 BLo = DAG.getBitcast(ExVT, BLo);
17548 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17549 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17552 // Extract the hi parts and sign extend to i16
17554 if (Subtarget->hasSSE41()) {
17555 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
17556 -1, -1, -1, -1, -1, -1, -1, -1};
17557 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17558 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17559 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17560 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17562 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
17563 -1, 12, -1, 13, -1, 14, -1, 15};
17564 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17565 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17566 AHi = DAG.getBitcast(ExVT, AHi);
17567 BHi = DAG.getBitcast(ExVT, BHi);
17568 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17569 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17572 // Multiply, mask the lower 8bits of the lo/hi results and pack
17573 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17574 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17575 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17576 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17577 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17580 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17581 if (VT == MVT::v4i32) {
17582 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17583 "Should not custom lower when pmuldq is available!");
17585 // Extract the odd parts.
17586 static const int UnpackMask[] = { 1, -1, 3, -1 };
17587 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17588 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17590 // Multiply the even parts.
17591 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17592 // Now multiply odd parts.
17593 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17595 Evens = DAG.getBitcast(VT, Evens);
17596 Odds = DAG.getBitcast(VT, Odds);
17598 // Merge the two vectors back together with a shuffle. This expands into 2
17600 static const int ShufMask[] = { 0, 4, 2, 6 };
17601 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17604 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17605 "Only know how to lower V2I64/V4I64/V8I64 multiply");
17607 // Ahi = psrlqi(a, 32);
17608 // Bhi = psrlqi(b, 32);
17610 // AloBlo = pmuludq(a, b);
17611 // AloBhi = pmuludq(a, Bhi);
17612 // AhiBlo = pmuludq(Ahi, b);
17614 // AloBhi = psllqi(AloBhi, 32);
17615 // AhiBlo = psllqi(AhiBlo, 32);
17616 // return AloBlo + AloBhi + AhiBlo;
17618 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17619 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17621 SDValue AhiBlo = Ahi;
17622 SDValue AloBhi = Bhi;
17623 // Bit cast to 32-bit vectors for MULUDQ
17624 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17625 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17626 A = DAG.getBitcast(MulVT, A);
17627 B = DAG.getBitcast(MulVT, B);
17628 Ahi = DAG.getBitcast(MulVT, Ahi);
17629 Bhi = DAG.getBitcast(MulVT, Bhi);
17631 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17632 // After shifting right const values the result may be all-zero.
17633 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17634 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17635 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17637 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17638 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17639 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17642 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17643 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17646 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17647 assert(Subtarget->isTargetWin64() && "Unexpected target");
17648 EVT VT = Op.getValueType();
17649 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17650 "Unexpected return type for lowering");
17654 switch (Op->getOpcode()) {
17655 default: llvm_unreachable("Unexpected request for libcall!");
17656 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
17657 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
17658 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
17659 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
17660 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
17661 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17665 SDValue InChain = DAG.getEntryNode();
17667 TargetLowering::ArgListTy Args;
17668 TargetLowering::ArgListEntry Entry;
17669 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17670 EVT ArgVT = Op->getOperand(i).getValueType();
17671 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17672 "Unexpected argument type for lowering");
17673 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17674 Entry.Node = StackPtr;
17675 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17677 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17678 Entry.Ty = PointerType::get(ArgTy,0);
17679 Entry.isSExt = false;
17680 Entry.isZExt = false;
17681 Args.push_back(Entry);
17684 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17685 getPointerTy(DAG.getDataLayout()));
17687 TargetLowering::CallLoweringInfo CLI(DAG);
17688 CLI.setDebugLoc(dl).setChain(InChain)
17689 .setCallee(getLibcallCallingConv(LC),
17690 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17691 Callee, std::move(Args), 0)
17692 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17694 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17695 return DAG.getBitcast(VT, CallInfo.first);
17698 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17699 SelectionDAG &DAG) {
17700 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17701 EVT VT = Op0.getValueType();
17704 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17705 (VT == MVT::v8i32 && Subtarget->hasInt256()));
17707 // PMULxD operations multiply each even value (starting at 0) of LHS with
17708 // the related value of RHS and produce a widen result.
17709 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17710 // => <2 x i64> <ae|cg>
17712 // In other word, to have all the results, we need to perform two PMULxD:
17713 // 1. one with the even values.
17714 // 2. one with the odd values.
17715 // To achieve #2, with need to place the odd values at an even position.
17717 // Place the odd value at an even position (basically, shift all values 1
17718 // step to the left):
17719 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17720 // <a|b|c|d> => <b|undef|d|undef>
17721 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17722 // <e|f|g|h> => <f|undef|h|undef>
17723 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17725 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17727 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17728 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17730 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17731 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17732 // => <2 x i64> <ae|cg>
17733 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17734 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17735 // => <2 x i64> <bf|dh>
17736 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17738 // Shuffle it back into the right order.
17739 SDValue Highs, Lows;
17740 if (VT == MVT::v8i32) {
17741 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17742 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17743 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17744 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17746 const int HighMask[] = {1, 5, 3, 7};
17747 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17748 const int LowMask[] = {0, 4, 2, 6};
17749 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17752 // If we have a signed multiply but no PMULDQ fix up the high parts of a
17753 // unsigned multiply.
17754 if (IsSigned && !Subtarget->hasSSE41()) {
17755 SDValue ShAmt = DAG.getConstant(
17757 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17758 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17759 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17760 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17761 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17763 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17764 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17767 // The first result of MUL_LOHI is actually the low value, followed by the
17769 SDValue Ops[] = {Lows, Highs};
17770 return DAG.getMergeValues(Ops, dl);
17773 // Return true if the required (according to Opcode) shift-imm form is natively
17774 // supported by the Subtarget
17775 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17777 if (VT.getScalarSizeInBits() < 16)
17780 if (VT.is512BitVector() &&
17781 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17784 bool LShift = VT.is128BitVector() ||
17785 (VT.is256BitVector() && Subtarget->hasInt256());
17787 bool AShift = LShift && (Subtarget->hasVLX() ||
17788 (VT != MVT::v2i64 && VT != MVT::v4i64));
17789 return (Opcode == ISD::SRA) ? AShift : LShift;
17792 // The shift amount is a variable, but it is the same for all vector lanes.
17793 // These instructions are defined together with shift-immediate.
17795 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17797 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17800 // Return true if the required (according to Opcode) variable-shift form is
17801 // natively supported by the Subtarget
17802 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17805 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17808 // vXi16 supported only on AVX-512, BWI
17809 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17812 if (VT.is512BitVector() || Subtarget->hasVLX())
17815 bool LShift = VT.is128BitVector() || VT.is256BitVector();
17816 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
17817 return (Opcode == ISD::SRA) ? AShift : LShift;
17820 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17821 const X86Subtarget *Subtarget) {
17822 MVT VT = Op.getSimpleValueType();
17824 SDValue R = Op.getOperand(0);
17825 SDValue Amt = Op.getOperand(1);
17827 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17828 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17830 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17831 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17832 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17833 SDValue Ex = DAG.getBitcast(ExVT, R);
17835 if (ShiftAmt >= 32) {
17836 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17838 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17839 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17840 ShiftAmt - 32, DAG);
17841 if (VT == MVT::v2i64)
17842 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17843 if (VT == MVT::v4i64)
17844 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17845 {9, 1, 11, 3, 13, 5, 15, 7});
17847 // SRA upper i32, SHL whole i64 and select lower i32.
17848 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17851 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17852 Lower = DAG.getBitcast(ExVT, Lower);
17853 if (VT == MVT::v2i64)
17854 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17855 if (VT == MVT::v4i64)
17856 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17857 {8, 1, 10, 3, 12, 5, 14, 7});
17859 return DAG.getBitcast(VT, Ex);
17862 // Optimize shl/srl/sra with constant shift amount.
17863 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17864 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17865 uint64_t ShiftAmt = ShiftConst->getZExtValue();
17867 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17868 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17870 // i64 SRA needs to be performed as partial shifts.
17871 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17872 Op.getOpcode() == ISD::SRA)
17873 return ArithmeticShiftRight64(ShiftAmt);
17875 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17876 unsigned NumElts = VT.getVectorNumElements();
17877 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17879 if (Op.getOpcode() == ISD::SHL) {
17880 // Simple i8 add case
17882 return DAG.getNode(ISD::ADD, dl, VT, R, R);
17884 // Make a large shift.
17885 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17887 SHL = DAG.getBitcast(VT, SHL);
17888 // Zero out the rightmost bits.
17889 SmallVector<SDValue, 32> V(
17890 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17891 return DAG.getNode(ISD::AND, dl, VT, SHL,
17892 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17894 if (Op.getOpcode() == ISD::SRL) {
17895 // Make a large shift.
17896 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17898 SRL = DAG.getBitcast(VT, SRL);
17899 // Zero out the leftmost bits.
17900 SmallVector<SDValue, 32> V(
17901 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17902 return DAG.getNode(ISD::AND, dl, VT, SRL,
17903 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17905 if (Op.getOpcode() == ISD::SRA) {
17906 if (ShiftAmt == 7) {
17907 // ashr(R, 7) === cmp_slt(R, 0)
17908 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17909 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17912 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17913 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17914 SmallVector<SDValue, 32> V(NumElts,
17915 DAG.getConstant(128 >> ShiftAmt, dl,
17917 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17918 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17919 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17922 llvm_unreachable("Unknown shift opcode.");
17927 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17928 if (!Subtarget->is64Bit() &&
17929 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17931 // Peek through any splat that was introduced for i64 shift vectorization.
17932 int SplatIndex = -1;
17933 if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17934 if (SVN->isSplat()) {
17935 SplatIndex = SVN->getSplatIndex();
17936 Amt = Amt.getOperand(0);
17937 assert(SplatIndex < (int)VT.getVectorNumElements() &&
17938 "Splat shuffle referencing second operand");
17941 if (Amt.getOpcode() != ISD::BITCAST ||
17942 Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17945 Amt = Amt.getOperand(0);
17946 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17947 VT.getVectorNumElements();
17948 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17949 uint64_t ShiftAmt = 0;
17950 unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17951 for (unsigned i = 0; i != Ratio; ++i) {
17952 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17956 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17959 // Check remaining shift amounts (if not a splat).
17960 if (SplatIndex < 0) {
17961 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17962 uint64_t ShAmt = 0;
17963 for (unsigned j = 0; j != Ratio; ++j) {
17964 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17968 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17970 if (ShAmt != ShiftAmt)
17975 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17976 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17978 if (Op.getOpcode() == ISD::SRA)
17979 return ArithmeticShiftRight64(ShiftAmt);
17985 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17986 const X86Subtarget* Subtarget) {
17987 MVT VT = Op.getSimpleValueType();
17989 SDValue R = Op.getOperand(0);
17990 SDValue Amt = Op.getOperand(1);
17992 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17993 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17995 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17996 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17998 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18000 EVT EltVT = VT.getVectorElementType();
18002 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18003 // Check if this build_vector node is doing a splat.
18004 // If so, then set BaseShAmt equal to the splat value.
18005 BaseShAmt = BV->getSplatValue();
18006 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18007 BaseShAmt = SDValue();
18009 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18010 Amt = Amt.getOperand(0);
18012 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18013 if (SVN && SVN->isSplat()) {
18014 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18015 SDValue InVec = Amt.getOperand(0);
18016 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18017 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
18018 "Unexpected shuffle index found!");
18019 BaseShAmt = InVec.getOperand(SplatIdx);
18020 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18021 if (ConstantSDNode *C =
18022 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18023 if (C->getZExtValue() == SplatIdx)
18024 BaseShAmt = InVec.getOperand(1);
18029 // Avoid introducing an extract element from a shuffle.
18030 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18031 DAG.getIntPtrConstant(SplatIdx, dl));
18035 if (BaseShAmt.getNode()) {
18036 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18037 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18038 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18039 else if (EltVT.bitsLT(MVT::i32))
18040 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18042 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18046 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18047 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
18048 Amt.getOpcode() == ISD::BITCAST &&
18049 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18050 Amt = Amt.getOperand(0);
18051 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18052 VT.getVectorNumElements();
18053 std::vector<SDValue> Vals(Ratio);
18054 for (unsigned i = 0; i != Ratio; ++i)
18055 Vals[i] = Amt.getOperand(i);
18056 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18057 for (unsigned j = 0; j != Ratio; ++j)
18058 if (Vals[j] != Amt.getOperand(i + j))
18062 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18063 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18068 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18069 SelectionDAG &DAG) {
18070 MVT VT = Op.getSimpleValueType();
18072 SDValue R = Op.getOperand(0);
18073 SDValue Amt = Op.getOperand(1);
18075 assert(VT.isVector() && "Custom lowering only for vector shifts!");
18076 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18078 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18081 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18084 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18087 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18088 // shifts per-lane and then shuffle the partial results back together.
18089 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18090 // Splat the shift amounts so the scalar shifts above will catch it.
18091 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18092 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18093 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18094 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18095 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18098 // i64 vector arithmetic shift can be emulated with the transform:
18099 // M = lshr(SIGN_BIT, Amt)
18100 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18101 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18102 Op.getOpcode() == ISD::SRA) {
18103 SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18104 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18105 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18106 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18107 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18111 // If possible, lower this packed shift into a vector multiply instead of
18112 // expanding it into a sequence of scalar shifts.
18113 // Do this only if the vector shift count is a constant build_vector.
18114 if (Op.getOpcode() == ISD::SHL &&
18115 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18116 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18117 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18118 SmallVector<SDValue, 8> Elts;
18119 EVT SVT = VT.getScalarType();
18120 unsigned SVTBits = SVT.getSizeInBits();
18121 const APInt &One = APInt(SVTBits, 1);
18122 unsigned NumElems = VT.getVectorNumElements();
18124 for (unsigned i=0; i !=NumElems; ++i) {
18125 SDValue Op = Amt->getOperand(i);
18126 if (Op->getOpcode() == ISD::UNDEF) {
18127 Elts.push_back(Op);
18131 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18132 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
18133 uint64_t ShAmt = C.getZExtValue();
18134 if (ShAmt >= SVTBits) {
18135 Elts.push_back(DAG.getUNDEF(SVT));
18138 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18140 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18141 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18144 // Lower SHL with variable shift amount.
18145 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18146 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18148 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18149 DAG.getConstant(0x3f800000U, dl, VT));
18150 Op = DAG.getBitcast(MVT::v4f32, Op);
18151 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18152 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18155 // If possible, lower this shift as a sequence of two shifts by
18156 // constant plus a MOVSS/MOVSD instead of scalarizing it.
18158 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18160 // Could be rewritten as:
18161 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18163 // The advantage is that the two shifts from the example would be
18164 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18165 // the vector shift into four scalar shifts plus four pairs of vector
18167 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18168 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18169 unsigned TargetOpcode = X86ISD::MOVSS;
18170 bool CanBeSimplified;
18171 // The splat value for the first packed shift (the 'X' from the example).
18172 SDValue Amt1 = Amt->getOperand(0);
18173 // The splat value for the second packed shift (the 'Y' from the example).
18174 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18175 Amt->getOperand(2);
18177 // See if it is possible to replace this node with a sequence of
18178 // two shifts followed by a MOVSS/MOVSD
18179 if (VT == MVT::v4i32) {
18180 // Check if it is legal to use a MOVSS.
18181 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18182 Amt2 == Amt->getOperand(3);
18183 if (!CanBeSimplified) {
18184 // Otherwise, check if we can still simplify this node using a MOVSD.
18185 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18186 Amt->getOperand(2) == Amt->getOperand(3);
18187 TargetOpcode = X86ISD::MOVSD;
18188 Amt2 = Amt->getOperand(2);
18191 // Do similar checks for the case where the machine value type
18193 CanBeSimplified = Amt1 == Amt->getOperand(1);
18194 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18195 CanBeSimplified = Amt2 == Amt->getOperand(i);
18197 if (!CanBeSimplified) {
18198 TargetOpcode = X86ISD::MOVSD;
18199 CanBeSimplified = true;
18200 Amt2 = Amt->getOperand(4);
18201 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18202 CanBeSimplified = Amt1 == Amt->getOperand(i);
18203 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18204 CanBeSimplified = Amt2 == Amt->getOperand(j);
18208 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18209 isa<ConstantSDNode>(Amt2)) {
18210 // Replace this node with two shifts followed by a MOVSS/MOVSD.
18211 EVT CastVT = MVT::v4i32;
18213 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18214 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18216 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18217 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18218 if (TargetOpcode == X86ISD::MOVSD)
18219 CastVT = MVT::v2i64;
18220 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18221 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18222 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18224 return DAG.getBitcast(VT, Result);
18228 // v4i32 Non Uniform Shifts.
18229 // If the shift amount is constant we can shift each lane using the SSE2
18230 // immediate shifts, else we need to zero-extend each lane to the lower i64
18231 // and shift using the SSE2 variable shifts.
18232 // The separate results can then be blended together.
18233 if (VT == MVT::v4i32) {
18234 unsigned Opc = Op.getOpcode();
18235 SDValue Amt0, Amt1, Amt2, Amt3;
18236 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18237 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18238 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18239 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18240 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18242 // ISD::SHL is handled above but we include it here for completeness.
18245 llvm_unreachable("Unknown target vector shift node");
18247 Opc = X86ISD::VSHL;
18250 Opc = X86ISD::VSRL;
18253 Opc = X86ISD::VSRA;
18256 // The SSE2 shifts use the lower i64 as the same shift amount for
18257 // all lanes and the upper i64 is ignored. These shuffle masks
18258 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18259 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18260 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18261 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18262 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18263 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18266 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18267 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18268 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18269 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18270 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18271 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18272 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18275 if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
18276 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18277 unsigned ShiftOpcode = Op->getOpcode();
18279 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18280 // On SSE41 targets we make use of the fact that VSELECT lowers
18281 // to PBLENDVB which selects bytes based just on the sign bit.
18282 if (Subtarget->hasSSE41()) {
18283 V0 = DAG.getBitcast(VT, V0);
18284 V1 = DAG.getBitcast(VT, V1);
18285 Sel = DAG.getBitcast(VT, Sel);
18286 return DAG.getBitcast(SelVT,
18287 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18289 // On pre-SSE41 targets we test for the sign bit by comparing to
18290 // zero - a negative value will set all bits of the lanes to true
18291 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18292 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18293 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18294 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18297 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18298 // We can safely do this using i16 shifts as we're only interested in
18299 // the 3 lower bits of each byte.
18300 Amt = DAG.getBitcast(ExtVT, Amt);
18301 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18302 Amt = DAG.getBitcast(VT, Amt);
18304 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18305 // r = VSELECT(r, shift(r, 4), a);
18307 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18308 R = SignBitSelect(VT, Amt, M, R);
18311 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18313 // r = VSELECT(r, shift(r, 2), a);
18314 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18315 R = SignBitSelect(VT, Amt, M, R);
18318 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18320 // return VSELECT(r, shift(r, 1), a);
18321 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18322 R = SignBitSelect(VT, Amt, M, R);
18326 if (Op->getOpcode() == ISD::SRA) {
18327 // For SRA we need to unpack each byte to the higher byte of a i16 vector
18328 // so we can correctly sign extend. We don't care what happens to the
18330 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18331 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18332 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18333 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18334 ALo = DAG.getBitcast(ExtVT, ALo);
18335 AHi = DAG.getBitcast(ExtVT, AHi);
18336 RLo = DAG.getBitcast(ExtVT, RLo);
18337 RHi = DAG.getBitcast(ExtVT, RHi);
18339 // r = VSELECT(r, shift(r, 4), a);
18340 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18341 DAG.getConstant(4, dl, ExtVT));
18342 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18343 DAG.getConstant(4, dl, ExtVT));
18344 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18345 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18348 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18349 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18351 // r = VSELECT(r, shift(r, 2), a);
18352 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18353 DAG.getConstant(2, dl, ExtVT));
18354 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18355 DAG.getConstant(2, dl, ExtVT));
18356 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18357 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18360 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18361 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18363 // r = VSELECT(r, shift(r, 1), a);
18364 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18365 DAG.getConstant(1, dl, ExtVT));
18366 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18367 DAG.getConstant(1, dl, ExtVT));
18368 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18369 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18371 // Logical shift the result back to the lower byte, leaving a zero upper
18373 // meaning that we can safely pack with PACKUSWB.
18375 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18377 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18378 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18382 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18383 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18384 // solution better.
18385 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18386 MVT ExtVT = MVT::v8i32;
18388 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18389 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18390 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18391 return DAG.getNode(ISD::TRUNCATE, dl, VT,
18392 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18395 if (Subtarget->hasInt256() && VT == MVT::v16i16) {
18396 MVT ExtVT = MVT::v8i32;
18397 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18398 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18399 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18400 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18401 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18402 ALo = DAG.getBitcast(ExtVT, ALo);
18403 AHi = DAG.getBitcast(ExtVT, AHi);
18404 RLo = DAG.getBitcast(ExtVT, RLo);
18405 RHi = DAG.getBitcast(ExtVT, RHi);
18406 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18407 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18408 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18409 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18410 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18413 if (VT == MVT::v8i16) {
18414 unsigned ShiftOpcode = Op->getOpcode();
18416 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18417 // On SSE41 targets we make use of the fact that VSELECT lowers
18418 // to PBLENDVB which selects bytes based just on the sign bit.
18419 if (Subtarget->hasSSE41()) {
18420 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18421 V0 = DAG.getBitcast(ExtVT, V0);
18422 V1 = DAG.getBitcast(ExtVT, V1);
18423 Sel = DAG.getBitcast(ExtVT, Sel);
18424 return DAG.getBitcast(
18425 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18427 // On pre-SSE41 targets we splat the sign bit - a negative value will
18428 // set all bits of the lanes to true and VSELECT uses that in
18429 // its OR(AND(V0,C),AND(V1,~C)) lowering.
18431 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18432 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18435 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18436 if (Subtarget->hasSSE41()) {
18437 // On SSE41 targets we need to replicate the shift mask in both
18438 // bytes for PBLENDVB.
18441 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18442 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18444 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18447 // r = VSELECT(r, shift(r, 8), a);
18448 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18449 R = SignBitSelect(Amt, M, R);
18452 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18454 // r = VSELECT(r, shift(r, 4), a);
18455 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18456 R = SignBitSelect(Amt, M, R);
18459 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18461 // r = VSELECT(r, shift(r, 2), a);
18462 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18463 R = SignBitSelect(Amt, M, R);
18466 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18468 // return VSELECT(r, shift(r, 1), a);
18469 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18470 R = SignBitSelect(Amt, M, R);
18474 // Decompose 256-bit shifts into smaller 128-bit shifts.
18475 if (VT.is256BitVector()) {
18476 unsigned NumElems = VT.getVectorNumElements();
18477 MVT EltVT = VT.getVectorElementType();
18478 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18480 // Extract the two vectors
18481 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18482 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18484 // Recreate the shift amount vectors
18485 SDValue Amt1, Amt2;
18486 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18487 // Constant shift amount
18488 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18489 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18490 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18492 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18493 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18495 // Variable shift amount
18496 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18497 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18500 // Issue new vector shifts for the smaller types
18501 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18502 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18504 // Concatenate the result back
18505 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18511 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18512 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18513 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18514 // looks for this combo and may remove the "setcc" instruction if the "setcc"
18515 // has only one use.
18516 SDNode *N = Op.getNode();
18517 SDValue LHS = N->getOperand(0);
18518 SDValue RHS = N->getOperand(1);
18519 unsigned BaseOp = 0;
18522 switch (Op.getOpcode()) {
18523 default: llvm_unreachable("Unknown ovf instruction!");
18525 // A subtract of one will be selected as a INC. Note that INC doesn't
18526 // set CF, so we can't do this for UADDO.
18527 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18529 BaseOp = X86ISD::INC;
18530 Cond = X86::COND_O;
18533 BaseOp = X86ISD::ADD;
18534 Cond = X86::COND_O;
18537 BaseOp = X86ISD::ADD;
18538 Cond = X86::COND_B;
18541 // A subtract of one will be selected as a DEC. Note that DEC doesn't
18542 // set CF, so we can't do this for USUBO.
18543 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18545 BaseOp = X86ISD::DEC;
18546 Cond = X86::COND_O;
18549 BaseOp = X86ISD::SUB;
18550 Cond = X86::COND_O;
18553 BaseOp = X86ISD::SUB;
18554 Cond = X86::COND_B;
18557 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18558 Cond = X86::COND_O;
18560 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18561 if (N->getValueType(0) == MVT::i8) {
18562 BaseOp = X86ISD::UMUL8;
18563 Cond = X86::COND_O;
18566 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18568 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18571 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18572 DAG.getConstant(X86::COND_O, DL, MVT::i32),
18573 SDValue(Sum.getNode(), 2));
18575 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18579 // Also sets EFLAGS.
18580 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18581 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18584 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18585 DAG.getConstant(Cond, DL, MVT::i32),
18586 SDValue(Sum.getNode(), 1));
18588 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18591 /// Returns true if the operand type is exactly twice the native width, and
18592 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18593 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18594 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18595 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18596 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18599 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18600 else if (OpWidth == 128)
18601 return Subtarget->hasCmpxchg16b();
18606 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18607 return needsCmpXchgNb(SI->getValueOperand()->getType());
18610 // Note: this turns large loads into lock cmpxchg8b/16b.
18611 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18612 TargetLowering::AtomicExpansionKind
18613 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18614 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18615 return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
18616 : AtomicExpansionKind::None;
18619 TargetLowering::AtomicExpansionKind
18620 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18621 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18622 Type *MemType = AI->getType();
18624 // If the operand is too big, we must see if cmpxchg8/16b is available
18625 // and default to library calls otherwise.
18626 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18627 return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
18628 : AtomicExpansionKind::None;
18631 AtomicRMWInst::BinOp Op = AI->getOperation();
18634 llvm_unreachable("Unknown atomic operation");
18635 case AtomicRMWInst::Xchg:
18636 case AtomicRMWInst::Add:
18637 case AtomicRMWInst::Sub:
18638 // It's better to use xadd, xsub or xchg for these in all cases.
18639 return AtomicExpansionKind::None;
18640 case AtomicRMWInst::Or:
18641 case AtomicRMWInst::And:
18642 case AtomicRMWInst::Xor:
18643 // If the atomicrmw's result isn't actually used, we can just add a "lock"
18644 // prefix to a normal instruction for these operations.
18645 return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
18646 : AtomicExpansionKind::None;
18647 case AtomicRMWInst::Nand:
18648 case AtomicRMWInst::Max:
18649 case AtomicRMWInst::Min:
18650 case AtomicRMWInst::UMax:
18651 case AtomicRMWInst::UMin:
18652 // These always require a non-trivial set of data operations on x86. We must
18653 // use a cmpxchg loop.
18654 return AtomicExpansionKind::CmpXChg;
18658 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18659 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18660 // no-sse2). There isn't any reason to disable it if the target processor
18662 return Subtarget.hasSSE2() || Subtarget.is64Bit();
18666 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18667 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18668 Type *MemType = AI->getType();
18669 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18670 // there is no benefit in turning such RMWs into loads, and it is actually
18671 // harmful as it introduces a mfence.
18672 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18675 auto Builder = IRBuilder<>(AI);
18676 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18677 auto SynchScope = AI->getSynchScope();
18678 // We must restrict the ordering to avoid generating loads with Release or
18679 // ReleaseAcquire orderings.
18680 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18681 auto Ptr = AI->getPointerOperand();
18683 // Before the load we need a fence. Here is an example lifted from
18684 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18687 // x.store(1, relaxed);
18688 // r1 = y.fetch_add(0, release);
18690 // y.fetch_add(42, acquire);
18691 // r2 = x.load(relaxed);
18692 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18693 // lowered to just a load without a fence. A mfence flushes the store buffer,
18694 // making the optimization clearly correct.
18695 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18696 // otherwise, we might be able to be more aggressive on relaxed idempotent
18697 // rmw. In practice, they do not look useful, so we don't try to be
18698 // especially clever.
18699 if (SynchScope == SingleThread)
18700 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18701 // the IR level, so we must wrap it in an intrinsic.
18704 if (!hasMFENCE(*Subtarget))
18705 // FIXME: it might make sense to use a locked operation here but on a
18706 // different cache-line to prevent cache-line bouncing. In practice it
18707 // is probably a small win, and x86 processors without mfence are rare
18708 // enough that we do not bother.
18712 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18713 Builder.CreateCall(MFence, {});
18715 // Finally we can emit the atomic load.
18716 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18717 AI->getType()->getPrimitiveSizeInBits());
18718 Loaded->setAtomic(Order, SynchScope);
18719 AI->replaceAllUsesWith(Loaded);
18720 AI->eraseFromParent();
18724 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18725 SelectionDAG &DAG) {
18727 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18728 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18729 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18730 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18732 // The only fence that needs an instruction is a sequentially-consistent
18733 // cross-thread fence.
18734 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18735 if (hasMFENCE(*Subtarget))
18736 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18738 SDValue Chain = Op.getOperand(0);
18739 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18741 DAG.getRegister(X86::ESP, MVT::i32), // Base
18742 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
18743 DAG.getRegister(0, MVT::i32), // Index
18744 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
18745 DAG.getRegister(0, MVT::i32), // Segment.
18749 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18750 return SDValue(Res, 0);
18753 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18754 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18757 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18758 SelectionDAG &DAG) {
18759 MVT T = Op.getSimpleValueType();
18763 switch(T.SimpleTy) {
18764 default: llvm_unreachable("Invalid value type!");
18765 case MVT::i8: Reg = X86::AL; size = 1; break;
18766 case MVT::i16: Reg = X86::AX; size = 2; break;
18767 case MVT::i32: Reg = X86::EAX; size = 4; break;
18769 assert(Subtarget->is64Bit() && "Node not type legal!");
18770 Reg = X86::RAX; size = 8;
18773 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18774 Op.getOperand(2), SDValue());
18775 SDValue Ops[] = { cpIn.getValue(0),
18778 DAG.getTargetConstant(size, DL, MVT::i8),
18779 cpIn.getValue(1) };
18780 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18781 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18782 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18786 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18787 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18788 MVT::i32, cpOut.getValue(2));
18789 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18790 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18793 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18794 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18795 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18799 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18800 SelectionDAG &DAG) {
18801 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18802 MVT DstVT = Op.getSimpleValueType();
18804 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18805 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18806 if (DstVT != MVT::f64)
18807 // This conversion needs to be expanded.
18810 SDValue InVec = Op->getOperand(0);
18812 unsigned NumElts = SrcVT.getVectorNumElements();
18813 EVT SVT = SrcVT.getVectorElementType();
18815 // Widen the vector in input in the case of MVT::v2i32.
18816 // Example: from MVT::v2i32 to MVT::v4i32.
18817 SmallVector<SDValue, 16> Elts;
18818 for (unsigned i = 0, e = NumElts; i != e; ++i)
18819 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18820 DAG.getIntPtrConstant(i, dl)));
18822 // Explicitly mark the extra elements as Undef.
18823 Elts.append(NumElts, DAG.getUNDEF(SVT));
18825 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18826 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18827 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18828 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18829 DAG.getIntPtrConstant(0, dl));
18832 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18833 Subtarget->hasMMX() && "Unexpected custom BITCAST");
18834 assert((DstVT == MVT::i64 ||
18835 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18836 "Unexpected custom BITCAST");
18837 // i64 <=> MMX conversions are Legal.
18838 if (SrcVT==MVT::i64 && DstVT.isVector())
18840 if (DstVT==MVT::i64 && SrcVT.isVector())
18842 // MMX <=> MMX conversions are Legal.
18843 if (SrcVT.isVector() && DstVT.isVector())
18845 // All other conversions need to be expanded.
18849 /// Compute the horizontal sum of bytes in V for the elements of VT.
18851 /// Requires V to be a byte vector and VT to be an integer vector type with
18852 /// wider elements than V's type. The width of the elements of VT determines
18853 /// how many bytes of V are summed horizontally to produce each element of the
18855 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18856 const X86Subtarget *Subtarget,
18857 SelectionDAG &DAG) {
18859 MVT ByteVecVT = V.getSimpleValueType();
18860 MVT EltVT = VT.getVectorElementType();
18861 int NumElts = VT.getVectorNumElements();
18862 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18863 "Expected value to have byte element type.");
18864 assert(EltVT != MVT::i8 &&
18865 "Horizontal byte sum only makes sense for wider elements!");
18866 unsigned VecSize = VT.getSizeInBits();
18867 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18869 // PSADBW instruction horizontally add all bytes and leave the result in i64
18870 // chunks, thus directly computes the pop count for v2i64 and v4i64.
18871 if (EltVT == MVT::i64) {
18872 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18873 V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18874 return DAG.getBitcast(VT, V);
18877 if (EltVT == MVT::i32) {
18878 // We unpack the low half and high half into i32s interleaved with zeros so
18879 // that we can use PSADBW to horizontally sum them. The most useful part of
18880 // this is that it lines up the results of two PSADBW instructions to be
18881 // two v2i64 vectors which concatenated are the 4 population counts. We can
18882 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18883 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18884 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18885 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18887 // Do the horizontal sums into two v2i64s.
18888 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18889 Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18890 DAG.getBitcast(ByteVecVT, Low), Zeros);
18891 High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18892 DAG.getBitcast(ByteVecVT, High), Zeros);
18894 // Merge them together.
18895 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18896 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18897 DAG.getBitcast(ShortVecVT, Low),
18898 DAG.getBitcast(ShortVecVT, High));
18900 return DAG.getBitcast(VT, V);
18903 // The only element type left is i16.
18904 assert(EltVT == MVT::i16 && "Unknown how to handle type");
18906 // To obtain pop count for each i16 element starting from the pop count for
18907 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18908 // right by 8. It is important to shift as i16s as i8 vector shift isn't
18909 // directly supported.
18910 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18911 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18912 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18913 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18914 DAG.getBitcast(ByteVecVT, V));
18915 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18918 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18919 const X86Subtarget *Subtarget,
18920 SelectionDAG &DAG) {
18921 MVT VT = Op.getSimpleValueType();
18922 MVT EltVT = VT.getVectorElementType();
18923 unsigned VecSize = VT.getSizeInBits();
18925 // Implement a lookup table in register by using an algorithm based on:
18926 // http://wm.ite.pl/articles/sse-popcount.html
18928 // The general idea is that every lower byte nibble in the input vector is an
18929 // index into a in-register pre-computed pop count table. We then split up the
18930 // input vector in two new ones: (1) a vector with only the shifted-right
18931 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18932 // masked out higher ones) for each byte. PSHUB is used separately with both
18933 // to index the in-register table. Next, both are added and the result is a
18934 // i8 vector where each element contains the pop count for input byte.
18936 // To obtain the pop count for elements != i8, we follow up with the same
18937 // approach and use additional tricks as described below.
18939 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18940 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18941 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18942 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18944 int NumByteElts = VecSize / 8;
18945 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18946 SDValue In = DAG.getBitcast(ByteVecVT, Op);
18947 SmallVector<SDValue, 16> LUTVec;
18948 for (int i = 0; i < NumByteElts; ++i)
18949 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18950 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18951 SmallVector<SDValue, 16> Mask0F(NumByteElts,
18952 DAG.getConstant(0x0F, DL, MVT::i8));
18953 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18956 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18957 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18958 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18961 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18963 // The input vector is used as the shuffle mask that index elements into the
18964 // LUT. After counting low and high nibbles, add the vector to obtain the
18965 // final pop count per i8 element.
18966 SDValue HighPopCnt =
18967 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18968 SDValue LowPopCnt =
18969 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18970 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18972 if (EltVT == MVT::i8)
18975 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18978 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18979 const X86Subtarget *Subtarget,
18980 SelectionDAG &DAG) {
18981 MVT VT = Op.getSimpleValueType();
18982 assert(VT.is128BitVector() &&
18983 "Only 128-bit vector bitmath lowering supported.");
18985 int VecSize = VT.getSizeInBits();
18986 MVT EltVT = VT.getVectorElementType();
18987 int Len = EltVT.getSizeInBits();
18989 // This is the vectorized version of the "best" algorithm from
18990 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18991 // with a minor tweak to use a series of adds + shifts instead of vector
18992 // multiplications. Implemented for all integer vector types. We only use
18993 // this when we don't have SSSE3 which allows a LUT-based lowering that is
18994 // much faster, even faster than using native popcnt instructions.
18996 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18997 MVT VT = V.getSimpleValueType();
18998 SmallVector<SDValue, 32> Shifters(
18999 VT.getVectorNumElements(),
19000 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19001 return DAG.getNode(OpCode, DL, VT, V,
19002 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19004 auto GetMask = [&](SDValue V, APInt Mask) {
19005 MVT VT = V.getSimpleValueType();
19006 SmallVector<SDValue, 32> Masks(
19007 VT.getVectorNumElements(),
19008 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19009 return DAG.getNode(ISD::AND, DL, VT, V,
19010 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19013 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19014 // x86, so set the SRL type to have elements at least i16 wide. This is
19015 // correct because all of our SRLs are followed immediately by a mask anyways
19016 // that handles any bits that sneak into the high bits of the byte elements.
19017 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19021 // v = v - ((v >> 1) & 0x55555555...)
19023 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19024 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19025 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19027 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19028 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19029 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19030 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19031 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19033 // v = (v + (v >> 4)) & 0x0F0F0F0F...
19034 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19035 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19036 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19038 // At this point, V contains the byte-wise population count, and we are
19039 // merely doing a horizontal sum if necessary to get the wider element
19041 if (EltVT == MVT::i8)
19044 return LowerHorizontalByteSum(
19045 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19049 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19050 SelectionDAG &DAG) {
19051 MVT VT = Op.getSimpleValueType();
19052 // FIXME: Need to add AVX-512 support here!
19053 assert((VT.is256BitVector() || VT.is128BitVector()) &&
19054 "Unknown CTPOP type to handle");
19055 SDLoc DL(Op.getNode());
19056 SDValue Op0 = Op.getOperand(0);
19058 if (!Subtarget->hasSSSE3()) {
19059 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19060 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19061 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19064 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19065 unsigned NumElems = VT.getVectorNumElements();
19067 // Extract each 128-bit vector, compute pop count and concat the result.
19068 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19069 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19071 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19072 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19073 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19076 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19079 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19080 SelectionDAG &DAG) {
19081 assert(Op.getValueType().isVector() &&
19082 "We only do custom lowering for vector population count.");
19083 return LowerVectorCTPOP(Op, Subtarget, DAG);
19086 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19087 SDNode *Node = Op.getNode();
19089 EVT T = Node->getValueType(0);
19090 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19091 DAG.getConstant(0, dl, T), Node->getOperand(2));
19092 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19093 cast<AtomicSDNode>(Node)->getMemoryVT(),
19094 Node->getOperand(0),
19095 Node->getOperand(1), negOp,
19096 cast<AtomicSDNode>(Node)->getMemOperand(),
19097 cast<AtomicSDNode>(Node)->getOrdering(),
19098 cast<AtomicSDNode>(Node)->getSynchScope());
19101 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19102 SDNode *Node = Op.getNode();
19104 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19106 // Convert seq_cst store -> xchg
19107 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19108 // FIXME: On 32-bit, store -> fist or movq would be more efficient
19109 // (The only way to get a 16-byte store is cmpxchg16b)
19110 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19111 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19112 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19113 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19114 cast<AtomicSDNode>(Node)->getMemoryVT(),
19115 Node->getOperand(0),
19116 Node->getOperand(1), Node->getOperand(2),
19117 cast<AtomicSDNode>(Node)->getMemOperand(),
19118 cast<AtomicSDNode>(Node)->getOrdering(),
19119 cast<AtomicSDNode>(Node)->getSynchScope());
19120 return Swap.getValue(1);
19122 // Other atomic stores have a simple pattern.
19126 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19127 EVT VT = Op.getNode()->getSimpleValueType(0);
19129 // Let legalize expand this if it isn't a legal type yet.
19130 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19133 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19136 bool ExtraOp = false;
19137 switch (Op.getOpcode()) {
19138 default: llvm_unreachable("Invalid code");
19139 case ISD::ADDC: Opc = X86ISD::ADD; break;
19140 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19141 case ISD::SUBC: Opc = X86ISD::SUB; break;
19142 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19146 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19148 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19149 Op.getOperand(1), Op.getOperand(2));
19152 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19153 SelectionDAG &DAG) {
19154 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19156 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19157 // which returns the values as { float, float } (in XMM0) or
19158 // { double, double } (which is returned in XMM0, XMM1).
19160 SDValue Arg = Op.getOperand(0);
19161 EVT ArgVT = Arg.getValueType();
19162 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19164 TargetLowering::ArgListTy Args;
19165 TargetLowering::ArgListEntry Entry;
19169 Entry.isSExt = false;
19170 Entry.isZExt = false;
19171 Args.push_back(Entry);
19173 bool isF64 = ArgVT == MVT::f64;
19174 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19175 // the small struct {f32, f32} is returned in (eax, edx). For f64,
19176 // the results are returned via SRet in memory.
19177 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
19178 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19180 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19182 Type *RetTy = isF64
19183 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19184 : (Type*)VectorType::get(ArgTy, 4);
19186 TargetLowering::CallLoweringInfo CLI(DAG);
19187 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19188 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19190 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19193 // Returned in xmm0 and xmm1.
19194 return CallResult.first;
19196 // Returned in bits 0:31 and 32:64 xmm0.
19197 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19198 CallResult.first, DAG.getIntPtrConstant(0, dl));
19199 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19200 CallResult.first, DAG.getIntPtrConstant(1, dl));
19201 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19202 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19205 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19206 SelectionDAG &DAG) {
19207 assert(Subtarget->hasAVX512() &&
19208 "MGATHER/MSCATTER are supported on AVX-512 arch only");
19210 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19211 EVT VT = N->getValue().getValueType();
19212 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19215 // X86 scatter kills mask register, so its type should be added to
19216 // the list of return values
19217 if (N->getNumValues() == 1) {
19218 SDValue Index = N->getIndex();
19219 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19220 !Index.getValueType().is512BitVector())
19221 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19223 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19224 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
19225 N->getOperand(3), Index };
19227 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19228 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19229 return SDValue(NewScatter.getNode(), 0);
19234 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19235 SelectionDAG &DAG) {
19236 assert(Subtarget->hasAVX512() &&
19237 "MGATHER/MSCATTER are supported on AVX-512 arch only");
19239 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19240 EVT VT = Op.getValueType();
19241 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19244 SDValue Index = N->getIndex();
19245 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19246 !Index.getValueType().is512BitVector()) {
19247 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19248 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
19249 N->getOperand(3), Index };
19250 DAG.UpdateNodeOperands(N, Ops);
19255 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19256 SelectionDAG &DAG) const {
19257 // TODO: Eventually, the lowering of these nodes should be informed by or
19258 // deferred to the GC strategy for the function in which they appear. For
19259 // now, however, they must be lowered to something. Since they are logically
19260 // no-ops in the case of a null GC strategy (or a GC strategy which does not
19261 // require special handling for these nodes), lower them as literal NOOPs for
19263 SmallVector<SDValue, 2> Ops;
19265 Ops.push_back(Op.getOperand(0));
19266 if (Op->getGluedNode())
19267 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19270 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19271 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19276 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19277 SelectionDAG &DAG) const {
19278 // TODO: Eventually, the lowering of these nodes should be informed by or
19279 // deferred to the GC strategy for the function in which they appear. For
19280 // now, however, they must be lowered to something. Since they are logically
19281 // no-ops in the case of a null GC strategy (or a GC strategy which does not
19282 // require special handling for these nodes), lower them as literal NOOPs for
19284 SmallVector<SDValue, 2> Ops;
19286 Ops.push_back(Op.getOperand(0));
19287 if (Op->getGluedNode())
19288 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19291 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19292 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19297 /// LowerOperation - Provide custom lowering hooks for some operations.
19299 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19300 switch (Op.getOpcode()) {
19301 default: llvm_unreachable("Should not custom lower this!");
19302 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19303 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19304 return LowerCMP_SWAP(Op, Subtarget, DAG);
19305 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
19306 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
19307 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
19308 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
19309 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19310 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
19311 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
19312 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19313 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
19314 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19315 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19316 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
19317 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
19318 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
19319 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
19320 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
19321 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
19322 case ISD::SHL_PARTS:
19323 case ISD::SRA_PARTS:
19324 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
19325 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
19326 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
19327 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
19328 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
19329 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19330 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
19331 case ISD::SIGN_EXTEND_VECTOR_INREG:
19332 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19333 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
19334 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
19335 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
19336 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
19338 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
19339 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
19340 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
19341 case ISD::SETCC: return LowerSETCC(Op, DAG);
19342 case ISD::SELECT: return LowerSELECT(Op, DAG);
19343 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
19344 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
19345 case ISD::VASTART: return LowerVASTART(Op, DAG);
19346 case ISD::VAARG: return LowerVAARG(Op, DAG);
19347 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
19348 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19349 case ISD::INTRINSIC_VOID:
19350 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19351 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
19352 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
19353 case ISD::FRAME_TO_ARGS_OFFSET:
19354 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19355 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19356 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
19357 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
19358 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
19359 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
19360 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
19361 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
19362 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
19363 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
19365 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op, DAG);
19366 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
19367 case ISD::UMUL_LOHI:
19368 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
19371 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
19377 case ISD::UMULO: return LowerXALUO(Op, DAG);
19378 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
19379 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
19383 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19384 case ISD::ADD: return LowerADD(Op, DAG);
19385 case ISD::SUB: return LowerSUB(Op, DAG);
19389 case ISD::UMIN: return LowerMINMAX(Op, DAG);
19390 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
19391 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
19392 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
19393 case ISD::GC_TRANSITION_START:
19394 return LowerGC_TRANSITION_START(Op, DAG);
19395 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
19399 /// ReplaceNodeResults - Replace a node with an illegal result type
19400 /// with a new node built out of custom code.
19401 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19402 SmallVectorImpl<SDValue>&Results,
19403 SelectionDAG &DAG) const {
19405 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19406 switch (N->getOpcode()) {
19408 llvm_unreachable("Do not know how to custom type legalize this operation!");
19409 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19410 case X86ISD::FMINC:
19412 case X86ISD::FMAXC:
19413 case X86ISD::FMAX: {
19414 EVT VT = N->getValueType(0);
19415 if (VT != MVT::v2f32)
19416 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19417 SDValue UNDEF = DAG.getUNDEF(VT);
19418 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19419 N->getOperand(0), UNDEF);
19420 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19421 N->getOperand(1), UNDEF);
19422 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19425 case ISD::SIGN_EXTEND_INREG:
19430 // We don't want to expand or promote these.
19437 case ISD::UDIVREM: {
19438 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19439 Results.push_back(V);
19442 case ISD::FP_TO_SINT:
19443 case ISD::FP_TO_UINT: {
19444 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19446 std::pair<SDValue,SDValue> Vals =
19447 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19448 SDValue FIST = Vals.first, StackSlot = Vals.second;
19449 if (FIST.getNode()) {
19450 EVT VT = N->getValueType(0);
19451 // Return a load from the stack slot.
19452 if (StackSlot.getNode())
19453 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19454 MachinePointerInfo(),
19455 false, false, false, 0));
19457 Results.push_back(FIST);
19461 case ISD::UINT_TO_FP: {
19462 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19463 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19464 N->getValueType(0) != MVT::v2f32)
19466 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19468 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19470 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19471 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19472 DAG.getBitcast(MVT::v2i64, VBias));
19473 Or = DAG.getBitcast(MVT::v2f64, Or);
19474 // TODO: Are there any fast-math-flags to propagate here?
19475 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19476 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19479 case ISD::FP_ROUND: {
19480 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19482 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19483 Results.push_back(V);
19486 case ISD::FP_EXTEND: {
19487 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19488 // No other ValueType for FP_EXTEND should reach this point.
19489 assert(N->getValueType(0) == MVT::v2f32 &&
19490 "Do not know how to legalize this Node");
19493 case ISD::INTRINSIC_W_CHAIN: {
19494 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19496 default : llvm_unreachable("Do not know how to custom type "
19497 "legalize this intrinsic operation!");
19498 case Intrinsic::x86_rdtsc:
19499 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19501 case Intrinsic::x86_rdtscp:
19502 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19504 case Intrinsic::x86_rdpmc:
19505 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19508 case ISD::READCYCLECOUNTER: {
19509 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19512 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19513 EVT T = N->getValueType(0);
19514 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19515 bool Regs64bit = T == MVT::i128;
19516 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19517 SDValue cpInL, cpInH;
19518 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19519 DAG.getConstant(0, dl, HalfT));
19520 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19521 DAG.getConstant(1, dl, HalfT));
19522 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19523 Regs64bit ? X86::RAX : X86::EAX,
19525 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19526 Regs64bit ? X86::RDX : X86::EDX,
19527 cpInH, cpInL.getValue(1));
19528 SDValue swapInL, swapInH;
19529 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19530 DAG.getConstant(0, dl, HalfT));
19531 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19532 DAG.getConstant(1, dl, HalfT));
19533 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19534 Regs64bit ? X86::RBX : X86::EBX,
19535 swapInL, cpInH.getValue(1));
19536 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19537 Regs64bit ? X86::RCX : X86::ECX,
19538 swapInH, swapInL.getValue(1));
19539 SDValue Ops[] = { swapInH.getValue(0),
19541 swapInH.getValue(1) };
19542 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19543 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19544 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19545 X86ISD::LCMPXCHG8_DAG;
19546 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19547 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19548 Regs64bit ? X86::RAX : X86::EAX,
19549 HalfT, Result.getValue(1));
19550 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19551 Regs64bit ? X86::RDX : X86::EDX,
19552 HalfT, cpOutL.getValue(2));
19553 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19555 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19556 MVT::i32, cpOutH.getValue(2));
19558 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19559 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19560 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19562 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19563 Results.push_back(Success);
19564 Results.push_back(EFLAGS.getValue(1));
19567 case ISD::ATOMIC_SWAP:
19568 case ISD::ATOMIC_LOAD_ADD:
19569 case ISD::ATOMIC_LOAD_SUB:
19570 case ISD::ATOMIC_LOAD_AND:
19571 case ISD::ATOMIC_LOAD_OR:
19572 case ISD::ATOMIC_LOAD_XOR:
19573 case ISD::ATOMIC_LOAD_NAND:
19574 case ISD::ATOMIC_LOAD_MIN:
19575 case ISD::ATOMIC_LOAD_MAX:
19576 case ISD::ATOMIC_LOAD_UMIN:
19577 case ISD::ATOMIC_LOAD_UMAX:
19578 case ISD::ATOMIC_LOAD: {
19579 // Delegate to generic TypeLegalization. Situations we can really handle
19580 // should have already been dealt with by AtomicExpandPass.cpp.
19583 case ISD::BITCAST: {
19584 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19585 EVT DstVT = N->getValueType(0);
19586 EVT SrcVT = N->getOperand(0)->getValueType(0);
19588 if (SrcVT != MVT::f64 ||
19589 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19592 unsigned NumElts = DstVT.getVectorNumElements();
19593 EVT SVT = DstVT.getVectorElementType();
19594 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19595 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19596 MVT::v2f64, N->getOperand(0));
19597 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19599 if (ExperimentalVectorWideningLegalization) {
19600 // If we are legalizing vectors by widening, we already have the desired
19601 // legal vector type, just return it.
19602 Results.push_back(ToVecInt);
19606 SmallVector<SDValue, 8> Elts;
19607 for (unsigned i = 0, e = NumElts; i != e; ++i)
19608 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19609 ToVecInt, DAG.getIntPtrConstant(i, dl)));
19611 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19616 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19617 switch ((X86ISD::NodeType)Opcode) {
19618 case X86ISD::FIRST_NUMBER: break;
19619 case X86ISD::BSF: return "X86ISD::BSF";
19620 case X86ISD::BSR: return "X86ISD::BSR";
19621 case X86ISD::SHLD: return "X86ISD::SHLD";
19622 case X86ISD::SHRD: return "X86ISD::SHRD";
19623 case X86ISD::FAND: return "X86ISD::FAND";
19624 case X86ISD::FANDN: return "X86ISD::FANDN";
19625 case X86ISD::FOR: return "X86ISD::FOR";
19626 case X86ISD::FXOR: return "X86ISD::FXOR";
19627 case X86ISD::FILD: return "X86ISD::FILD";
19628 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
19629 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19630 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19631 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19632 case X86ISD::FLD: return "X86ISD::FLD";
19633 case X86ISD::FST: return "X86ISD::FST";
19634 case X86ISD::CALL: return "X86ISD::CALL";
19635 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
19636 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
19637 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
19638 case X86ISD::BT: return "X86ISD::BT";
19639 case X86ISD::CMP: return "X86ISD::CMP";
19640 case X86ISD::COMI: return "X86ISD::COMI";
19641 case X86ISD::UCOMI: return "X86ISD::UCOMI";
19642 case X86ISD::CMPM: return "X86ISD::CMPM";
19643 case X86ISD::CMPMU: return "X86ISD::CMPMU";
19644 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
19645 case X86ISD::SETCC: return "X86ISD::SETCC";
19646 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
19647 case X86ISD::FSETCC: return "X86ISD::FSETCC";
19648 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
19649 case X86ISD::CMOV: return "X86ISD::CMOV";
19650 case X86ISD::BRCOND: return "X86ISD::BRCOND";
19651 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
19652 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
19653 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
19654 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
19655 case X86ISD::Wrapper: return "X86ISD::Wrapper";
19656 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
19657 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
19658 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
19659 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
19660 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
19661 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
19662 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
19663 case X86ISD::PINSRB: return "X86ISD::PINSRB";
19664 case X86ISD::PINSRW: return "X86ISD::PINSRW";
19665 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
19666 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
19667 case X86ISD::ANDNP: return "X86ISD::ANDNP";
19668 case X86ISD::PSIGN: return "X86ISD::PSIGN";
19669 case X86ISD::BLENDI: return "X86ISD::BLENDI";
19670 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
19671 case X86ISD::ADDUS: return "X86ISD::ADDUS";
19672 case X86ISD::SUBUS: return "X86ISD::SUBUS";
19673 case X86ISD::HADD: return "X86ISD::HADD";
19674 case X86ISD::HSUB: return "X86ISD::HSUB";
19675 case X86ISD::FHADD: return "X86ISD::FHADD";
19676 case X86ISD::FHSUB: return "X86ISD::FHSUB";
19677 case X86ISD::ABS: return "X86ISD::ABS";
19678 case X86ISD::CONFLICT: return "X86ISD::CONFLICT";
19679 case X86ISD::FMAX: return "X86ISD::FMAX";
19680 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
19681 case X86ISD::FMIN: return "X86ISD::FMIN";
19682 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
19683 case X86ISD::FMAXC: return "X86ISD::FMAXC";
19684 case X86ISD::FMINC: return "X86ISD::FMINC";
19685 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
19686 case X86ISD::FRCP: return "X86ISD::FRCP";
19687 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
19688 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
19689 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
19690 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
19691 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
19692 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
19693 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
19694 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
19695 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
19696 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
19697 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
19698 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
19699 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
19700 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
19701 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
19702 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
19703 case X86ISD::VZEXT: return "X86ISD::VZEXT";
19704 case X86ISD::VSEXT: return "X86ISD::VSEXT";
19705 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
19706 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
19707 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
19708 case X86ISD::VINSERT: return "X86ISD::VINSERT";
19709 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
19710 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
19711 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
19712 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
19713 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
19714 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
19715 case X86ISD::VSHL: return "X86ISD::VSHL";
19716 case X86ISD::VSRL: return "X86ISD::VSRL";
19717 case X86ISD::VSRA: return "X86ISD::VSRA";
19718 case X86ISD::VSHLI: return "X86ISD::VSHLI";
19719 case X86ISD::VSRLI: return "X86ISD::VSRLI";
19720 case X86ISD::VSRAI: return "X86ISD::VSRAI";
19721 case X86ISD::CMPP: return "X86ISD::CMPP";
19722 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
19723 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
19724 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
19725 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
19726 case X86ISD::ADD: return "X86ISD::ADD";
19727 case X86ISD::SUB: return "X86ISD::SUB";
19728 case X86ISD::ADC: return "X86ISD::ADC";
19729 case X86ISD::SBB: return "X86ISD::SBB";
19730 case X86ISD::SMUL: return "X86ISD::SMUL";
19731 case X86ISD::UMUL: return "X86ISD::UMUL";
19732 case X86ISD::SMUL8: return "X86ISD::SMUL8";
19733 case X86ISD::UMUL8: return "X86ISD::UMUL8";
19734 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19735 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19736 case X86ISD::INC: return "X86ISD::INC";
19737 case X86ISD::DEC: return "X86ISD::DEC";
19738 case X86ISD::OR: return "X86ISD::OR";
19739 case X86ISD::XOR: return "X86ISD::XOR";
19740 case X86ISD::AND: return "X86ISD::AND";
19741 case X86ISD::BEXTR: return "X86ISD::BEXTR";
19742 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
19743 case X86ISD::PTEST: return "X86ISD::PTEST";
19744 case X86ISD::TESTP: return "X86ISD::TESTP";
19745 case X86ISD::TESTM: return "X86ISD::TESTM";
19746 case X86ISD::TESTNM: return "X86ISD::TESTNM";
19747 case X86ISD::KORTEST: return "X86ISD::KORTEST";
19748 case X86ISD::KTEST: return "X86ISD::KTEST";
19749 case X86ISD::PACKSS: return "X86ISD::PACKSS";
19750 case X86ISD::PACKUS: return "X86ISD::PACKUS";
19751 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
19752 case X86ISD::VALIGN: return "X86ISD::VALIGN";
19753 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
19754 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
19755 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
19756 case X86ISD::SHUFP: return "X86ISD::SHUFP";
19757 case X86ISD::SHUF128: return "X86ISD::SHUF128";
19758 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
19759 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
19760 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
19761 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
19762 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
19763 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
19764 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
19765 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
19766 case X86ISD::MOVSD: return "X86ISD::MOVSD";
19767 case X86ISD::MOVSS: return "X86ISD::MOVSS";
19768 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
19769 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
19770 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
19771 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
19772 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
19773 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
19774 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
19775 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
19776 case X86ISD::VPERMV: return "X86ISD::VPERMV";
19777 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
19778 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
19779 case X86ISD::VPERMI: return "X86ISD::VPERMI";
19780 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
19781 case X86ISD::VRANGE: return "X86ISD::VRANGE";
19782 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
19783 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
19784 case X86ISD::PSADBW: return "X86ISD::PSADBW";
19785 case X86ISD::DBPSADBW: return "X86ISD::DBPSADBW";
19786 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19787 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
19788 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
19789 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
19790 case X86ISD::MFENCE: return "X86ISD::MFENCE";
19791 case X86ISD::SFENCE: return "X86ISD::SFENCE";
19792 case X86ISD::LFENCE: return "X86ISD::LFENCE";
19793 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
19794 case X86ISD::SAHF: return "X86ISD::SAHF";
19795 case X86ISD::RDRAND: return "X86ISD::RDRAND";
19796 case X86ISD::RDSEED: return "X86ISD::RDSEED";
19797 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
19798 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
19799 case X86ISD::FMADD: return "X86ISD::FMADD";
19800 case X86ISD::FMSUB: return "X86ISD::FMSUB";
19801 case X86ISD::FNMADD: return "X86ISD::FNMADD";
19802 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
19803 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
19804 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
19805 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
19806 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
19807 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
19808 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
19809 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
19810 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
19811 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
19812 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
19813 case X86ISD::VGETMANT: return "X86ISD::VGETMANT";
19814 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
19815 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
19816 case X86ISD::XTEST: return "X86ISD::XTEST";
19817 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
19818 case X86ISD::EXPAND: return "X86ISD::EXPAND";
19819 case X86ISD::SELECT: return "X86ISD::SELECT";
19820 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
19821 case X86ISD::RCP28: return "X86ISD::RCP28";
19822 case X86ISD::EXP2: return "X86ISD::EXP2";
19823 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
19824 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
19825 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
19826 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
19827 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
19828 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
19829 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
19830 case X86ISD::SCALEF: return "X86ISD::SCALEF";
19831 case X86ISD::ADDS: return "X86ISD::ADDS";
19832 case X86ISD::SUBS: return "X86ISD::SUBS";
19833 case X86ISD::AVG: return "X86ISD::AVG";
19834 case X86ISD::MULHRS: return "X86ISD::MULHRS";
19835 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
19836 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
19837 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
19838 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
19839 case X86ISD::VFPCLASS: return "X86ISD::VFPCLASS";
19844 // isLegalAddressingMode - Return true if the addressing mode represented
19845 // by AM is legal for this target, for a load/store of the specified type.
19846 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19847 const AddrMode &AM, Type *Ty,
19848 unsigned AS) const {
19849 // X86 supports extremely general addressing modes.
19850 CodeModel::Model M = getTargetMachine().getCodeModel();
19851 Reloc::Model R = getTargetMachine().getRelocationModel();
19853 // X86 allows a sign-extended 32-bit immediate field as a displacement.
19854 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19859 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19861 // If a reference to this global requires an extra load, we can't fold it.
19862 if (isGlobalStubReference(GVFlags))
19865 // If BaseGV requires a register for the PIC base, we cannot also have a
19866 // BaseReg specified.
19867 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19870 // If lower 4G is not available, then we must use rip-relative addressing.
19871 if ((M != CodeModel::Small || R != Reloc::Static) &&
19872 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19876 switch (AM.Scale) {
19882 // These scales always work.
19887 // These scales are formed with basereg+scalereg. Only accept if there is
19892 default: // Other stuff never works.
19899 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19900 unsigned Bits = Ty->getScalarSizeInBits();
19902 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19903 // particularly cheaper than those without.
19907 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19908 // variable shifts just as cheap as scalar ones.
19909 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19912 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19913 // fully general vector.
19917 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19918 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19920 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19921 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19922 return NumBits1 > NumBits2;
19925 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19926 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19929 if (!isTypeLegal(EVT::getEVT(Ty1)))
19932 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19934 // Assuming the caller doesn't have a zeroext or signext return parameter,
19935 // truncation all the way down to i1 is valid.
19939 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19940 return isInt<32>(Imm);
19943 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19944 // Can also use sub to handle negated immediates.
19945 return isInt<32>(Imm);
19948 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19949 if (!VT1.isInteger() || !VT2.isInteger())
19951 unsigned NumBits1 = VT1.getSizeInBits();
19952 unsigned NumBits2 = VT2.getSizeInBits();
19953 return NumBits1 > NumBits2;
19956 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19957 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19958 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19961 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19962 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19963 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19966 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19967 EVT VT1 = Val.getValueType();
19968 if (isZExtFree(VT1, VT2))
19971 if (Val.getOpcode() != ISD::LOAD)
19974 if (!VT1.isSimple() || !VT1.isInteger() ||
19975 !VT2.isSimple() || !VT2.isInteger())
19978 switch (VT1.getSimpleVT().SimpleTy) {
19983 // X86 has 8, 16, and 32-bit zero-extending loads.
19990 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19993 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19994 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19997 VT = VT.getScalarType();
19999 if (!VT.isSimple())
20002 switch (VT.getSimpleVT().SimpleTy) {
20013 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20014 // i16 instructions are longer (0x66 prefix) and potentially slower.
20015 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20018 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20019 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20020 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20021 /// are assumed to be legal.
20023 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20025 if (!VT.isSimple())
20028 // Not for i1 vectors
20029 if (VT.getScalarType() == MVT::i1)
20032 // Very little shuffling can be done for 64-bit vectors right now.
20033 if (VT.getSizeInBits() == 64)
20036 // We only care that the types being shuffled are legal. The lowering can
20037 // handle any possible shuffle mask that results.
20038 return isTypeLegal(VT.getSimpleVT());
20042 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20044 // Just delegate to the generic legality, clear masks aren't special.
20045 return isShuffleMaskLegal(Mask, VT);
20048 //===----------------------------------------------------------------------===//
20049 // X86 Scheduler Hooks
20050 //===----------------------------------------------------------------------===//
20052 /// Utility function to emit xbegin specifying the start of an RTM region.
20053 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20054 const TargetInstrInfo *TII) {
20055 DebugLoc DL = MI->getDebugLoc();
20057 const BasicBlock *BB = MBB->getBasicBlock();
20058 MachineFunction::iterator I = MBB;
20061 // For the v = xbegin(), we generate
20072 MachineBasicBlock *thisMBB = MBB;
20073 MachineFunction *MF = MBB->getParent();
20074 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20075 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20076 MF->insert(I, mainMBB);
20077 MF->insert(I, sinkMBB);
20079 // Transfer the remainder of BB and its successor edges to sinkMBB.
20080 sinkMBB->splice(sinkMBB->begin(), MBB,
20081 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20082 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20086 // # fallthrough to mainMBB
20087 // # abortion to sinkMBB
20088 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20089 thisMBB->addSuccessor(mainMBB);
20090 thisMBB->addSuccessor(sinkMBB);
20094 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20095 mainMBB->addSuccessor(sinkMBB);
20098 // EAX is live into the sinkMBB
20099 sinkMBB->addLiveIn(X86::EAX);
20100 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20101 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20104 MI->eraseFromParent();
20108 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20109 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20110 // in the .td file.
20111 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20112 const TargetInstrInfo *TII) {
20114 switch (MI->getOpcode()) {
20115 default: llvm_unreachable("illegal opcode!");
20116 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
20117 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20118 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
20119 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20120 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
20121 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20122 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
20123 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20126 DebugLoc dl = MI->getDebugLoc();
20127 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20129 unsigned NumArgs = MI->getNumOperands();
20130 for (unsigned i = 1; i < NumArgs; ++i) {
20131 MachineOperand &Op = MI->getOperand(i);
20132 if (!(Op.isReg() && Op.isImplicit()))
20133 MIB.addOperand(Op);
20135 if (MI->hasOneMemOperand())
20136 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20138 BuildMI(*BB, MI, dl,
20139 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20140 .addReg(X86::XMM0);
20142 MI->eraseFromParent();
20146 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20147 // defs in an instruction pattern
20148 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20149 const TargetInstrInfo *TII) {
20151 switch (MI->getOpcode()) {
20152 default: llvm_unreachable("illegal opcode!");
20153 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
20154 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20155 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
20156 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20157 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
20158 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20159 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
20160 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20163 DebugLoc dl = MI->getDebugLoc();
20164 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20166 unsigned NumArgs = MI->getNumOperands(); // remove the results
20167 for (unsigned i = 1; i < NumArgs; ++i) {
20168 MachineOperand &Op = MI->getOperand(i);
20169 if (!(Op.isReg() && Op.isImplicit()))
20170 MIB.addOperand(Op);
20172 if (MI->hasOneMemOperand())
20173 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20175 BuildMI(*BB, MI, dl,
20176 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20179 MI->eraseFromParent();
20183 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20184 const X86Subtarget *Subtarget) {
20185 DebugLoc dl = MI->getDebugLoc();
20186 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20187 // Address into RAX/EAX, other two args into ECX, EDX.
20188 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20189 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20190 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20191 for (int i = 0; i < X86::AddrNumOperands; ++i)
20192 MIB.addOperand(MI->getOperand(i));
20194 unsigned ValOps = X86::AddrNumOperands;
20195 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20196 .addReg(MI->getOperand(ValOps).getReg());
20197 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20198 .addReg(MI->getOperand(ValOps+1).getReg());
20200 // The instruction doesn't actually take any operands though.
20201 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20203 MI->eraseFromParent(); // The pseudo is gone now.
20207 MachineBasicBlock *
20208 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20209 MachineBasicBlock *MBB) const {
20210 // Emit va_arg instruction on X86-64.
20212 // Operands to this pseudo-instruction:
20213 // 0 ) Output : destination address (reg)
20214 // 1-5) Input : va_list address (addr, i64mem)
20215 // 6 ) ArgSize : Size (in bytes) of vararg type
20216 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20217 // 8 ) Align : Alignment of type
20218 // 9 ) EFLAGS (implicit-def)
20220 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20221 static_assert(X86::AddrNumOperands == 5,
20222 "VAARG_64 assumes 5 address operands");
20224 unsigned DestReg = MI->getOperand(0).getReg();
20225 MachineOperand &Base = MI->getOperand(1);
20226 MachineOperand &Scale = MI->getOperand(2);
20227 MachineOperand &Index = MI->getOperand(3);
20228 MachineOperand &Disp = MI->getOperand(4);
20229 MachineOperand &Segment = MI->getOperand(5);
20230 unsigned ArgSize = MI->getOperand(6).getImm();
20231 unsigned ArgMode = MI->getOperand(7).getImm();
20232 unsigned Align = MI->getOperand(8).getImm();
20234 // Memory Reference
20235 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20236 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20237 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20239 // Machine Information
20240 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20241 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20242 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20243 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20244 DebugLoc DL = MI->getDebugLoc();
20246 // struct va_list {
20249 // i64 overflow_area (address)
20250 // i64 reg_save_area (address)
20252 // sizeof(va_list) = 24
20253 // alignment(va_list) = 8
20255 unsigned TotalNumIntRegs = 6;
20256 unsigned TotalNumXMMRegs = 8;
20257 bool UseGPOffset = (ArgMode == 1);
20258 bool UseFPOffset = (ArgMode == 2);
20259 unsigned MaxOffset = TotalNumIntRegs * 8 +
20260 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20262 /* Align ArgSize to a multiple of 8 */
20263 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20264 bool NeedsAlign = (Align > 8);
20266 MachineBasicBlock *thisMBB = MBB;
20267 MachineBasicBlock *overflowMBB;
20268 MachineBasicBlock *offsetMBB;
20269 MachineBasicBlock *endMBB;
20271 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
20272 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
20273 unsigned OffsetReg = 0;
20275 if (!UseGPOffset && !UseFPOffset) {
20276 // If we only pull from the overflow region, we don't create a branch.
20277 // We don't need to alter control flow.
20278 OffsetDestReg = 0; // unused
20279 OverflowDestReg = DestReg;
20281 offsetMBB = nullptr;
20282 overflowMBB = thisMBB;
20285 // First emit code to check if gp_offset (or fp_offset) is below the bound.
20286 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20287 // If not, pull from overflow_area. (branch to overflowMBB)
20292 // offsetMBB overflowMBB
20297 // Registers for the PHI in endMBB
20298 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20299 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20301 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20302 MachineFunction *MF = MBB->getParent();
20303 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20304 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20305 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20307 MachineFunction::iterator MBBIter = MBB;
20310 // Insert the new basic blocks
20311 MF->insert(MBBIter, offsetMBB);
20312 MF->insert(MBBIter, overflowMBB);
20313 MF->insert(MBBIter, endMBB);
20315 // Transfer the remainder of MBB and its successor edges to endMBB.
20316 endMBB->splice(endMBB->begin(), thisMBB,
20317 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20318 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20320 // Make offsetMBB and overflowMBB successors of thisMBB
20321 thisMBB->addSuccessor(offsetMBB);
20322 thisMBB->addSuccessor(overflowMBB);
20324 // endMBB is a successor of both offsetMBB and overflowMBB
20325 offsetMBB->addSuccessor(endMBB);
20326 overflowMBB->addSuccessor(endMBB);
20328 // Load the offset value into a register
20329 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20330 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
20334 .addDisp(Disp, UseFPOffset ? 4 : 0)
20335 .addOperand(Segment)
20336 .setMemRefs(MMOBegin, MMOEnd);
20338 // Check if there is enough room left to pull this argument.
20339 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
20341 .addImm(MaxOffset + 8 - ArgSizeA8);
20343 // Branch to "overflowMBB" if offset >= max
20344 // Fall through to "offsetMBB" otherwise
20345 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
20346 .addMBB(overflowMBB);
20349 // In offsetMBB, emit code to use the reg_save_area.
20351 assert(OffsetReg != 0);
20353 // Read the reg_save_area address.
20354 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
20355 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
20360 .addOperand(Segment)
20361 .setMemRefs(MMOBegin, MMOEnd);
20363 // Zero-extend the offset
20364 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
20365 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
20368 .addImm(X86::sub_32bit);
20370 // Add the offset to the reg_save_area to get the final address.
20371 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
20372 .addReg(OffsetReg64)
20373 .addReg(RegSaveReg);
20375 // Compute the offset for the next argument
20376 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
20377 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
20379 .addImm(UseFPOffset ? 16 : 8);
20381 // Store it back into the va_list.
20382 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20386 .addDisp(Disp, UseFPOffset ? 4 : 0)
20387 .addOperand(Segment)
20388 .addReg(NextOffsetReg)
20389 .setMemRefs(MMOBegin, MMOEnd);
20392 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20397 // Emit code to use overflow area
20400 // Load the overflow_area address into a register.
20401 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20402 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20407 .addOperand(Segment)
20408 .setMemRefs(MMOBegin, MMOEnd);
20410 // If we need to align it, do so. Otherwise, just copy the address
20411 // to OverflowDestReg.
20413 // Align the overflow address
20414 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20415 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20417 // aligned_addr = (addr + (align-1)) & ~(align-1)
20418 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20419 .addReg(OverflowAddrReg)
20422 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20424 .addImm(~(uint64_t)(Align-1));
20426 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20427 .addReg(OverflowAddrReg);
20430 // Compute the next overflow address after this argument.
20431 // (the overflow address should be kept 8-byte aligned)
20432 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20433 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20434 .addReg(OverflowDestReg)
20435 .addImm(ArgSizeA8);
20437 // Store the new overflow address.
20438 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20443 .addOperand(Segment)
20444 .addReg(NextAddrReg)
20445 .setMemRefs(MMOBegin, MMOEnd);
20447 // If we branched, emit the PHI to the front of endMBB.
20449 BuildMI(*endMBB, endMBB->begin(), DL,
20450 TII->get(X86::PHI), DestReg)
20451 .addReg(OffsetDestReg).addMBB(offsetMBB)
20452 .addReg(OverflowDestReg).addMBB(overflowMBB);
20455 // Erase the pseudo instruction
20456 MI->eraseFromParent();
20461 MachineBasicBlock *
20462 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20464 MachineBasicBlock *MBB) const {
20465 // Emit code to save XMM registers to the stack. The ABI says that the
20466 // number of registers to save is given in %al, so it's theoretically
20467 // possible to do an indirect jump trick to avoid saving all of them,
20468 // however this code takes a simpler approach and just executes all
20469 // of the stores if %al is non-zero. It's less code, and it's probably
20470 // easier on the hardware branch predictor, and stores aren't all that
20471 // expensive anyway.
20473 // Create the new basic blocks. One block contains all the XMM stores,
20474 // and one block is the final destination regardless of whether any
20475 // stores were performed.
20476 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20477 MachineFunction *F = MBB->getParent();
20478 MachineFunction::iterator MBBIter = MBB;
20480 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20481 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20482 F->insert(MBBIter, XMMSaveMBB);
20483 F->insert(MBBIter, EndMBB);
20485 // Transfer the remainder of MBB and its successor edges to EndMBB.
20486 EndMBB->splice(EndMBB->begin(), MBB,
20487 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20488 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20490 // The original block will now fall through to the XMM save block.
20491 MBB->addSuccessor(XMMSaveMBB);
20492 // The XMMSaveMBB will fall through to the end block.
20493 XMMSaveMBB->addSuccessor(EndMBB);
20495 // Now add the instructions.
20496 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20497 DebugLoc DL = MI->getDebugLoc();
20499 unsigned CountReg = MI->getOperand(0).getReg();
20500 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20501 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20503 if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20504 // If %al is 0, branch around the XMM save block.
20505 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20506 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20507 MBB->addSuccessor(EndMBB);
20510 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20511 // that was just emitted, but clearly shouldn't be "saved".
20512 assert((MI->getNumOperands() <= 3 ||
20513 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20514 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20515 && "Expected last argument to be EFLAGS");
20516 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20517 // In the XMM save block, save all the XMM argument registers.
20518 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20519 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20520 MachineMemOperand *MMO = F->getMachineMemOperand(
20521 MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20522 MachineMemOperand::MOStore,
20523 /*Size=*/16, /*Align=*/16);
20524 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20525 .addFrameIndex(RegSaveFrameIndex)
20526 .addImm(/*Scale=*/1)
20527 .addReg(/*IndexReg=*/0)
20528 .addImm(/*Disp=*/Offset)
20529 .addReg(/*Segment=*/0)
20530 .addReg(MI->getOperand(i).getReg())
20531 .addMemOperand(MMO);
20534 MI->eraseFromParent(); // The pseudo instruction is gone now.
20539 // The EFLAGS operand of SelectItr might be missing a kill marker
20540 // because there were multiple uses of EFLAGS, and ISel didn't know
20541 // which to mark. Figure out whether SelectItr should have had a
20542 // kill marker, and set it if it should. Returns the correct kill
20544 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20545 MachineBasicBlock* BB,
20546 const TargetRegisterInfo* TRI) {
20547 // Scan forward through BB for a use/def of EFLAGS.
20548 MachineBasicBlock::iterator miI(std::next(SelectItr));
20549 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20550 const MachineInstr& mi = *miI;
20551 if (mi.readsRegister(X86::EFLAGS))
20553 if (mi.definesRegister(X86::EFLAGS))
20554 break; // Should have kill-flag - update below.
20557 // If we hit the end of the block, check whether EFLAGS is live into a
20559 if (miI == BB->end()) {
20560 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20561 sEnd = BB->succ_end();
20562 sItr != sEnd; ++sItr) {
20563 MachineBasicBlock* succ = *sItr;
20564 if (succ->isLiveIn(X86::EFLAGS))
20569 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20570 // out. SelectMI should have a kill flag on EFLAGS.
20571 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20575 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20576 // together with other CMOV pseudo-opcodes into a single basic-block with
20577 // conditional jump around it.
20578 static bool isCMOVPseudo(MachineInstr *MI) {
20579 switch (MI->getOpcode()) {
20580 case X86::CMOV_FR32:
20581 case X86::CMOV_FR64:
20582 case X86::CMOV_GR8:
20583 case X86::CMOV_GR16:
20584 case X86::CMOV_GR32:
20585 case X86::CMOV_RFP32:
20586 case X86::CMOV_RFP64:
20587 case X86::CMOV_RFP80:
20588 case X86::CMOV_V2F64:
20589 case X86::CMOV_V2I64:
20590 case X86::CMOV_V4F32:
20591 case X86::CMOV_V4F64:
20592 case X86::CMOV_V4I64:
20593 case X86::CMOV_V16F32:
20594 case X86::CMOV_V8F32:
20595 case X86::CMOV_V8F64:
20596 case X86::CMOV_V8I64:
20597 case X86::CMOV_V8I1:
20598 case X86::CMOV_V16I1:
20599 case X86::CMOV_V32I1:
20600 case X86::CMOV_V64I1:
20608 MachineBasicBlock *
20609 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20610 MachineBasicBlock *BB) const {
20611 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20612 DebugLoc DL = MI->getDebugLoc();
20614 // To "insert" a SELECT_CC instruction, we actually have to insert the
20615 // diamond control-flow pattern. The incoming instruction knows the
20616 // destination vreg to set, the condition code register to branch on, the
20617 // true/false values to select between, and a branch opcode to use.
20618 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20619 MachineFunction::iterator It = BB;
20625 // cmpTY ccX, r1, r2
20627 // fallthrough --> copy0MBB
20628 MachineBasicBlock *thisMBB = BB;
20629 MachineFunction *F = BB->getParent();
20631 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20632 // as described above, by inserting a BB, and then making a PHI at the join
20633 // point to select the true and false operands of the CMOV in the PHI.
20635 // The code also handles two different cases of multiple CMOV opcodes
20639 // In this case, there are multiple CMOVs in a row, all which are based on
20640 // the same condition setting (or the exact opposite condition setting).
20641 // In this case we can lower all the CMOVs using a single inserted BB, and
20642 // then make a number of PHIs at the join point to model the CMOVs. The only
20643 // trickiness here, is that in a case like:
20645 // t2 = CMOV cond1 t1, f1
20646 // t3 = CMOV cond1 t2, f2
20648 // when rewriting this into PHIs, we have to perform some renaming on the
20649 // temps since you cannot have a PHI operand refer to a PHI result earlier
20650 // in the same block. The "simple" but wrong lowering would be:
20652 // t2 = PHI t1(BB1), f1(BB2)
20653 // t3 = PHI t2(BB1), f2(BB2)
20655 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20656 // renaming is to note that on the path through BB1, t2 is really just a
20657 // copy of t1, and do that renaming, properly generating:
20659 // t2 = PHI t1(BB1), f1(BB2)
20660 // t3 = PHI t1(BB1), f2(BB2)
20662 // Case 2, we lower cascaded CMOVs such as
20664 // (CMOV (CMOV F, T, cc1), T, cc2)
20666 // to two successives branches. For that, we look for another CMOV as the
20667 // following instruction.
20669 // Without this, we would add a PHI between the two jumps, which ends up
20670 // creating a few copies all around. For instance, for
20672 // (sitofp (zext (fcmp une)))
20674 // we would generate:
20676 // ucomiss %xmm1, %xmm0
20677 // movss <1.0f>, %xmm0
20678 // movaps %xmm0, %xmm1
20680 // xorps %xmm1, %xmm1
20683 // movaps %xmm1, %xmm0
20687 // because this custom-inserter would have generated:
20699 // A: X = ...; Y = ...
20701 // C: Z = PHI [X, A], [Y, B]
20703 // E: PHI [X, C], [Z, D]
20705 // If we lower both CMOVs in a single step, we can instead generate:
20717 // A: X = ...; Y = ...
20719 // E: PHI [X, A], [X, C], [Y, D]
20721 // Which, in our sitofp/fcmp example, gives us something like:
20723 // ucomiss %xmm1, %xmm0
20724 // movss <1.0f>, %xmm0
20727 // xorps %xmm0, %xmm0
20731 MachineInstr *CascadedCMOV = nullptr;
20732 MachineInstr *LastCMOV = MI;
20733 X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20734 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20735 MachineBasicBlock::iterator NextMIIt =
20736 std::next(MachineBasicBlock::iterator(MI));
20738 // Check for case 1, where there are multiple CMOVs with the same condition
20739 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
20740 // number of jumps the most.
20742 if (isCMOVPseudo(MI)) {
20743 // See if we have a string of CMOVS with the same condition.
20744 while (NextMIIt != BB->end() &&
20745 isCMOVPseudo(NextMIIt) &&
20746 (NextMIIt->getOperand(3).getImm() == CC ||
20747 NextMIIt->getOperand(3).getImm() == OppCC)) {
20748 LastCMOV = &*NextMIIt;
20753 // This checks for case 2, but only do this if we didn't already find
20754 // case 1, as indicated by LastCMOV == MI.
20755 if (LastCMOV == MI &&
20756 NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20757 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20758 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20759 CascadedCMOV = &*NextMIIt;
20762 MachineBasicBlock *jcc1MBB = nullptr;
20764 // If we have a cascaded CMOV, we lower it to two successive branches to
20765 // the same block. EFLAGS is used by both, so mark it as live in the second.
20766 if (CascadedCMOV) {
20767 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20768 F->insert(It, jcc1MBB);
20769 jcc1MBB->addLiveIn(X86::EFLAGS);
20772 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20773 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20774 F->insert(It, copy0MBB);
20775 F->insert(It, sinkMBB);
20777 // If the EFLAGS register isn't dead in the terminator, then claim that it's
20778 // live into the sink and copy blocks.
20779 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20781 MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20782 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20783 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20784 copy0MBB->addLiveIn(X86::EFLAGS);
20785 sinkMBB->addLiveIn(X86::EFLAGS);
20788 // Transfer the remainder of BB and its successor edges to sinkMBB.
20789 sinkMBB->splice(sinkMBB->begin(), BB,
20790 std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20791 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20793 // Add the true and fallthrough blocks as its successors.
20794 if (CascadedCMOV) {
20795 // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20796 BB->addSuccessor(jcc1MBB);
20798 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20799 // jump to the sinkMBB.
20800 jcc1MBB->addSuccessor(copy0MBB);
20801 jcc1MBB->addSuccessor(sinkMBB);
20803 BB->addSuccessor(copy0MBB);
20806 // The true block target of the first (or only) branch is always sinkMBB.
20807 BB->addSuccessor(sinkMBB);
20809 // Create the conditional branch instruction.
20810 unsigned Opc = X86::GetCondBranchFromCond(CC);
20811 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20813 if (CascadedCMOV) {
20814 unsigned Opc2 = X86::GetCondBranchFromCond(
20815 (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20816 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20820 // %FalseValue = ...
20821 // # fallthrough to sinkMBB
20822 copy0MBB->addSuccessor(sinkMBB);
20825 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20827 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20828 MachineBasicBlock::iterator MIItEnd =
20829 std::next(MachineBasicBlock::iterator(LastCMOV));
20830 MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20831 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20832 MachineInstrBuilder MIB;
20834 // As we are creating the PHIs, we have to be careful if there is more than
20835 // one. Later CMOVs may reference the results of earlier CMOVs, but later
20836 // PHIs have to reference the individual true/false inputs from earlier PHIs.
20837 // That also means that PHI construction must work forward from earlier to
20838 // later, and that the code must maintain a mapping from earlier PHI's
20839 // destination registers, and the registers that went into the PHI.
20841 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20842 unsigned DestReg = MIIt->getOperand(0).getReg();
20843 unsigned Op1Reg = MIIt->getOperand(1).getReg();
20844 unsigned Op2Reg = MIIt->getOperand(2).getReg();
20846 // If this CMOV we are generating is the opposite condition from
20847 // the jump we generated, then we have to swap the operands for the
20848 // PHI that is going to be generated.
20849 if (MIIt->getOperand(3).getImm() == OppCC)
20850 std::swap(Op1Reg, Op2Reg);
20852 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20853 Op1Reg = RegRewriteTable[Op1Reg].first;
20855 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20856 Op2Reg = RegRewriteTable[Op2Reg].second;
20858 MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20859 TII->get(X86::PHI), DestReg)
20860 .addReg(Op1Reg).addMBB(copy0MBB)
20861 .addReg(Op2Reg).addMBB(thisMBB);
20863 // Add this PHI to the rewrite table.
20864 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20867 // If we have a cascaded CMOV, the second Jcc provides the same incoming
20868 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20869 if (CascadedCMOV) {
20870 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20871 // Copy the PHI result to the register defined by the second CMOV.
20872 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20873 DL, TII->get(TargetOpcode::COPY),
20874 CascadedCMOV->getOperand(0).getReg())
20875 .addReg(MI->getOperand(0).getReg());
20876 CascadedCMOV->eraseFromParent();
20879 // Now remove the CMOV(s).
20880 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20881 (MIIt++)->eraseFromParent();
20886 MachineBasicBlock *
20887 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20888 MachineBasicBlock *BB) const {
20889 // Combine the following atomic floating-point modification pattern:
20890 // a.store(reg OP a.load(acquire), release)
20891 // Transform them into:
20892 // OPss (%gpr), %xmm
20893 // movss %xmm, (%gpr)
20894 // Or sd equivalent for 64-bit operations.
20896 switch (MI->getOpcode()) {
20897 default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20898 case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20899 case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20901 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20902 DebugLoc DL = MI->getDebugLoc();
20903 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20904 unsigned MSrc = MI->getOperand(0).getReg();
20905 unsigned VSrc = MI->getOperand(5).getReg();
20906 MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20907 .addReg(/*Base=*/MSrc)
20908 .addImm(/*Scale=*/1)
20909 .addReg(/*Index=*/0)
20912 MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20913 MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20915 .addReg(/*Base=*/MSrc)
20916 .addImm(/*Scale=*/1)
20917 .addReg(/*Index=*/0)
20918 .addImm(/*Disp=*/0)
20919 .addReg(/*Segment=*/0);
20920 MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20921 MI->eraseFromParent(); // The pseudo instruction is gone now.
20925 MachineBasicBlock *
20926 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20927 MachineBasicBlock *BB) const {
20928 MachineFunction *MF = BB->getParent();
20929 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20930 DebugLoc DL = MI->getDebugLoc();
20931 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20933 assert(MF->shouldSplitStack());
20935 const bool Is64Bit = Subtarget->is64Bit();
20936 const bool IsLP64 = Subtarget->isTarget64BitLP64();
20938 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20939 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20942 // ... [Till the alloca]
20943 // If stacklet is not large enough, jump to mallocMBB
20946 // Allocate by subtracting from RSP
20947 // Jump to continueMBB
20950 // Allocate by call to runtime
20954 // [rest of original BB]
20957 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20958 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20959 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20961 MachineRegisterInfo &MRI = MF->getRegInfo();
20962 const TargetRegisterClass *AddrRegClass =
20963 getRegClassFor(getPointerTy(MF->getDataLayout()));
20965 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20966 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20967 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20968 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20969 sizeVReg = MI->getOperand(1).getReg(),
20970 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20972 MachineFunction::iterator MBBIter = BB;
20975 MF->insert(MBBIter, bumpMBB);
20976 MF->insert(MBBIter, mallocMBB);
20977 MF->insert(MBBIter, continueMBB);
20979 continueMBB->splice(continueMBB->begin(), BB,
20980 std::next(MachineBasicBlock::iterator(MI)), BB->end());
20981 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20983 // Add code to the main basic block to check if the stack limit has been hit,
20984 // and if so, jump to mallocMBB otherwise to bumpMBB.
20985 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20986 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20987 .addReg(tmpSPVReg).addReg(sizeVReg);
20988 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20989 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20990 .addReg(SPLimitVReg);
20991 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20993 // bumpMBB simply decreases the stack pointer, since we know the current
20994 // stacklet has enough space.
20995 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20996 .addReg(SPLimitVReg);
20997 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20998 .addReg(SPLimitVReg);
20999 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21001 // Calls into a routine in libgcc to allocate more space from the heap.
21002 const uint32_t *RegMask =
21003 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
21005 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21007 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21008 .addExternalSymbol("__morestack_allocate_stack_space")
21009 .addRegMask(RegMask)
21010 .addReg(X86::RDI, RegState::Implicit)
21011 .addReg(X86::RAX, RegState::ImplicitDefine);
21012 } else if (Is64Bit) {
21013 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21015 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21016 .addExternalSymbol("__morestack_allocate_stack_space")
21017 .addRegMask(RegMask)
21018 .addReg(X86::EDI, RegState::Implicit)
21019 .addReg(X86::EAX, RegState::ImplicitDefine);
21021 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21023 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21024 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21025 .addExternalSymbol("__morestack_allocate_stack_space")
21026 .addRegMask(RegMask)
21027 .addReg(X86::EAX, RegState::ImplicitDefine);
21031 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21034 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21035 .addReg(IsLP64 ? X86::RAX : X86::EAX);
21036 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21038 // Set up the CFG correctly.
21039 BB->addSuccessor(bumpMBB);
21040 BB->addSuccessor(mallocMBB);
21041 mallocMBB->addSuccessor(continueMBB);
21042 bumpMBB->addSuccessor(continueMBB);
21044 // Take care of the PHI nodes.
21045 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21046 MI->getOperand(0).getReg())
21047 .addReg(mallocPtrVReg).addMBB(mallocMBB)
21048 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21050 // Delete the original pseudo instruction.
21051 MI->eraseFromParent();
21054 return continueMBB;
21057 MachineBasicBlock *
21058 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21059 MachineBasicBlock *BB) const {
21060 DebugLoc DL = MI->getDebugLoc();
21062 assert(!Subtarget->isTargetMachO());
21064 Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
21067 MI->eraseFromParent(); // The pseudo instruction is gone now.
21071 MachineBasicBlock *
21072 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
21073 MachineBasicBlock *BB) const {
21074 // This is pretty easy. We're taking the value that we received from
21075 // our load from the relocation, sticking it in either RDI (x86-64)
21076 // or EAX and doing an indirect call. The return value will then
21077 // be in the normal return register.
21078 MachineFunction *F = BB->getParent();
21079 const X86InstrInfo *TII = Subtarget->getInstrInfo();
21080 DebugLoc DL = MI->getDebugLoc();
21082 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
21083 assert(MI->getOperand(3).isGlobal() && "This should be a global");
21085 // Get a register mask for the lowered call.
21086 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
21087 // proper register mask.
21088 const uint32_t *RegMask =
21089 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
21090 if (Subtarget->is64Bit()) {
21091 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21092 TII->get(X86::MOV64rm), X86::RDI)
21094 .addImm(0).addReg(0)
21095 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21096 MI->getOperand(3).getTargetFlags())
21098 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21099 addDirectMem(MIB, X86::RDI);
21100 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21101 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21102 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21103 TII->get(X86::MOV32rm), X86::EAX)
21105 .addImm(0).addReg(0)
21106 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21107 MI->getOperand(3).getTargetFlags())
21109 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21110 addDirectMem(MIB, X86::EAX);
21111 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21113 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21114 TII->get(X86::MOV32rm), X86::EAX)
21115 .addReg(TII->getGlobalBaseReg(F))
21116 .addImm(0).addReg(0)
21117 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21118 MI->getOperand(3).getTargetFlags())
21120 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21121 addDirectMem(MIB, X86::EAX);
21122 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21125 MI->eraseFromParent(); // The pseudo instruction is gone now.
21129 MachineBasicBlock *
21130 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21131 MachineBasicBlock *MBB) const {
21132 DebugLoc DL = MI->getDebugLoc();
21133 MachineFunction *MF = MBB->getParent();
21134 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21135 MachineRegisterInfo &MRI = MF->getRegInfo();
21137 const BasicBlock *BB = MBB->getBasicBlock();
21138 MachineFunction::iterator I = MBB;
21141 // Memory Reference
21142 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21143 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21146 unsigned MemOpndSlot = 0;
21148 unsigned CurOp = 0;
21150 DstReg = MI->getOperand(CurOp++).getReg();
21151 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21152 assert(RC->hasType(MVT::i32) && "Invalid destination!");
21153 unsigned mainDstReg = MRI.createVirtualRegister(RC);
21154 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21156 MemOpndSlot = CurOp;
21158 MVT PVT = getPointerTy(MF->getDataLayout());
21159 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21160 "Invalid Pointer Size!");
21162 // For v = setjmp(buf), we generate
21165 // buf[LabelOffset] = restoreMBB
21166 // SjLjSetup restoreMBB
21172 // v = phi(main, restore)
21175 // if base pointer being used, load it from frame
21178 MachineBasicBlock *thisMBB = MBB;
21179 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21180 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21181 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21182 MF->insert(I, mainMBB);
21183 MF->insert(I, sinkMBB);
21184 MF->push_back(restoreMBB);
21186 MachineInstrBuilder MIB;
21188 // Transfer the remainder of BB and its successor edges to sinkMBB.
21189 sinkMBB->splice(sinkMBB->begin(), MBB,
21190 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21191 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21194 unsigned PtrStoreOpc = 0;
21195 unsigned LabelReg = 0;
21196 const int64_t LabelOffset = 1 * PVT.getStoreSize();
21197 Reloc::Model RM = MF->getTarget().getRelocationModel();
21198 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21199 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21201 // Prepare IP either in reg or imm.
21202 if (!UseImmLabel) {
21203 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21204 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21205 LabelReg = MRI.createVirtualRegister(PtrRC);
21206 if (Subtarget->is64Bit()) {
21207 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21211 .addMBB(restoreMBB)
21214 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21215 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21216 .addReg(XII->getGlobalBaseReg(MF))
21219 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21223 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21225 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21226 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21227 if (i == X86::AddrDisp)
21228 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21230 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21233 MIB.addReg(LabelReg);
21235 MIB.addMBB(restoreMBB);
21236 MIB.setMemRefs(MMOBegin, MMOEnd);
21238 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21239 .addMBB(restoreMBB);
21241 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21242 MIB.addRegMask(RegInfo->getNoPreservedMask());
21243 thisMBB->addSuccessor(mainMBB);
21244 thisMBB->addSuccessor(restoreMBB);
21248 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21249 mainMBB->addSuccessor(sinkMBB);
21252 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21253 TII->get(X86::PHI), DstReg)
21254 .addReg(mainDstReg).addMBB(mainMBB)
21255 .addReg(restoreDstReg).addMBB(restoreMBB);
21258 if (RegInfo->hasBasePointer(*MF)) {
21259 const bool Uses64BitFramePtr =
21260 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21261 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21262 X86FI->setRestoreBasePointer(MF);
21263 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21264 unsigned BasePtr = RegInfo->getBaseRegister();
21265 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21266 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21267 FramePtr, true, X86FI->getRestoreBasePointerOffset())
21268 .setMIFlag(MachineInstr::FrameSetup);
21270 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21271 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21272 restoreMBB->addSuccessor(sinkMBB);
21274 MI->eraseFromParent();
21278 MachineBasicBlock *
21279 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
21280 MachineBasicBlock *MBB) const {
21281 DebugLoc DL = MI->getDebugLoc();
21282 MachineFunction *MF = MBB->getParent();
21283 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21284 MachineRegisterInfo &MRI = MF->getRegInfo();
21286 // Memory Reference
21287 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21288 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21290 MVT PVT = getPointerTy(MF->getDataLayout());
21291 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21292 "Invalid Pointer Size!");
21294 const TargetRegisterClass *RC =
21295 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
21296 unsigned Tmp = MRI.createVirtualRegister(RC);
21297 // Since FP is only updated here but NOT referenced, it's treated as GPR.
21298 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21299 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
21300 unsigned SP = RegInfo->getStackRegister();
21302 MachineInstrBuilder MIB;
21304 const int64_t LabelOffset = 1 * PVT.getStoreSize();
21305 const int64_t SPOffset = 2 * PVT.getStoreSize();
21307 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
21308 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
21311 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
21312 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
21313 MIB.addOperand(MI->getOperand(i));
21314 MIB.setMemRefs(MMOBegin, MMOEnd);
21316 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
21317 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21318 if (i == X86::AddrDisp)
21319 MIB.addDisp(MI->getOperand(i), LabelOffset);
21321 MIB.addOperand(MI->getOperand(i));
21323 MIB.setMemRefs(MMOBegin, MMOEnd);
21325 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
21326 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21327 if (i == X86::AddrDisp)
21328 MIB.addDisp(MI->getOperand(i), SPOffset);
21330 MIB.addOperand(MI->getOperand(i));
21332 MIB.setMemRefs(MMOBegin, MMOEnd);
21334 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
21336 MI->eraseFromParent();
21340 // Replace 213-type (isel default) FMA3 instructions with 231-type for
21341 // accumulator loops. Writing back to the accumulator allows the coalescer
21342 // to remove extra copies in the loop.
21343 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
21344 MachineBasicBlock *
21345 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
21346 MachineBasicBlock *MBB) const {
21347 MachineOperand &AddendOp = MI->getOperand(3);
21349 // Bail out early if the addend isn't a register - we can't switch these.
21350 if (!AddendOp.isReg())
21353 MachineFunction &MF = *MBB->getParent();
21354 MachineRegisterInfo &MRI = MF.getRegInfo();
21356 // Check whether the addend is defined by a PHI:
21357 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
21358 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
21359 if (!AddendDef.isPHI())
21362 // Look for the following pattern:
21364 // %addend = phi [%entry, 0], [%loop, %result]
21366 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
21370 // %addend = phi [%entry, 0], [%loop, %result]
21372 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
21374 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
21375 assert(AddendDef.getOperand(i).isReg());
21376 MachineOperand PHISrcOp = AddendDef.getOperand(i);
21377 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
21378 if (&PHISrcInst == MI) {
21379 // Found a matching instruction.
21380 unsigned NewFMAOpc = 0;
21381 switch (MI->getOpcode()) {
21382 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21383 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21384 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21385 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21386 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21387 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21388 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21389 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21390 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21391 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21392 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21393 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21394 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21395 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21396 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21397 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21398 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21399 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21400 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21401 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21403 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21404 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21405 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21406 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21407 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21408 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21409 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21410 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21411 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21412 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21413 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21414 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21415 default: llvm_unreachable("Unrecognized FMA variant.");
21418 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21419 MachineInstrBuilder MIB =
21420 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21421 .addOperand(MI->getOperand(0))
21422 .addOperand(MI->getOperand(3))
21423 .addOperand(MI->getOperand(2))
21424 .addOperand(MI->getOperand(1));
21425 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21426 MI->eraseFromParent();
21433 MachineBasicBlock *
21434 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21435 MachineBasicBlock *BB) const {
21436 switch (MI->getOpcode()) {
21437 default: llvm_unreachable("Unexpected instr type to insert");
21438 case X86::TAILJMPd64:
21439 case X86::TAILJMPr64:
21440 case X86::TAILJMPm64:
21441 case X86::TAILJMPd64_REX:
21442 case X86::TAILJMPr64_REX:
21443 case X86::TAILJMPm64_REX:
21444 llvm_unreachable("TAILJMP64 would not be touched here.");
21445 case X86::TCRETURNdi64:
21446 case X86::TCRETURNri64:
21447 case X86::TCRETURNmi64:
21449 case X86::WIN_ALLOCA:
21450 return EmitLoweredWinAlloca(MI, BB);
21451 case X86::SEG_ALLOCA_32:
21452 case X86::SEG_ALLOCA_64:
21453 return EmitLoweredSegAlloca(MI, BB);
21454 case X86::TLSCall_32:
21455 case X86::TLSCall_64:
21456 return EmitLoweredTLSCall(MI, BB);
21457 case X86::CMOV_FR32:
21458 case X86::CMOV_FR64:
21459 case X86::CMOV_GR8:
21460 case X86::CMOV_GR16:
21461 case X86::CMOV_GR32:
21462 case X86::CMOV_RFP32:
21463 case X86::CMOV_RFP64:
21464 case X86::CMOV_RFP80:
21465 case X86::CMOV_V2F64:
21466 case X86::CMOV_V2I64:
21467 case X86::CMOV_V4F32:
21468 case X86::CMOV_V4F64:
21469 case X86::CMOV_V4I64:
21470 case X86::CMOV_V16F32:
21471 case X86::CMOV_V8F32:
21472 case X86::CMOV_V8F64:
21473 case X86::CMOV_V8I64:
21474 case X86::CMOV_V8I1:
21475 case X86::CMOV_V16I1:
21476 case X86::CMOV_V32I1:
21477 case X86::CMOV_V64I1:
21478 return EmitLoweredSelect(MI, BB);
21480 case X86::RELEASE_FADD32mr:
21481 case X86::RELEASE_FADD64mr:
21482 return EmitLoweredAtomicFP(MI, BB);
21484 case X86::FP32_TO_INT16_IN_MEM:
21485 case X86::FP32_TO_INT32_IN_MEM:
21486 case X86::FP32_TO_INT64_IN_MEM:
21487 case X86::FP64_TO_INT16_IN_MEM:
21488 case X86::FP64_TO_INT32_IN_MEM:
21489 case X86::FP64_TO_INT64_IN_MEM:
21490 case X86::FP80_TO_INT16_IN_MEM:
21491 case X86::FP80_TO_INT32_IN_MEM:
21492 case X86::FP80_TO_INT64_IN_MEM: {
21493 MachineFunction *F = BB->getParent();
21494 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21495 DebugLoc DL = MI->getDebugLoc();
21497 // Change the floating point control register to use "round towards zero"
21498 // mode when truncating to an integer value.
21499 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21500 addFrameReference(BuildMI(*BB, MI, DL,
21501 TII->get(X86::FNSTCW16m)), CWFrameIdx);
21503 // Load the old value of the high byte of the control word...
21505 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21506 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21509 // Set the high part to be round to zero...
21510 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21513 // Reload the modified control word now...
21514 addFrameReference(BuildMI(*BB, MI, DL,
21515 TII->get(X86::FLDCW16m)), CWFrameIdx);
21517 // Restore the memory image of control word to original value
21518 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21521 // Get the X86 opcode to use.
21523 switch (MI->getOpcode()) {
21524 default: llvm_unreachable("illegal opcode!");
21525 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21526 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21527 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21528 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21529 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21530 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21531 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21532 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21533 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21537 MachineOperand &Op = MI->getOperand(0);
21539 AM.BaseType = X86AddressMode::RegBase;
21540 AM.Base.Reg = Op.getReg();
21542 AM.BaseType = X86AddressMode::FrameIndexBase;
21543 AM.Base.FrameIndex = Op.getIndex();
21545 Op = MI->getOperand(1);
21547 AM.Scale = Op.getImm();
21548 Op = MI->getOperand(2);
21550 AM.IndexReg = Op.getImm();
21551 Op = MI->getOperand(3);
21552 if (Op.isGlobal()) {
21553 AM.GV = Op.getGlobal();
21555 AM.Disp = Op.getImm();
21557 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21558 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21560 // Reload the original control word now.
21561 addFrameReference(BuildMI(*BB, MI, DL,
21562 TII->get(X86::FLDCW16m)), CWFrameIdx);
21564 MI->eraseFromParent(); // The pseudo instruction is gone now.
21567 // String/text processing lowering.
21568 case X86::PCMPISTRM128REG:
21569 case X86::VPCMPISTRM128REG:
21570 case X86::PCMPISTRM128MEM:
21571 case X86::VPCMPISTRM128MEM:
21572 case X86::PCMPESTRM128REG:
21573 case X86::VPCMPESTRM128REG:
21574 case X86::PCMPESTRM128MEM:
21575 case X86::VPCMPESTRM128MEM:
21576 assert(Subtarget->hasSSE42() &&
21577 "Target must have SSE4.2 or AVX features enabled");
21578 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21580 // String/text processing lowering.
21581 case X86::PCMPISTRIREG:
21582 case X86::VPCMPISTRIREG:
21583 case X86::PCMPISTRIMEM:
21584 case X86::VPCMPISTRIMEM:
21585 case X86::PCMPESTRIREG:
21586 case X86::VPCMPESTRIREG:
21587 case X86::PCMPESTRIMEM:
21588 case X86::VPCMPESTRIMEM:
21589 assert(Subtarget->hasSSE42() &&
21590 "Target must have SSE4.2 or AVX features enabled");
21591 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21593 // Thread synchronization.
21595 return EmitMonitor(MI, BB, Subtarget);
21599 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21601 case X86::VASTART_SAVE_XMM_REGS:
21602 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21604 case X86::VAARG_64:
21605 return EmitVAARG64WithCustomInserter(MI, BB);
21607 case X86::EH_SjLj_SetJmp32:
21608 case X86::EH_SjLj_SetJmp64:
21609 return emitEHSjLjSetJmp(MI, BB);
21611 case X86::EH_SjLj_LongJmp32:
21612 case X86::EH_SjLj_LongJmp64:
21613 return emitEHSjLjLongJmp(MI, BB);
21615 case TargetOpcode::STATEPOINT:
21616 // As an implementation detail, STATEPOINT shares the STACKMAP format at
21617 // this point in the process. We diverge later.
21618 return emitPatchPoint(MI, BB);
21620 case TargetOpcode::STACKMAP:
21621 case TargetOpcode::PATCHPOINT:
21622 return emitPatchPoint(MI, BB);
21624 case X86::VFMADDPDr213r:
21625 case X86::VFMADDPSr213r:
21626 case X86::VFMADDSDr213r:
21627 case X86::VFMADDSSr213r:
21628 case X86::VFMSUBPDr213r:
21629 case X86::VFMSUBPSr213r:
21630 case X86::VFMSUBSDr213r:
21631 case X86::VFMSUBSSr213r:
21632 case X86::VFNMADDPDr213r:
21633 case X86::VFNMADDPSr213r:
21634 case X86::VFNMADDSDr213r:
21635 case X86::VFNMADDSSr213r:
21636 case X86::VFNMSUBPDr213r:
21637 case X86::VFNMSUBPSr213r:
21638 case X86::VFNMSUBSDr213r:
21639 case X86::VFNMSUBSSr213r:
21640 case X86::VFMADDSUBPDr213r:
21641 case X86::VFMADDSUBPSr213r:
21642 case X86::VFMSUBADDPDr213r:
21643 case X86::VFMSUBADDPSr213r:
21644 case X86::VFMADDPDr213rY:
21645 case X86::VFMADDPSr213rY:
21646 case X86::VFMSUBPDr213rY:
21647 case X86::VFMSUBPSr213rY:
21648 case X86::VFNMADDPDr213rY:
21649 case X86::VFNMADDPSr213rY:
21650 case X86::VFNMSUBPDr213rY:
21651 case X86::VFNMSUBPSr213rY:
21652 case X86::VFMADDSUBPDr213rY:
21653 case X86::VFMADDSUBPSr213rY:
21654 case X86::VFMSUBADDPDr213rY:
21655 case X86::VFMSUBADDPSr213rY:
21656 return emitFMA3Instr(MI, BB);
21660 //===----------------------------------------------------------------------===//
21661 // X86 Optimization Hooks
21662 //===----------------------------------------------------------------------===//
21664 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21667 const SelectionDAG &DAG,
21668 unsigned Depth) const {
21669 unsigned BitWidth = KnownZero.getBitWidth();
21670 unsigned Opc = Op.getOpcode();
21671 assert((Opc >= ISD::BUILTIN_OP_END ||
21672 Opc == ISD::INTRINSIC_WO_CHAIN ||
21673 Opc == ISD::INTRINSIC_W_CHAIN ||
21674 Opc == ISD::INTRINSIC_VOID) &&
21675 "Should use MaskedValueIsZero if you don't know whether Op"
21676 " is a target node!");
21678 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
21692 // These nodes' second result is a boolean.
21693 if (Op.getResNo() == 0)
21696 case X86ISD::SETCC:
21697 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21699 case ISD::INTRINSIC_WO_CHAIN: {
21700 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21701 unsigned NumLoBits = 0;
21704 case Intrinsic::x86_sse_movmsk_ps:
21705 case Intrinsic::x86_avx_movmsk_ps_256:
21706 case Intrinsic::x86_sse2_movmsk_pd:
21707 case Intrinsic::x86_avx_movmsk_pd_256:
21708 case Intrinsic::x86_mmx_pmovmskb:
21709 case Intrinsic::x86_sse2_pmovmskb_128:
21710 case Intrinsic::x86_avx2_pmovmskb: {
21711 // High bits of movmskp{s|d}, pmovmskb are known zero.
21713 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
21714 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
21715 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
21716 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
21717 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
21718 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
21719 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
21720 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
21722 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21731 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21733 const SelectionDAG &,
21734 unsigned Depth) const {
21735 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21736 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21737 return Op.getValueType().getScalarType().getSizeInBits();
21743 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21744 /// node is a GlobalAddress + offset.
21745 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21746 const GlobalValue* &GA,
21747 int64_t &Offset) const {
21748 if (N->getOpcode() == X86ISD::Wrapper) {
21749 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21750 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21751 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21755 return TargetLowering::isGAPlusOffset(N, GA, Offset);
21758 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21759 /// same as extracting the high 128-bit part of 256-bit vector and then
21760 /// inserting the result into the low part of a new 256-bit vector
21761 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21762 EVT VT = SVOp->getValueType(0);
21763 unsigned NumElems = VT.getVectorNumElements();
21765 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21766 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21767 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21768 SVOp->getMaskElt(j) >= 0)
21774 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21775 /// same as extracting the low 128-bit part of 256-bit vector and then
21776 /// inserting the result into the high part of a new 256-bit vector
21777 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21778 EVT VT = SVOp->getValueType(0);
21779 unsigned NumElems = VT.getVectorNumElements();
21781 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21782 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21783 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21784 SVOp->getMaskElt(j) >= 0)
21790 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21791 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21792 TargetLowering::DAGCombinerInfo &DCI,
21793 const X86Subtarget* Subtarget) {
21795 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21796 SDValue V1 = SVOp->getOperand(0);
21797 SDValue V2 = SVOp->getOperand(1);
21798 EVT VT = SVOp->getValueType(0);
21799 unsigned NumElems = VT.getVectorNumElements();
21801 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21802 V2.getOpcode() == ISD::CONCAT_VECTORS) {
21806 // V UNDEF BUILD_VECTOR UNDEF
21808 // CONCAT_VECTOR CONCAT_VECTOR
21811 // RESULT: V + zero extended
21813 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21814 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21815 V1.getOperand(1).getOpcode() != ISD::UNDEF)
21818 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21821 // To match the shuffle mask, the first half of the mask should
21822 // be exactly the first vector, and all the rest a splat with the
21823 // first element of the second one.
21824 for (unsigned i = 0; i != NumElems/2; ++i)
21825 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21826 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21829 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21830 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21831 if (Ld->hasNUsesOfValue(1, 0)) {
21832 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21833 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21835 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21837 Ld->getPointerInfo(),
21838 Ld->getAlignment(),
21839 false/*isVolatile*/, true/*ReadMem*/,
21840 false/*WriteMem*/);
21842 // Make sure the newly-created LOAD is in the same position as Ld in
21843 // terms of dependency. We create a TokenFactor for Ld and ResNode,
21844 // and update uses of Ld's output chain to use the TokenFactor.
21845 if (Ld->hasAnyUseOfValue(1)) {
21846 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21847 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21848 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21849 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21850 SDValue(ResNode.getNode(), 1));
21853 return DAG.getBitcast(VT, ResNode);
21857 // Emit a zeroed vector and insert the desired subvector on its
21859 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21860 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21861 return DCI.CombineTo(N, InsV);
21864 //===--------------------------------------------------------------------===//
21865 // Combine some shuffles into subvector extracts and inserts:
21868 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21869 if (isShuffleHigh128VectorInsertLow(SVOp)) {
21870 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21871 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21872 return DCI.CombineTo(N, InsV);
21875 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21876 if (isShuffleLow128VectorInsertHigh(SVOp)) {
21877 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21878 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21879 return DCI.CombineTo(N, InsV);
21885 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21888 /// This is the leaf of the recursive combinine below. When we have found some
21889 /// chain of single-use x86 shuffle instructions and accumulated the combined
21890 /// shuffle mask represented by them, this will try to pattern match that mask
21891 /// into either a single instruction if there is a special purpose instruction
21892 /// for this operation, or into a PSHUFB instruction which is a fully general
21893 /// instruction but should only be used to replace chains over a certain depth.
21894 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21895 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21896 TargetLowering::DAGCombinerInfo &DCI,
21897 const X86Subtarget *Subtarget) {
21898 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21900 // Find the operand that enters the chain. Note that multiple uses are OK
21901 // here, we're not going to remove the operand we find.
21902 SDValue Input = Op.getOperand(0);
21903 while (Input.getOpcode() == ISD::BITCAST)
21904 Input = Input.getOperand(0);
21906 MVT VT = Input.getSimpleValueType();
21907 MVT RootVT = Root.getSimpleValueType();
21910 // Just remove no-op shuffle masks.
21911 if (Mask.size() == 1) {
21912 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21917 // Use the float domain if the operand type is a floating point type.
21918 bool FloatDomain = VT.isFloatingPoint();
21920 // For floating point shuffles, we don't have free copies in the shuffle
21921 // instructions or the ability to load as part of the instruction, so
21922 // canonicalize their shuffles to UNPCK or MOV variants.
21924 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21925 // vectors because it can have a load folded into it that UNPCK cannot. This
21926 // doesn't preclude something switching to the shorter encoding post-RA.
21928 // FIXME: Should teach these routines about AVX vector widths.
21929 if (FloatDomain && VT.getSizeInBits() == 128) {
21930 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21931 bool Lo = Mask.equals({0, 0});
21934 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21935 // is no slower than UNPCKLPD but has the option to fold the input operand
21936 // into even an unaligned memory load.
21937 if (Lo && Subtarget->hasSSE3()) {
21938 Shuffle = X86ISD::MOVDDUP;
21939 ShuffleVT = MVT::v2f64;
21941 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21942 // than the UNPCK variants.
21943 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21944 ShuffleVT = MVT::v4f32;
21946 if (Depth == 1 && Root->getOpcode() == Shuffle)
21947 return false; // Nothing to do!
21948 Op = DAG.getBitcast(ShuffleVT, Input);
21949 DCI.AddToWorklist(Op.getNode());
21950 if (Shuffle == X86ISD::MOVDDUP)
21951 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21953 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21954 DCI.AddToWorklist(Op.getNode());
21955 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21959 if (Subtarget->hasSSE3() &&
21960 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21961 bool Lo = Mask.equals({0, 0, 2, 2});
21962 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21963 MVT ShuffleVT = MVT::v4f32;
21964 if (Depth == 1 && Root->getOpcode() == Shuffle)
21965 return false; // Nothing to do!
21966 Op = DAG.getBitcast(ShuffleVT, Input);
21967 DCI.AddToWorklist(Op.getNode());
21968 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21969 DCI.AddToWorklist(Op.getNode());
21970 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21974 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21975 bool Lo = Mask.equals({0, 0, 1, 1});
21976 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21977 MVT ShuffleVT = MVT::v4f32;
21978 if (Depth == 1 && Root->getOpcode() == Shuffle)
21979 return false; // Nothing to do!
21980 Op = DAG.getBitcast(ShuffleVT, Input);
21981 DCI.AddToWorklist(Op.getNode());
21982 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21983 DCI.AddToWorklist(Op.getNode());
21984 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21990 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21991 // variants as none of these have single-instruction variants that are
21992 // superior to the UNPCK formulation.
21993 if (!FloatDomain && VT.getSizeInBits() == 128 &&
21994 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21995 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21996 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21998 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21999 bool Lo = Mask[0] == 0;
22000 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22001 if (Depth == 1 && Root->getOpcode() == Shuffle)
22002 return false; // Nothing to do!
22004 switch (Mask.size()) {
22006 ShuffleVT = MVT::v8i16;
22009 ShuffleVT = MVT::v16i8;
22012 llvm_unreachable("Impossible mask size!");
22014 Op = DAG.getBitcast(ShuffleVT, Input);
22015 DCI.AddToWorklist(Op.getNode());
22016 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22017 DCI.AddToWorklist(Op.getNode());
22018 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22023 // Don't try to re-form single instruction chains under any circumstances now
22024 // that we've done encoding canonicalization for them.
22028 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22029 // can replace them with a single PSHUFB instruction profitably. Intel's
22030 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22031 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22032 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22033 SmallVector<SDValue, 16> PSHUFBMask;
22034 int NumBytes = VT.getSizeInBits() / 8;
22035 int Ratio = NumBytes / Mask.size();
22036 for (int i = 0; i < NumBytes; ++i) {
22037 if (Mask[i / Ratio] == SM_SentinelUndef) {
22038 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22041 int M = Mask[i / Ratio] != SM_SentinelZero
22042 ? Ratio * Mask[i / Ratio] + i % Ratio
22044 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
22046 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
22047 Op = DAG.getBitcast(ByteVT, Input);
22048 DCI.AddToWorklist(Op.getNode());
22049 SDValue PSHUFBMaskOp =
22050 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
22051 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22052 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
22053 DCI.AddToWorklist(Op.getNode());
22054 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22059 // Failed to find any combines.
22063 /// \brief Fully generic combining of x86 shuffle instructions.
22065 /// This should be the last combine run over the x86 shuffle instructions. Once
22066 /// they have been fully optimized, this will recursively consider all chains
22067 /// of single-use shuffle instructions, build a generic model of the cumulative
22068 /// shuffle operation, and check for simpler instructions which implement this
22069 /// operation. We use this primarily for two purposes:
22071 /// 1) Collapse generic shuffles to specialized single instructions when
22072 /// equivalent. In most cases, this is just an encoding size win, but
22073 /// sometimes we will collapse multiple generic shuffles into a single
22074 /// special-purpose shuffle.
22075 /// 2) Look for sequences of shuffle instructions with 3 or more total
22076 /// instructions, and replace them with the slightly more expensive SSSE3
22077 /// PSHUFB instruction if available. We do this as the last combining step
22078 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
22079 /// a suitable short sequence of other instructions. The PHUFB will either
22080 /// use a register or have to read from memory and so is slightly (but only
22081 /// slightly) more expensive than the other shuffle instructions.
22083 /// Because this is inherently a quadratic operation (for each shuffle in
22084 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
22085 /// This should never be an issue in practice as the shuffle lowering doesn't
22086 /// produce sequences of more than 8 instructions.
22088 /// FIXME: We will currently miss some cases where the redundant shuffling
22089 /// would simplify under the threshold for PSHUFB formation because of
22090 /// combine-ordering. To fix this, we should do the redundant instruction
22091 /// combining in this recursive walk.
22092 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
22093 ArrayRef<int> RootMask,
22094 int Depth, bool HasPSHUFB,
22096 TargetLowering::DAGCombinerInfo &DCI,
22097 const X86Subtarget *Subtarget) {
22098 // Bound the depth of our recursive combine because this is ultimately
22099 // quadratic in nature.
22103 // Directly rip through bitcasts to find the underlying operand.
22104 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22105 Op = Op.getOperand(0);
22107 MVT VT = Op.getSimpleValueType();
22108 if (!VT.isVector())
22109 return false; // Bail if we hit a non-vector.
22111 assert(Root.getSimpleValueType().isVector() &&
22112 "Shuffles operate on vector types!");
22113 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22114 "Can only combine shuffles of the same vector register size.");
22116 if (!isTargetShuffle(Op.getOpcode()))
22118 SmallVector<int, 16> OpMask;
22120 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22121 // We only can combine unary shuffles which we can decode the mask for.
22122 if (!HaveMask || !IsUnary)
22125 assert(VT.getVectorNumElements() == OpMask.size() &&
22126 "Different mask size from vector size!");
22127 assert(((RootMask.size() > OpMask.size() &&
22128 RootMask.size() % OpMask.size() == 0) ||
22129 (OpMask.size() > RootMask.size() &&
22130 OpMask.size() % RootMask.size() == 0) ||
22131 OpMask.size() == RootMask.size()) &&
22132 "The smaller number of elements must divide the larger.");
22133 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22134 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22135 assert(((RootRatio == 1 && OpRatio == 1) ||
22136 (RootRatio == 1) != (OpRatio == 1)) &&
22137 "Must not have a ratio for both incoming and op masks!");
22139 SmallVector<int, 16> Mask;
22140 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22142 // Merge this shuffle operation's mask into our accumulated mask. Note that
22143 // this shuffle's mask will be the first applied to the input, followed by the
22144 // root mask to get us all the way to the root value arrangement. The reason
22145 // for this order is that we are recursing up the operation chain.
22146 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22147 int RootIdx = i / RootRatio;
22148 if (RootMask[RootIdx] < 0) {
22149 // This is a zero or undef lane, we're done.
22150 Mask.push_back(RootMask[RootIdx]);
22154 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22155 int OpIdx = RootMaskedIdx / OpRatio;
22156 if (OpMask[OpIdx] < 0) {
22157 // The incoming lanes are zero or undef, it doesn't matter which ones we
22159 Mask.push_back(OpMask[OpIdx]);
22163 // Ok, we have non-zero lanes, map them through.
22164 Mask.push_back(OpMask[OpIdx] * OpRatio +
22165 RootMaskedIdx % OpRatio);
22168 // See if we can recurse into the operand to combine more things.
22169 switch (Op.getOpcode()) {
22170 case X86ISD::PSHUFB:
22172 case X86ISD::PSHUFD:
22173 case X86ISD::PSHUFHW:
22174 case X86ISD::PSHUFLW:
22175 if (Op.getOperand(0).hasOneUse() &&
22176 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22177 HasPSHUFB, DAG, DCI, Subtarget))
22181 case X86ISD::UNPCKL:
22182 case X86ISD::UNPCKH:
22183 assert(Op.getOperand(0) == Op.getOperand(1) &&
22184 "We only combine unary shuffles!");
22185 // We can't check for single use, we have to check that this shuffle is the
22187 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22188 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22189 HasPSHUFB, DAG, DCI, Subtarget))
22194 // Minor canonicalization of the accumulated shuffle mask to make it easier
22195 // to match below. All this does is detect masks with squential pairs of
22196 // elements, and shrink them to the half-width mask. It does this in a loop
22197 // so it will reduce the size of the mask to the minimal width mask which
22198 // performs an equivalent shuffle.
22199 SmallVector<int, 16> WidenedMask;
22200 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22201 Mask = std::move(WidenedMask);
22202 WidenedMask.clear();
22205 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22209 /// \brief Get the PSHUF-style mask from PSHUF node.
22211 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22212 /// PSHUF-style masks that can be reused with such instructions.
22213 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22214 MVT VT = N.getSimpleValueType();
22215 SmallVector<int, 4> Mask;
22217 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22221 // If we have more than 128-bits, only the low 128-bits of shuffle mask
22222 // matter. Check that the upper masks are repeats and remove them.
22223 if (VT.getSizeInBits() > 128) {
22224 int LaneElts = 128 / VT.getScalarSizeInBits();
22226 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22227 for (int j = 0; j < LaneElts; ++j)
22228 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22229 "Mask doesn't repeat in high 128-bit lanes!");
22231 Mask.resize(LaneElts);
22234 switch (N.getOpcode()) {
22235 case X86ISD::PSHUFD:
22237 case X86ISD::PSHUFLW:
22240 case X86ISD::PSHUFHW:
22241 Mask.erase(Mask.begin(), Mask.begin() + 4);
22242 for (int &M : Mask)
22246 llvm_unreachable("No valid shuffle instruction found!");
22250 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22252 /// We walk up the chain and look for a combinable shuffle, skipping over
22253 /// shuffles that we could hoist this shuffle's transformation past without
22254 /// altering anything.
22256 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
22258 TargetLowering::DAGCombinerInfo &DCI) {
22259 assert(N.getOpcode() == X86ISD::PSHUFD &&
22260 "Called with something other than an x86 128-bit half shuffle!");
22263 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
22264 // of the shuffles in the chain so that we can form a fresh chain to replace
22266 SmallVector<SDValue, 8> Chain;
22267 SDValue V = N.getOperand(0);
22268 for (; V.hasOneUse(); V = V.getOperand(0)) {
22269 switch (V.getOpcode()) {
22271 return SDValue(); // Nothing combined!
22274 // Skip bitcasts as we always know the type for the target specific
22278 case X86ISD::PSHUFD:
22279 // Found another dword shuffle.
22282 case X86ISD::PSHUFLW:
22283 // Check that the low words (being shuffled) are the identity in the
22284 // dword shuffle, and the high words are self-contained.
22285 if (Mask[0] != 0 || Mask[1] != 1 ||
22286 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
22289 Chain.push_back(V);
22292 case X86ISD::PSHUFHW:
22293 // Check that the high words (being shuffled) are the identity in the
22294 // dword shuffle, and the low words are self-contained.
22295 if (Mask[2] != 2 || Mask[3] != 3 ||
22296 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
22299 Chain.push_back(V);
22302 case X86ISD::UNPCKL:
22303 case X86ISD::UNPCKH:
22304 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
22305 // shuffle into a preceding word shuffle.
22306 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
22307 V.getSimpleValueType().getScalarType() != MVT::i16)
22310 // Search for a half-shuffle which we can combine with.
22311 unsigned CombineOp =
22312 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
22313 if (V.getOperand(0) != V.getOperand(1) ||
22314 !V->isOnlyUserOf(V.getOperand(0).getNode()))
22316 Chain.push_back(V);
22317 V = V.getOperand(0);
22319 switch (V.getOpcode()) {
22321 return SDValue(); // Nothing to combine.
22323 case X86ISD::PSHUFLW:
22324 case X86ISD::PSHUFHW:
22325 if (V.getOpcode() == CombineOp)
22328 Chain.push_back(V);
22332 V = V.getOperand(0);
22336 } while (V.hasOneUse());
22339 // Break out of the loop if we break out of the switch.
22343 if (!V.hasOneUse())
22344 // We fell out of the loop without finding a viable combining instruction.
22347 // Merge this node's mask and our incoming mask.
22348 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22349 for (int &M : Mask)
22351 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
22352 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22354 // Rebuild the chain around this new shuffle.
22355 while (!Chain.empty()) {
22356 SDValue W = Chain.pop_back_val();
22358 if (V.getValueType() != W.getOperand(0).getValueType())
22359 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
22361 switch (W.getOpcode()) {
22363 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
22365 case X86ISD::UNPCKL:
22366 case X86ISD::UNPCKH:
22367 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
22370 case X86ISD::PSHUFD:
22371 case X86ISD::PSHUFLW:
22372 case X86ISD::PSHUFHW:
22373 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
22377 if (V.getValueType() != N.getValueType())
22378 V = DAG.getBitcast(N.getValueType(), V);
22380 // Return the new chain to replace N.
22384 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
22387 /// We walk up the chain, skipping shuffles of the other half and looking
22388 /// through shuffles which switch halves trying to find a shuffle of the same
22389 /// pair of dwords.
22390 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22392 TargetLowering::DAGCombinerInfo &DCI) {
22394 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22395 "Called with something other than an x86 128-bit half shuffle!");
22397 unsigned CombineOpcode = N.getOpcode();
22399 // Walk up a single-use chain looking for a combinable shuffle.
22400 SDValue V = N.getOperand(0);
22401 for (; V.hasOneUse(); V = V.getOperand(0)) {
22402 switch (V.getOpcode()) {
22404 return false; // Nothing combined!
22407 // Skip bitcasts as we always know the type for the target specific
22411 case X86ISD::PSHUFLW:
22412 case X86ISD::PSHUFHW:
22413 if (V.getOpcode() == CombineOpcode)
22416 // Other-half shuffles are no-ops.
22419 // Break out of the loop if we break out of the switch.
22423 if (!V.hasOneUse())
22424 // We fell out of the loop without finding a viable combining instruction.
22427 // Combine away the bottom node as its shuffle will be accumulated into
22428 // a preceding shuffle.
22429 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22431 // Record the old value.
22434 // Merge this node's mask and our incoming mask (adjusted to account for all
22435 // the pshufd instructions encountered).
22436 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22437 for (int &M : Mask)
22439 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22440 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22442 // Check that the shuffles didn't cancel each other out. If not, we need to
22443 // combine to the new one.
22445 // Replace the combinable shuffle with the combined one, updating all users
22446 // so that we re-evaluate the chain here.
22447 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22452 /// \brief Try to combine x86 target specific shuffles.
22453 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22454 TargetLowering::DAGCombinerInfo &DCI,
22455 const X86Subtarget *Subtarget) {
22457 MVT VT = N.getSimpleValueType();
22458 SmallVector<int, 4> Mask;
22460 switch (N.getOpcode()) {
22461 case X86ISD::PSHUFD:
22462 case X86ISD::PSHUFLW:
22463 case X86ISD::PSHUFHW:
22464 Mask = getPSHUFShuffleMask(N);
22465 assert(Mask.size() == 4);
22471 // Nuke no-op shuffles that show up after combining.
22472 if (isNoopShuffleMask(Mask))
22473 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22475 // Look for simplifications involving one or two shuffle instructions.
22476 SDValue V = N.getOperand(0);
22477 switch (N.getOpcode()) {
22480 case X86ISD::PSHUFLW:
22481 case X86ISD::PSHUFHW:
22482 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22484 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22485 return SDValue(); // We combined away this shuffle, so we're done.
22487 // See if this reduces to a PSHUFD which is no more expensive and can
22488 // combine with more operations. Note that it has to at least flip the
22489 // dwords as otherwise it would have been removed as a no-op.
22490 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22491 int DMask[] = {0, 1, 2, 3};
22492 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22493 DMask[DOffset + 0] = DOffset + 1;
22494 DMask[DOffset + 1] = DOffset + 0;
22495 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22496 V = DAG.getBitcast(DVT, V);
22497 DCI.AddToWorklist(V.getNode());
22498 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22499 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22500 DCI.AddToWorklist(V.getNode());
22501 return DAG.getBitcast(VT, V);
22504 // Look for shuffle patterns which can be implemented as a single unpack.
22505 // FIXME: This doesn't handle the location of the PSHUFD generically, and
22506 // only works when we have a PSHUFD followed by two half-shuffles.
22507 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22508 (V.getOpcode() == X86ISD::PSHUFLW ||
22509 V.getOpcode() == X86ISD::PSHUFHW) &&
22510 V.getOpcode() != N.getOpcode() &&
22512 SDValue D = V.getOperand(0);
22513 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22514 D = D.getOperand(0);
22515 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22516 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22517 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22518 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22519 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22521 for (int i = 0; i < 4; ++i) {
22522 WordMask[i + NOffset] = Mask[i] + NOffset;
22523 WordMask[i + VOffset] = VMask[i] + VOffset;
22525 // Map the word mask through the DWord mask.
22527 for (int i = 0; i < 8; ++i)
22528 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22529 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22530 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22531 // We can replace all three shuffles with an unpack.
22532 V = DAG.getBitcast(VT, D.getOperand(0));
22533 DCI.AddToWorklist(V.getNode());
22534 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22543 case X86ISD::PSHUFD:
22544 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22553 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22555 /// We combine this directly on the abstract vector shuffle nodes so it is
22556 /// easier to generically match. We also insert dummy vector shuffle nodes for
22557 /// the operands which explicitly discard the lanes which are unused by this
22558 /// operation to try to flow through the rest of the combiner the fact that
22559 /// they're unused.
22560 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22562 EVT VT = N->getValueType(0);
22564 // We only handle target-independent shuffles.
22565 // FIXME: It would be easy and harmless to use the target shuffle mask
22566 // extraction tool to support more.
22567 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22570 auto *SVN = cast<ShuffleVectorSDNode>(N);
22571 ArrayRef<int> Mask = SVN->getMask();
22572 SDValue V1 = N->getOperand(0);
22573 SDValue V2 = N->getOperand(1);
22575 // We require the first shuffle operand to be the SUB node, and the second to
22576 // be the ADD node.
22577 // FIXME: We should support the commuted patterns.
22578 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22581 // If there are other uses of these operations we can't fold them.
22582 if (!V1->hasOneUse() || !V2->hasOneUse())
22585 // Ensure that both operations have the same operands. Note that we can
22586 // commute the FADD operands.
22587 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22588 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22589 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22592 // We're looking for blends between FADD and FSUB nodes. We insist on these
22593 // nodes being lined up in a specific expected pattern.
22594 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22595 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22596 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22599 // Only specific types are legal at this point, assert so we notice if and
22600 // when these change.
22601 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22602 VT == MVT::v4f64) &&
22603 "Unknown vector type encountered!");
22605 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22608 /// PerformShuffleCombine - Performs several different shuffle combines.
22609 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22610 TargetLowering::DAGCombinerInfo &DCI,
22611 const X86Subtarget *Subtarget) {
22613 SDValue N0 = N->getOperand(0);
22614 SDValue N1 = N->getOperand(1);
22615 EVT VT = N->getValueType(0);
22617 // Don't create instructions with illegal types after legalize types has run.
22618 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22619 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22622 // If we have legalized the vector types, look for blends of FADD and FSUB
22623 // nodes that we can fuse into an ADDSUB node.
22624 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22625 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22628 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22629 if (Subtarget->hasFp256() && VT.is256BitVector() &&
22630 N->getOpcode() == ISD::VECTOR_SHUFFLE)
22631 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22633 // During Type Legalization, when promoting illegal vector types,
22634 // the backend might introduce new shuffle dag nodes and bitcasts.
22636 // This code performs the following transformation:
22637 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22638 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22640 // We do this only if both the bitcast and the BINOP dag nodes have
22641 // one use. Also, perform this transformation only if the new binary
22642 // operation is legal. This is to avoid introducing dag nodes that
22643 // potentially need to be further expanded (or custom lowered) into a
22644 // less optimal sequence of dag nodes.
22645 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22646 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22647 N0.getOpcode() == ISD::BITCAST) {
22648 SDValue BC0 = N0.getOperand(0);
22649 EVT SVT = BC0.getValueType();
22650 unsigned Opcode = BC0.getOpcode();
22651 unsigned NumElts = VT.getVectorNumElements();
22653 if (BC0.hasOneUse() && SVT.isVector() &&
22654 SVT.getVectorNumElements() * 2 == NumElts &&
22655 TLI.isOperationLegal(Opcode, VT)) {
22656 bool CanFold = false;
22668 unsigned SVTNumElts = SVT.getVectorNumElements();
22669 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22670 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22671 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22672 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22673 CanFold = SVOp->getMaskElt(i) < 0;
22676 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22677 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22678 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22679 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22684 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22685 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22686 // consecutive, non-overlapping, and in the right order.
22687 SmallVector<SDValue, 16> Elts;
22688 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22689 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22691 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22694 if (isTargetShuffle(N->getOpcode())) {
22696 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22697 if (Shuffle.getNode())
22700 // Try recursively combining arbitrary sequences of x86 shuffle
22701 // instructions into higher-order shuffles. We do this after combining
22702 // specific PSHUF instruction sequences into their minimal form so that we
22703 // can evaluate how many specialized shuffle instructions are involved in
22704 // a particular chain.
22705 SmallVector<int, 1> NonceMask; // Just a placeholder.
22706 NonceMask.push_back(0);
22707 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22708 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22710 return SDValue(); // This routine will use CombineTo to replace N.
22716 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22717 /// specific shuffle of a load can be folded into a single element load.
22718 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22719 /// shuffles have been custom lowered so we need to handle those here.
22720 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22721 TargetLowering::DAGCombinerInfo &DCI) {
22722 if (DCI.isBeforeLegalizeOps())
22725 SDValue InVec = N->getOperand(0);
22726 SDValue EltNo = N->getOperand(1);
22728 if (!isa<ConstantSDNode>(EltNo))
22731 EVT OriginalVT = InVec.getValueType();
22733 if (InVec.getOpcode() == ISD::BITCAST) {
22734 // Don't duplicate a load with other uses.
22735 if (!InVec.hasOneUse())
22737 EVT BCVT = InVec.getOperand(0).getValueType();
22738 if (!BCVT.isVector() ||
22739 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22741 InVec = InVec.getOperand(0);
22744 EVT CurrentVT = InVec.getValueType();
22746 if (!isTargetShuffle(InVec.getOpcode()))
22749 // Don't duplicate a load with other uses.
22750 if (!InVec.hasOneUse())
22753 SmallVector<int, 16> ShuffleMask;
22755 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22756 ShuffleMask, UnaryShuffle))
22759 // Select the input vector, guarding against out of range extract vector.
22760 unsigned NumElems = CurrentVT.getVectorNumElements();
22761 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22762 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22763 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22764 : InVec.getOperand(1);
22766 // If inputs to shuffle are the same for both ops, then allow 2 uses
22767 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22768 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22770 if (LdNode.getOpcode() == ISD::BITCAST) {
22771 // Don't duplicate a load with other uses.
22772 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22775 AllowedUses = 1; // only allow 1 load use if we have a bitcast
22776 LdNode = LdNode.getOperand(0);
22779 if (!ISD::isNormalLoad(LdNode.getNode()))
22782 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22784 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22787 EVT EltVT = N->getValueType(0);
22788 // If there's a bitcast before the shuffle, check if the load type and
22789 // alignment is valid.
22790 unsigned Align = LN0->getAlignment();
22791 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22792 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22793 EltVT.getTypeForEVT(*DAG.getContext()));
22795 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22798 // All checks match so transform back to vector_shuffle so that DAG combiner
22799 // can finish the job
22802 // Create shuffle node taking into account the case that its a unary shuffle
22803 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22804 : InVec.getOperand(1);
22805 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22806 InVec.getOperand(0), Shuffle,
22808 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22809 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22813 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22814 /// special and don't usually play with other vector types, it's better to
22815 /// handle them early to be sure we emit efficient code by avoiding
22816 /// store-load conversions.
22817 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22818 if (N->getValueType(0) != MVT::x86mmx ||
22819 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22820 N->getOperand(0)->getValueType(0) != MVT::v2i32)
22823 SDValue V = N->getOperand(0);
22824 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22825 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22826 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22827 N->getValueType(0), V.getOperand(0));
22832 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22833 /// generation and convert it from being a bunch of shuffles and extracts
22834 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22835 /// storing the value and loading scalars back, while for x64 we should
22836 /// use 64-bit extracts and shifts.
22837 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22838 TargetLowering::DAGCombinerInfo &DCI) {
22839 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22842 SDValue InputVector = N->getOperand(0);
22843 SDLoc dl(InputVector);
22844 // Detect mmx to i32 conversion through a v2i32 elt extract.
22845 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22846 N->getValueType(0) == MVT::i32 &&
22847 InputVector.getValueType() == MVT::v2i32) {
22849 // The bitcast source is a direct mmx result.
22850 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22851 if (MMXSrc.getValueType() == MVT::x86mmx)
22852 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22853 N->getValueType(0),
22854 InputVector.getNode()->getOperand(0));
22856 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22857 SDValue MMXSrcOp = MMXSrc.getOperand(0);
22858 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22859 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22860 MMXSrcOp.getOpcode() == ISD::BITCAST &&
22861 MMXSrcOp.getValueType() == MVT::v1i64 &&
22862 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22863 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22864 N->getValueType(0),
22865 MMXSrcOp.getOperand(0));
22868 EVT VT = N->getValueType(0);
22870 if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22871 InputVector.getOpcode() == ISD::BITCAST &&
22872 dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22873 uint64_t ExtractedElt =
22874 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22875 uint64_t InputValue =
22876 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22877 uint64_t Res = (InputValue >> ExtractedElt) & 1;
22878 return DAG.getConstant(Res, dl, MVT::i1);
22880 // Only operate on vectors of 4 elements, where the alternative shuffling
22881 // gets to be more expensive.
22882 if (InputVector.getValueType() != MVT::v4i32)
22885 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22886 // single use which is a sign-extend or zero-extend, and all elements are
22888 SmallVector<SDNode *, 4> Uses;
22889 unsigned ExtractedElements = 0;
22890 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22891 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22892 if (UI.getUse().getResNo() != InputVector.getResNo())
22895 SDNode *Extract = *UI;
22896 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22899 if (Extract->getValueType(0) != MVT::i32)
22901 if (!Extract->hasOneUse())
22903 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22904 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22906 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22909 // Record which element was extracted.
22910 ExtractedElements |=
22911 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22913 Uses.push_back(Extract);
22916 // If not all the elements were used, this may not be worthwhile.
22917 if (ExtractedElements != 15)
22920 // Ok, we've now decided to do the transformation.
22921 // If 64-bit shifts are legal, use the extract-shift sequence,
22922 // otherwise bounce the vector off the cache.
22923 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22926 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22927 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22928 auto &DL = DAG.getDataLayout();
22929 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22930 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22931 DAG.getConstant(0, dl, VecIdxTy));
22932 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22933 DAG.getConstant(1, dl, VecIdxTy));
22935 SDValue ShAmt = DAG.getConstant(
22936 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22937 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22938 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22939 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22940 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22941 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22942 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22944 // Store the value to a temporary stack slot.
22945 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22946 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22947 MachinePointerInfo(), false, false, 0);
22949 EVT ElementType = InputVector.getValueType().getVectorElementType();
22950 unsigned EltSize = ElementType.getSizeInBits() / 8;
22952 // Replace each use (extract) with a load of the appropriate element.
22953 for (unsigned i = 0; i < 4; ++i) {
22954 uint64_t Offset = EltSize * i;
22955 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22956 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22958 SDValue ScalarAddr =
22959 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22961 // Load the scalar.
22962 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22963 ScalarAddr, MachinePointerInfo(),
22964 false, false, false, 0);
22969 // Replace the extracts
22970 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22971 UE = Uses.end(); UI != UE; ++UI) {
22972 SDNode *Extract = *UI;
22974 SDValue Idx = Extract->getOperand(1);
22975 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22976 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22979 // The replacement was made in place; don't return anything.
22984 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22985 const X86Subtarget *Subtarget) {
22987 SDValue Cond = N->getOperand(0);
22988 SDValue LHS = N->getOperand(1);
22989 SDValue RHS = N->getOperand(2);
22991 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22992 SDValue CondSrc = Cond->getOperand(0);
22993 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22994 Cond = CondSrc->getOperand(0);
22997 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
23000 // A vselect where all conditions and data are constants can be optimized into
23001 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23002 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23003 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23006 unsigned MaskValue = 0;
23007 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23010 MVT VT = N->getSimpleValueType(0);
23011 unsigned NumElems = VT.getVectorNumElements();
23012 SmallVector<int, 8> ShuffleMask(NumElems, -1);
23013 for (unsigned i = 0; i < NumElems; ++i) {
23014 // Be sure we emit undef where we can.
23015 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
23016 ShuffleMask[i] = -1;
23018 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
23021 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23022 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
23024 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
23027 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
23029 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
23030 TargetLowering::DAGCombinerInfo &DCI,
23031 const X86Subtarget *Subtarget) {
23033 SDValue Cond = N->getOperand(0);
23034 // Get the LHS/RHS of the select.
23035 SDValue LHS = N->getOperand(1);
23036 SDValue RHS = N->getOperand(2);
23037 EVT VT = LHS.getValueType();
23038 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23040 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
23041 // instructions match the semantics of the common C idiom x<y?x:y but not
23042 // x<=y?x:y, because of how they handle negative zero (which can be
23043 // ignored in unsafe-math mode).
23044 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
23045 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
23046 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
23047 (Subtarget->hasSSE2() ||
23048 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
23049 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23051 unsigned Opcode = 0;
23052 // Check for x CC y ? x : y.
23053 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23054 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23058 // Converting this to a min would handle NaNs incorrectly, and swapping
23059 // the operands would cause it to handle comparisons between positive
23060 // and negative zero incorrectly.
23061 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23062 if (!DAG.getTarget().Options.UnsafeFPMath &&
23063 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23065 std::swap(LHS, RHS);
23067 Opcode = X86ISD::FMIN;
23070 // Converting this to a min would handle comparisons between positive
23071 // and negative zero incorrectly.
23072 if (!DAG.getTarget().Options.UnsafeFPMath &&
23073 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23075 Opcode = X86ISD::FMIN;
23078 // Converting this to a min would handle both negative zeros and NaNs
23079 // incorrectly, but we can swap the operands to fix both.
23080 std::swap(LHS, RHS);
23084 Opcode = X86ISD::FMIN;
23088 // Converting this to a max would handle comparisons between positive
23089 // and negative zero incorrectly.
23090 if (!DAG.getTarget().Options.UnsafeFPMath &&
23091 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23093 Opcode = X86ISD::FMAX;
23096 // Converting this to a max would handle NaNs incorrectly, and swapping
23097 // the operands would cause it to handle comparisons between positive
23098 // and negative zero incorrectly.
23099 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23100 if (!DAG.getTarget().Options.UnsafeFPMath &&
23101 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23103 std::swap(LHS, RHS);
23105 Opcode = X86ISD::FMAX;
23108 // Converting this to a max would handle both negative zeros and NaNs
23109 // incorrectly, but we can swap the operands to fix both.
23110 std::swap(LHS, RHS);
23114 Opcode = X86ISD::FMAX;
23117 // Check for x CC y ? y : x -- a min/max with reversed arms.
23118 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23119 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23123 // Converting this to a min would handle comparisons between positive
23124 // and negative zero incorrectly, and swapping the operands would
23125 // cause it to handle NaNs incorrectly.
23126 if (!DAG.getTarget().Options.UnsafeFPMath &&
23127 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23128 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23130 std::swap(LHS, RHS);
23132 Opcode = X86ISD::FMIN;
23135 // Converting this to a min would handle NaNs incorrectly.
23136 if (!DAG.getTarget().Options.UnsafeFPMath &&
23137 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23139 Opcode = X86ISD::FMIN;
23142 // Converting this to a min would handle both negative zeros and NaNs
23143 // incorrectly, but we can swap the operands to fix both.
23144 std::swap(LHS, RHS);
23148 Opcode = X86ISD::FMIN;
23152 // Converting this to a max would handle NaNs incorrectly.
23153 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23155 Opcode = X86ISD::FMAX;
23158 // Converting this to a max would handle comparisons between positive
23159 // and negative zero incorrectly, and swapping the operands would
23160 // cause it to handle NaNs incorrectly.
23161 if (!DAG.getTarget().Options.UnsafeFPMath &&
23162 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23163 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23165 std::swap(LHS, RHS);
23167 Opcode = X86ISD::FMAX;
23170 // Converting this to a max would handle both negative zeros and NaNs
23171 // incorrectly, but we can swap the operands to fix both.
23172 std::swap(LHS, RHS);
23176 Opcode = X86ISD::FMAX;
23182 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23185 EVT CondVT = Cond.getValueType();
23186 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23187 CondVT.getVectorElementType() == MVT::i1) {
23188 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23189 // lowering on KNL. In this case we convert it to
23190 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
23191 // The same situation for all 128 and 256-bit vectors of i8 and i16.
23192 // Since SKX these selects have a proper lowering.
23193 EVT OpVT = LHS.getValueType();
23194 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
23195 (OpVT.getVectorElementType() == MVT::i8 ||
23196 OpVT.getVectorElementType() == MVT::i16) &&
23197 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
23198 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
23199 DCI.AddToWorklist(Cond.getNode());
23200 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
23203 // If this is a select between two integer constants, try to do some
23205 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
23206 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
23207 // Don't do this for crazy integer types.
23208 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
23209 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
23210 // so that TrueC (the true value) is larger than FalseC.
23211 bool NeedsCondInvert = false;
23213 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
23214 // Efficiently invertible.
23215 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
23216 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
23217 isa<ConstantSDNode>(Cond.getOperand(1))))) {
23218 NeedsCondInvert = true;
23219 std::swap(TrueC, FalseC);
23222 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
23223 if (FalseC->getAPIntValue() == 0 &&
23224 TrueC->getAPIntValue().isPowerOf2()) {
23225 if (NeedsCondInvert) // Invert the condition if needed.
23226 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23227 DAG.getConstant(1, DL, Cond.getValueType()));
23229 // Zero extend the condition if needed.
23230 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
23232 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23233 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
23234 DAG.getConstant(ShAmt, DL, MVT::i8));
23237 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
23238 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23239 if (NeedsCondInvert) // Invert the condition if needed.
23240 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23241 DAG.getConstant(1, DL, Cond.getValueType()));
23243 // Zero extend the condition if needed.
23244 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23245 FalseC->getValueType(0), Cond);
23246 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23247 SDValue(FalseC, 0));
23250 // Optimize cases that will turn into an LEA instruction. This requires
23251 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23252 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23253 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23254 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23256 bool isFastMultiplier = false;
23258 switch ((unsigned char)Diff) {
23260 case 1: // result = add base, cond
23261 case 2: // result = lea base( , cond*2)
23262 case 3: // result = lea base(cond, cond*2)
23263 case 4: // result = lea base( , cond*4)
23264 case 5: // result = lea base(cond, cond*4)
23265 case 8: // result = lea base( , cond*8)
23266 case 9: // result = lea base(cond, cond*8)
23267 isFastMultiplier = true;
23272 if (isFastMultiplier) {
23273 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23274 if (NeedsCondInvert) // Invert the condition if needed.
23275 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
23276 DAG.getConstant(1, DL, Cond.getValueType()));
23278 // Zero extend the condition if needed.
23279 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23281 // Scale the condition by the difference.
23283 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23284 DAG.getConstant(Diff, DL,
23285 Cond.getValueType()));
23287 // Add the base if non-zero.
23288 if (FalseC->getAPIntValue() != 0)
23289 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23290 SDValue(FalseC, 0));
23297 // Canonicalize max and min:
23298 // (x > y) ? x : y -> (x >= y) ? x : y
23299 // (x < y) ? x : y -> (x <= y) ? x : y
23300 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
23301 // the need for an extra compare
23302 // against zero. e.g.
23303 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
23305 // testl %edi, %edi
23307 // cmovgl %edi, %eax
23311 // cmovsl %eax, %edi
23312 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
23313 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23314 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23315 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23320 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
23321 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
23322 Cond.getOperand(0), Cond.getOperand(1), NewCC);
23323 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
23328 // Early exit check
23329 if (!TLI.isTypeLegal(VT))
23332 // Match VSELECTs into subs with unsigned saturation.
23333 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
23334 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
23335 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
23336 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
23337 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23339 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
23340 // left side invert the predicate to simplify logic below.
23342 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
23344 CC = ISD::getSetCCInverse(CC, true);
23345 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
23349 if (Other.getNode() && Other->getNumOperands() == 2 &&
23350 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
23351 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
23352 SDValue CondRHS = Cond->getOperand(1);
23354 // Look for a general sub with unsigned saturation first.
23355 // x >= y ? x-y : 0 --> subus x, y
23356 // x > y ? x-y : 0 --> subus x, y
23357 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
23358 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
23359 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
23361 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
23362 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
23363 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
23364 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
23365 // If the RHS is a constant we have to reverse the const
23366 // canonicalization.
23367 // x > C-1 ? x+-C : 0 --> subus x, C
23368 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
23369 CondRHSConst->getAPIntValue() ==
23370 (-OpRHSConst->getAPIntValue() - 1))
23371 return DAG.getNode(
23372 X86ISD::SUBUS, DL, VT, OpLHS,
23373 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
23375 // Another special case: If C was a sign bit, the sub has been
23376 // canonicalized into a xor.
23377 // FIXME: Would it be better to use computeKnownBits to determine
23378 // whether it's safe to decanonicalize the xor?
23379 // x s< 0 ? x^C : 0 --> subus x, C
23380 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
23381 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
23382 OpRHSConst->getAPIntValue().isSignBit())
23383 // Note that we have to rebuild the RHS constant here to ensure we
23384 // don't rely on particular values of undef lanes.
23385 return DAG.getNode(
23386 X86ISD::SUBUS, DL, VT, OpLHS,
23387 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23392 // Simplify vector selection if condition value type matches vselect
23394 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23395 assert(Cond.getValueType().isVector() &&
23396 "vector select expects a vector selector!");
23398 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23399 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23401 // Try invert the condition if true value is not all 1s and false value
23403 if (!TValIsAllOnes && !FValIsAllZeros &&
23404 // Check if the selector will be produced by CMPP*/PCMP*
23405 Cond.getOpcode() == ISD::SETCC &&
23406 // Check if SETCC has already been promoted
23407 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23409 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23410 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23412 if (TValIsAllZeros || FValIsAllOnes) {
23413 SDValue CC = Cond.getOperand(2);
23414 ISD::CondCode NewCC =
23415 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23416 Cond.getOperand(0).getValueType().isInteger());
23417 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23418 std::swap(LHS, RHS);
23419 TValIsAllOnes = FValIsAllOnes;
23420 FValIsAllZeros = TValIsAllZeros;
23424 if (TValIsAllOnes || FValIsAllZeros) {
23427 if (TValIsAllOnes && FValIsAllZeros)
23429 else if (TValIsAllOnes)
23431 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23432 else if (FValIsAllZeros)
23433 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23434 DAG.getBitcast(CondVT, LHS));
23436 return DAG.getBitcast(VT, Ret);
23440 // We should generate an X86ISD::BLENDI from a vselect if its argument
23441 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23442 // constants. This specific pattern gets generated when we split a
23443 // selector for a 512 bit vector in a machine without AVX512 (but with
23444 // 256-bit vectors), during legalization:
23446 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23448 // Iff we find this pattern and the build_vectors are built from
23449 // constants, we translate the vselect into a shuffle_vector that we
23450 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23451 if ((N->getOpcode() == ISD::VSELECT ||
23452 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23453 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23454 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23455 if (Shuffle.getNode())
23459 // If this is a *dynamic* select (non-constant condition) and we can match
23460 // this node with one of the variable blend instructions, restructure the
23461 // condition so that the blends can use the high bit of each element and use
23462 // SimplifyDemandedBits to simplify the condition operand.
23463 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23464 !DCI.isBeforeLegalize() &&
23465 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23466 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23468 // Don't optimize vector selects that map to mask-registers.
23472 // We can only handle the cases where VSELECT is directly legal on the
23473 // subtarget. We custom lower VSELECT nodes with constant conditions and
23474 // this makes it hard to see whether a dynamic VSELECT will correctly
23475 // lower, so we both check the operation's status and explicitly handle the
23476 // cases where a *dynamic* blend will fail even though a constant-condition
23477 // blend could be custom lowered.
23478 // FIXME: We should find a better way to handle this class of problems.
23479 // Potentially, we should combine constant-condition vselect nodes
23480 // pre-legalization into shuffles and not mark as many types as custom
23482 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23484 // FIXME: We don't support i16-element blends currently. We could and
23485 // should support them by making *all* the bits in the condition be set
23486 // rather than just the high bit and using an i8-element blend.
23487 if (VT.getScalarType() == MVT::i16)
23489 // Dynamic blending was only available from SSE4.1 onward.
23490 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23492 // Byte blends are only available in AVX2
23493 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23494 !Subtarget->hasAVX2())
23497 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23498 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23500 APInt KnownZero, KnownOne;
23501 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23502 DCI.isBeforeLegalizeOps());
23503 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23504 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23506 // If we changed the computation somewhere in the DAG, this change
23507 // will affect all users of Cond.
23508 // Make sure it is fine and update all the nodes so that we do not
23509 // use the generic VSELECT anymore. Otherwise, we may perform
23510 // wrong optimizations as we messed up with the actual expectation
23511 // for the vector boolean values.
23512 if (Cond != TLO.Old) {
23513 // Check all uses of that condition operand to check whether it will be
23514 // consumed by non-BLEND instructions, which may depend on all bits are
23516 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23518 if (I->getOpcode() != ISD::VSELECT)
23519 // TODO: Add other opcodes eventually lowered into BLEND.
23522 // Update all the users of the condition, before committing the change,
23523 // so that the VSELECT optimizations that expect the correct vector
23524 // boolean value will not be triggered.
23525 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23527 DAG.ReplaceAllUsesOfValueWith(
23529 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23530 Cond, I->getOperand(1), I->getOperand(2)));
23531 DCI.CommitTargetLoweringOpt(TLO);
23534 // At this point, only Cond is changed. Change the condition
23535 // just for N to keep the opportunity to optimize all other
23536 // users their own way.
23537 DAG.ReplaceAllUsesOfValueWith(
23539 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23540 TLO.New, N->getOperand(1), N->getOperand(2)));
23548 // Check whether a boolean test is testing a boolean value generated by
23549 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23552 // Simplify the following patterns:
23553 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23554 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23555 // to (Op EFLAGS Cond)
23557 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23558 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23559 // to (Op EFLAGS !Cond)
23561 // where Op could be BRCOND or CMOV.
23563 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23564 // Quit if not CMP and SUB with its value result used.
23565 if (Cmp.getOpcode() != X86ISD::CMP &&
23566 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23569 // Quit if not used as a boolean value.
23570 if (CC != X86::COND_E && CC != X86::COND_NE)
23573 // Check CMP operands. One of them should be 0 or 1 and the other should be
23574 // an SetCC or extended from it.
23575 SDValue Op1 = Cmp.getOperand(0);
23576 SDValue Op2 = Cmp.getOperand(1);
23579 const ConstantSDNode* C = nullptr;
23580 bool needOppositeCond = (CC == X86::COND_E);
23581 bool checkAgainstTrue = false; // Is it a comparison against 1?
23583 if ((C = dyn_cast<ConstantSDNode>(Op1)))
23585 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23587 else // Quit if all operands are not constants.
23590 if (C->getZExtValue() == 1) {
23591 needOppositeCond = !needOppositeCond;
23592 checkAgainstTrue = true;
23593 } else if (C->getZExtValue() != 0)
23594 // Quit if the constant is neither 0 or 1.
23597 bool truncatedToBoolWithAnd = false;
23598 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23599 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23600 SetCC.getOpcode() == ISD::TRUNCATE ||
23601 SetCC.getOpcode() == ISD::AND) {
23602 if (SetCC.getOpcode() == ISD::AND) {
23604 ConstantSDNode *CS;
23605 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23606 CS->getZExtValue() == 1)
23608 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23609 CS->getZExtValue() == 1)
23613 SetCC = SetCC.getOperand(OpIdx);
23614 truncatedToBoolWithAnd = true;
23616 SetCC = SetCC.getOperand(0);
23619 switch (SetCC.getOpcode()) {
23620 case X86ISD::SETCC_CARRY:
23621 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23622 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23623 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23624 // truncated to i1 using 'and'.
23625 if (checkAgainstTrue && !truncatedToBoolWithAnd)
23627 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23628 "Invalid use of SETCC_CARRY!");
23630 case X86ISD::SETCC:
23631 // Set the condition code or opposite one if necessary.
23632 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23633 if (needOppositeCond)
23634 CC = X86::GetOppositeBranchCondition(CC);
23635 return SetCC.getOperand(1);
23636 case X86ISD::CMOV: {
23637 // Check whether false/true value has canonical one, i.e. 0 or 1.
23638 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23639 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23640 // Quit if true value is not a constant.
23643 // Quit if false value is not a constant.
23645 SDValue Op = SetCC.getOperand(0);
23646 // Skip 'zext' or 'trunc' node.
23647 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23648 Op.getOpcode() == ISD::TRUNCATE)
23649 Op = Op.getOperand(0);
23650 // A special case for rdrand/rdseed, where 0 is set if false cond is
23652 if ((Op.getOpcode() != X86ISD::RDRAND &&
23653 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23656 // Quit if false value is not the constant 0 or 1.
23657 bool FValIsFalse = true;
23658 if (FVal && FVal->getZExtValue() != 0) {
23659 if (FVal->getZExtValue() != 1)
23661 // If FVal is 1, opposite cond is needed.
23662 needOppositeCond = !needOppositeCond;
23663 FValIsFalse = false;
23665 // Quit if TVal is not the constant opposite of FVal.
23666 if (FValIsFalse && TVal->getZExtValue() != 1)
23668 if (!FValIsFalse && TVal->getZExtValue() != 0)
23670 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23671 if (needOppositeCond)
23672 CC = X86::GetOppositeBranchCondition(CC);
23673 return SetCC.getOperand(3);
23680 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23682 /// (X86or (X86setcc) (X86setcc))
23683 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
23684 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23685 X86::CondCode &CC1, SDValue &Flags,
23687 if (Cond->getOpcode() == X86ISD::CMP) {
23688 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23689 if (!CondOp1C || !CondOp1C->isNullValue())
23692 Cond = Cond->getOperand(0);
23697 SDValue SetCC0, SetCC1;
23698 switch (Cond->getOpcode()) {
23699 default: return false;
23706 SetCC0 = Cond->getOperand(0);
23707 SetCC1 = Cond->getOperand(1);
23711 // Make sure we have SETCC nodes, using the same flags value.
23712 if (SetCC0.getOpcode() != X86ISD::SETCC ||
23713 SetCC1.getOpcode() != X86ISD::SETCC ||
23714 SetCC0->getOperand(1) != SetCC1->getOperand(1))
23717 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23718 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23719 Flags = SetCC0->getOperand(1);
23723 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23724 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23725 TargetLowering::DAGCombinerInfo &DCI,
23726 const X86Subtarget *Subtarget) {
23729 // If the flag operand isn't dead, don't touch this CMOV.
23730 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23733 SDValue FalseOp = N->getOperand(0);
23734 SDValue TrueOp = N->getOperand(1);
23735 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23736 SDValue Cond = N->getOperand(3);
23738 if (CC == X86::COND_E || CC == X86::COND_NE) {
23739 switch (Cond.getOpcode()) {
23743 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23744 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23745 return (CC == X86::COND_E) ? FalseOp : TrueOp;
23751 Flags = checkBoolTestSetCCCombine(Cond, CC);
23752 if (Flags.getNode() &&
23753 // Extra check as FCMOV only supports a subset of X86 cond.
23754 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23755 SDValue Ops[] = { FalseOp, TrueOp,
23756 DAG.getConstant(CC, DL, MVT::i8), Flags };
23757 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23760 // If this is a select between two integer constants, try to do some
23761 // optimizations. Note that the operands are ordered the opposite of SELECT
23763 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23764 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23765 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23766 // larger than FalseC (the false value).
23767 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23768 CC = X86::GetOppositeBranchCondition(CC);
23769 std::swap(TrueC, FalseC);
23770 std::swap(TrueOp, FalseOp);
23773 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
23774 // This is efficient for any integer data type (including i8/i16) and
23776 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23777 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23778 DAG.getConstant(CC, DL, MVT::i8), Cond);
23780 // Zero extend the condition if needed.
23781 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23783 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23784 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23785 DAG.getConstant(ShAmt, DL, MVT::i8));
23786 if (N->getNumValues() == 2) // Dead flag value?
23787 return DCI.CombineTo(N, Cond, SDValue());
23791 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
23792 // for any integer data type, including i8/i16.
23793 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23794 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23795 DAG.getConstant(CC, DL, MVT::i8), Cond);
23797 // Zero extend the condition if needed.
23798 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23799 FalseC->getValueType(0), Cond);
23800 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23801 SDValue(FalseC, 0));
23803 if (N->getNumValues() == 2) // Dead flag value?
23804 return DCI.CombineTo(N, Cond, SDValue());
23808 // Optimize cases that will turn into an LEA instruction. This requires
23809 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23810 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23811 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23812 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23814 bool isFastMultiplier = false;
23816 switch ((unsigned char)Diff) {
23818 case 1: // result = add base, cond
23819 case 2: // result = lea base( , cond*2)
23820 case 3: // result = lea base(cond, cond*2)
23821 case 4: // result = lea base( , cond*4)
23822 case 5: // result = lea base(cond, cond*4)
23823 case 8: // result = lea base( , cond*8)
23824 case 9: // result = lea base(cond, cond*8)
23825 isFastMultiplier = true;
23830 if (isFastMultiplier) {
23831 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23832 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23833 DAG.getConstant(CC, DL, MVT::i8), Cond);
23834 // Zero extend the condition if needed.
23835 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23837 // Scale the condition by the difference.
23839 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23840 DAG.getConstant(Diff, DL, Cond.getValueType()));
23842 // Add the base if non-zero.
23843 if (FalseC->getAPIntValue() != 0)
23844 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23845 SDValue(FalseC, 0));
23846 if (N->getNumValues() == 2) // Dead flag value?
23847 return DCI.CombineTo(N, Cond, SDValue());
23854 // Handle these cases:
23855 // (select (x != c), e, c) -> select (x != c), e, x),
23856 // (select (x == c), c, e) -> select (x == c), x, e)
23857 // where the c is an integer constant, and the "select" is the combination
23858 // of CMOV and CMP.
23860 // The rationale for this change is that the conditional-move from a constant
23861 // needs two instructions, however, conditional-move from a register needs
23862 // only one instruction.
23864 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23865 // some instruction-combining opportunities. This opt needs to be
23866 // postponed as late as possible.
23868 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23869 // the DCI.xxxx conditions are provided to postpone the optimization as
23870 // late as possible.
23872 ConstantSDNode *CmpAgainst = nullptr;
23873 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23874 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23875 !isa<ConstantSDNode>(Cond.getOperand(0))) {
23877 if (CC == X86::COND_NE &&
23878 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23879 CC = X86::GetOppositeBranchCondition(CC);
23880 std::swap(TrueOp, FalseOp);
23883 if (CC == X86::COND_E &&
23884 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23885 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23886 DAG.getConstant(CC, DL, MVT::i8), Cond };
23887 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23892 // Fold and/or of setcc's to double CMOV:
23893 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23894 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23896 // This combine lets us generate:
23897 // cmovcc1 (jcc1 if we don't have CMOV)
23903 // cmovne (jne if we don't have CMOV)
23904 // When we can't use the CMOV instruction, it might increase branch
23906 // When we can use CMOV, or when there is no mispredict, this improves
23907 // throughput and reduces register pressure.
23909 if (CC == X86::COND_NE) {
23911 X86::CondCode CC0, CC1;
23913 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23915 std::swap(FalseOp, TrueOp);
23916 CC0 = X86::GetOppositeBranchCondition(CC0);
23917 CC1 = X86::GetOppositeBranchCondition(CC1);
23920 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23922 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23923 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23924 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23925 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23933 /// PerformMulCombine - Optimize a single multiply with constant into two
23934 /// in order to implement it with two cheaper instructions, e.g.
23935 /// LEA + SHL, LEA + LEA.
23936 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23937 TargetLowering::DAGCombinerInfo &DCI) {
23938 // An imul is usually smaller than the alternative sequence.
23939 if (DAG.getMachineFunction().getFunction()->optForMinSize())
23942 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23945 EVT VT = N->getValueType(0);
23946 if (VT != MVT::i64 && VT != MVT::i32)
23949 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23952 uint64_t MulAmt = C->getZExtValue();
23953 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23956 uint64_t MulAmt1 = 0;
23957 uint64_t MulAmt2 = 0;
23958 if ((MulAmt % 9) == 0) {
23960 MulAmt2 = MulAmt / 9;
23961 } else if ((MulAmt % 5) == 0) {
23963 MulAmt2 = MulAmt / 5;
23964 } else if ((MulAmt % 3) == 0) {
23966 MulAmt2 = MulAmt / 3;
23969 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23972 if (isPowerOf2_64(MulAmt2) &&
23973 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23974 // If second multiplifer is pow2, issue it first. We want the multiply by
23975 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23977 std::swap(MulAmt1, MulAmt2);
23980 if (isPowerOf2_64(MulAmt1))
23981 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23982 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23984 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23985 DAG.getConstant(MulAmt1, DL, VT));
23987 if (isPowerOf2_64(MulAmt2))
23988 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23989 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23991 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23992 DAG.getConstant(MulAmt2, DL, VT));
23994 // Do not add new nodes to DAG combiner worklist.
23995 DCI.CombineTo(N, NewMul, false);
24000 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
24001 SDValue N0 = N->getOperand(0);
24002 SDValue N1 = N->getOperand(1);
24003 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
24004 EVT VT = N0.getValueType();
24006 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
24007 // since the result of setcc_c is all zero's or all ones.
24008 if (VT.isInteger() && !VT.isVector() &&
24009 N1C && N0.getOpcode() == ISD::AND &&
24010 N0.getOperand(1).getOpcode() == ISD::Constant) {
24011 SDValue N00 = N0.getOperand(0);
24012 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
24013 APInt ShAmt = N1C->getAPIntValue();
24014 Mask = Mask.shl(ShAmt);
24015 bool MaskOK = false;
24016 // We can handle cases concerning bit-widening nodes containing setcc_c if
24017 // we carefully interrogate the mask to make sure we are semantics
24019 // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
24020 // of the underlying setcc_c operation if the setcc_c was zero extended.
24021 // Consider the following example:
24022 // zext(setcc_c) -> i32 0x0000FFFF
24023 // c1 -> i32 0x0000FFFF
24024 // c2 -> i32 0x00000001
24025 // (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
24026 // (and setcc_c, (c1 << c2)) -> i32 0x0000FFFE
24027 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24029 } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
24030 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24032 } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
24033 N00.getOpcode() == ISD::ANY_EXTEND) &&
24034 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24035 MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
24037 if (MaskOK && Mask != 0) {
24039 return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
24043 // Hardware support for vector shifts is sparse which makes us scalarize the
24044 // vector operations in many cases. Also, on sandybridge ADD is faster than
24046 // (shl V, 1) -> add V,V
24047 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24048 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24049 assert(N0.getValueType().isVector() && "Invalid vector shift type");
24050 // We shift all of the values by one. In many cases we do not have
24051 // hardware support for this operation. This is better expressed as an ADD
24053 if (N1SplatC->getAPIntValue() == 1)
24054 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24060 /// \brief Returns a vector of 0s if the node in input is a vector logical
24061 /// shift by a constant amount which is known to be bigger than or equal
24062 /// to the vector element size in bits.
24063 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24064 const X86Subtarget *Subtarget) {
24065 EVT VT = N->getValueType(0);
24067 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24068 (!Subtarget->hasInt256() ||
24069 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24072 SDValue Amt = N->getOperand(1);
24074 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24075 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24076 APInt ShiftAmt = AmtSplat->getAPIntValue();
24077 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
24079 // SSE2/AVX2 logical shifts always return a vector of 0s
24080 // if the shift amount is bigger than or equal to
24081 // the element size. The constant shift amount will be
24082 // encoded as a 8-bit immediate.
24083 if (ShiftAmt.trunc(8).uge(MaxAmount))
24084 return getZeroVector(VT, Subtarget, DAG, DL);
24090 /// PerformShiftCombine - Combine shifts.
24091 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24092 TargetLowering::DAGCombinerInfo &DCI,
24093 const X86Subtarget *Subtarget) {
24094 if (N->getOpcode() == ISD::SHL)
24095 if (SDValue V = PerformSHLCombine(N, DAG))
24098 // Try to fold this logical shift into a zero vector.
24099 if (N->getOpcode() != ISD::SRA)
24100 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
24106 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
24107 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24108 // and friends. Likewise for OR -> CMPNEQSS.
24109 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24110 TargetLowering::DAGCombinerInfo &DCI,
24111 const X86Subtarget *Subtarget) {
24114 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24115 // we're requiring SSE2 for both.
24116 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24117 SDValue N0 = N->getOperand(0);
24118 SDValue N1 = N->getOperand(1);
24119 SDValue CMP0 = N0->getOperand(1);
24120 SDValue CMP1 = N1->getOperand(1);
24123 // The SETCCs should both refer to the same CMP.
24124 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24127 SDValue CMP00 = CMP0->getOperand(0);
24128 SDValue CMP01 = CMP0->getOperand(1);
24129 EVT VT = CMP00.getValueType();
24131 if (VT == MVT::f32 || VT == MVT::f64) {
24132 bool ExpectingFlags = false;
24133 // Check for any users that want flags:
24134 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24135 !ExpectingFlags && UI != UE; ++UI)
24136 switch (UI->getOpcode()) {
24141 ExpectingFlags = true;
24143 case ISD::CopyToReg:
24144 case ISD::SIGN_EXTEND:
24145 case ISD::ZERO_EXTEND:
24146 case ISD::ANY_EXTEND:
24150 if (!ExpectingFlags) {
24151 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24152 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24154 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24155 X86::CondCode tmp = cc0;
24160 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
24161 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24162 // FIXME: need symbolic constants for these magic numbers.
24163 // See X86ATTInstPrinter.cpp:printSSECC().
24164 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24165 if (Subtarget->hasAVX512()) {
24166 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24168 DAG.getConstant(x86cc, DL, MVT::i8));
24169 if (N->getValueType(0) != MVT::i1)
24170 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
24174 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
24175 CMP00.getValueType(), CMP00, CMP01,
24176 DAG.getConstant(x86cc, DL,
24179 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
24180 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
24182 if (is64BitFP && !Subtarget->is64Bit()) {
24183 // On a 32-bit target, we cannot bitcast the 64-bit float to a
24184 // 64-bit integer, since that's not a legal type. Since
24185 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
24186 // bits, but can do this little dance to extract the lowest 32 bits
24187 // and work with those going forward.
24188 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
24190 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
24191 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
24192 Vector32, DAG.getIntPtrConstant(0, DL));
24196 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
24197 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
24198 DAG.getConstant(1, DL, IntVT));
24199 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
24201 return OneBitOfTruth;
24209 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
24210 /// so it can be folded inside ANDNP.
24211 static bool CanFoldXORWithAllOnes(const SDNode *N) {
24212 EVT VT = N->getValueType(0);
24214 // Match direct AllOnes for 128 and 256-bit vectors
24215 if (ISD::isBuildVectorAllOnes(N))
24218 // Look through a bit convert.
24219 if (N->getOpcode() == ISD::BITCAST)
24220 N = N->getOperand(0).getNode();
24222 // Sometimes the operand may come from a insert_subvector building a 256-bit
24224 if (VT.is256BitVector() &&
24225 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
24226 SDValue V1 = N->getOperand(0);
24227 SDValue V2 = N->getOperand(1);
24229 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
24230 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
24231 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
24232 ISD::isBuildVectorAllOnes(V2.getNode()))
24239 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
24240 // register. In most cases we actually compare or select YMM-sized registers
24241 // and mixing the two types creates horrible code. This method optimizes
24242 // some of the transition sequences.
24243 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
24244 TargetLowering::DAGCombinerInfo &DCI,
24245 const X86Subtarget *Subtarget) {
24246 EVT VT = N->getValueType(0);
24247 if (!VT.is256BitVector())
24250 assert((N->getOpcode() == ISD::ANY_EXTEND ||
24251 N->getOpcode() == ISD::ZERO_EXTEND ||
24252 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
24254 SDValue Narrow = N->getOperand(0);
24255 EVT NarrowVT = Narrow->getValueType(0);
24256 if (!NarrowVT.is128BitVector())
24259 if (Narrow->getOpcode() != ISD::XOR &&
24260 Narrow->getOpcode() != ISD::AND &&
24261 Narrow->getOpcode() != ISD::OR)
24264 SDValue N0 = Narrow->getOperand(0);
24265 SDValue N1 = Narrow->getOperand(1);
24268 // The Left side has to be a trunc.
24269 if (N0.getOpcode() != ISD::TRUNCATE)
24272 // The type of the truncated inputs.
24273 EVT WideVT = N0->getOperand(0)->getValueType(0);
24277 // The right side has to be a 'trunc' or a constant vector.
24278 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
24279 ConstantSDNode *RHSConstSplat = nullptr;
24280 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
24281 RHSConstSplat = RHSBV->getConstantSplatNode();
24282 if (!RHSTrunc && !RHSConstSplat)
24285 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24287 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
24290 // Set N0 and N1 to hold the inputs to the new wide operation.
24291 N0 = N0->getOperand(0);
24292 if (RHSConstSplat) {
24293 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
24294 SDValue(RHSConstSplat, 0));
24295 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
24296 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
24297 } else if (RHSTrunc) {
24298 N1 = N1->getOperand(0);
24301 // Generate the wide operation.
24302 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
24303 unsigned Opcode = N->getOpcode();
24305 case ISD::ANY_EXTEND:
24307 case ISD::ZERO_EXTEND: {
24308 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
24309 APInt Mask = APInt::getAllOnesValue(InBits);
24310 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
24311 return DAG.getNode(ISD::AND, DL, VT,
24312 Op, DAG.getConstant(Mask, DL, VT));
24314 case ISD::SIGN_EXTEND:
24315 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
24316 Op, DAG.getValueType(NarrowVT));
24318 llvm_unreachable("Unexpected opcode");
24322 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
24323 TargetLowering::DAGCombinerInfo &DCI,
24324 const X86Subtarget *Subtarget) {
24325 SDValue N0 = N->getOperand(0);
24326 SDValue N1 = N->getOperand(1);
24329 // A vector zext_in_reg may be represented as a shuffle,
24330 // feeding into a bitcast (this represents anyext) feeding into
24331 // an and with a mask.
24332 // We'd like to try to combine that into a shuffle with zero
24333 // plus a bitcast, removing the and.
24334 if (N0.getOpcode() != ISD::BITCAST ||
24335 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
24338 // The other side of the AND should be a splat of 2^C, where C
24339 // is the number of bits in the source type.
24340 if (N1.getOpcode() == ISD::BITCAST)
24341 N1 = N1.getOperand(0);
24342 if (N1.getOpcode() != ISD::BUILD_VECTOR)
24344 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
24346 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
24347 EVT SrcType = Shuffle->getValueType(0);
24349 // We expect a single-source shuffle
24350 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
24353 unsigned SrcSize = SrcType.getScalarSizeInBits();
24355 APInt SplatValue, SplatUndef;
24356 unsigned SplatBitSize;
24358 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
24359 SplatBitSize, HasAnyUndefs))
24362 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
24363 // Make sure the splat matches the mask we expect
24364 if (SplatBitSize > ResSize ||
24365 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
24368 // Make sure the input and output size make sense
24369 if (SrcSize >= ResSize || ResSize % SrcSize)
24372 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
24373 // The number of u's between each two values depends on the ratio between
24374 // the source and dest type.
24375 unsigned ZextRatio = ResSize / SrcSize;
24376 bool IsZext = true;
24377 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
24378 if (i % ZextRatio) {
24379 if (Shuffle->getMaskElt(i) > 0) {
24385 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24386 // Expected element number
24396 // Ok, perform the transformation - replace the shuffle with
24397 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24398 // (instead of undef) where the k elements come from the zero vector.
24399 SmallVector<int, 8> Mask;
24400 unsigned NumElems = SrcType.getVectorNumElements();
24401 for (unsigned i = 0; i < NumElems; ++i)
24403 Mask.push_back(NumElems);
24405 Mask.push_back(i / ZextRatio);
24407 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24408 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24409 return DAG.getBitcast(N0.getValueType(), NewShuffle);
24412 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24413 TargetLowering::DAGCombinerInfo &DCI,
24414 const X86Subtarget *Subtarget) {
24415 if (DCI.isBeforeLegalizeOps())
24418 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24421 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24424 EVT VT = N->getValueType(0);
24425 SDValue N0 = N->getOperand(0);
24426 SDValue N1 = N->getOperand(1);
24429 // Create BEXTR instructions
24430 // BEXTR is ((X >> imm) & (2**size-1))
24431 if (VT == MVT::i32 || VT == MVT::i64) {
24432 // Check for BEXTR.
24433 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24434 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24435 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24436 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24437 if (MaskNode && ShiftNode) {
24438 uint64_t Mask = MaskNode->getZExtValue();
24439 uint64_t Shift = ShiftNode->getZExtValue();
24440 if (isMask_64(Mask)) {
24441 uint64_t MaskSize = countPopulation(Mask);
24442 if (Shift + MaskSize <= VT.getSizeInBits())
24443 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24444 DAG.getConstant(Shift | (MaskSize << 8), DL,
24453 // Want to form ANDNP nodes:
24454 // 1) In the hopes of then easily combining them with OR and AND nodes
24455 // to form PBLEND/PSIGN.
24456 // 2) To match ANDN packed intrinsics
24457 if (VT != MVT::v2i64 && VT != MVT::v4i64)
24460 // Check LHS for vnot
24461 if (N0.getOpcode() == ISD::XOR &&
24462 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24463 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24464 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24466 // Check RHS for vnot
24467 if (N1.getOpcode() == ISD::XOR &&
24468 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24469 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24470 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24475 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24476 TargetLowering::DAGCombinerInfo &DCI,
24477 const X86Subtarget *Subtarget) {
24478 if (DCI.isBeforeLegalizeOps())
24481 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24484 SDValue N0 = N->getOperand(0);
24485 SDValue N1 = N->getOperand(1);
24486 EVT VT = N->getValueType(0);
24488 // look for psign/blend
24489 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24490 if (!Subtarget->hasSSSE3() ||
24491 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24494 // Canonicalize pandn to RHS
24495 if (N0.getOpcode() == X86ISD::ANDNP)
24497 // or (and (m, y), (pandn m, x))
24498 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24499 SDValue Mask = N1.getOperand(0);
24500 SDValue X = N1.getOperand(1);
24502 if (N0.getOperand(0) == Mask)
24503 Y = N0.getOperand(1);
24504 if (N0.getOperand(1) == Mask)
24505 Y = N0.getOperand(0);
24507 // Check to see if the mask appeared in both the AND and ANDNP and
24511 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24512 // Look through mask bitcast.
24513 if (Mask.getOpcode() == ISD::BITCAST)
24514 Mask = Mask.getOperand(0);
24515 if (X.getOpcode() == ISD::BITCAST)
24516 X = X.getOperand(0);
24517 if (Y.getOpcode() == ISD::BITCAST)
24518 Y = Y.getOperand(0);
24520 EVT MaskVT = Mask.getValueType();
24522 // Validate that the Mask operand is a vector sra node.
24523 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24524 // there is no psrai.b
24525 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24526 unsigned SraAmt = ~0;
24527 if (Mask.getOpcode() == ISD::SRA) {
24528 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24529 if (auto *AmtConst = AmtBV->getConstantSplatNode())
24530 SraAmt = AmtConst->getZExtValue();
24531 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24532 SDValue SraC = Mask.getOperand(1);
24533 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
24535 if ((SraAmt + 1) != EltBits)
24540 // Now we know we at least have a plendvb with the mask val. See if
24541 // we can form a psignb/w/d.
24542 // psign = x.type == y.type == mask.type && y = sub(0, x);
24543 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24544 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24545 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24546 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24547 "Unsupported VT for PSIGN");
24548 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24549 return DAG.getBitcast(VT, Mask);
24551 // PBLENDVB only available on SSE 4.1
24552 if (!Subtarget->hasSSE41())
24555 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24557 X = DAG.getBitcast(BlendVT, X);
24558 Y = DAG.getBitcast(BlendVT, Y);
24559 Mask = DAG.getBitcast(BlendVT, Mask);
24560 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24561 return DAG.getBitcast(VT, Mask);
24565 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24568 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24569 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24571 // SHLD/SHRD instructions have lower register pressure, but on some
24572 // platforms they have higher latency than the equivalent
24573 // series of shifts/or that would otherwise be generated.
24574 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24575 // have higher latencies and we are not optimizing for size.
24576 if (!OptForSize && Subtarget->isSHLDSlow())
24579 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24581 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24583 if (!N0.hasOneUse() || !N1.hasOneUse())
24586 SDValue ShAmt0 = N0.getOperand(1);
24587 if (ShAmt0.getValueType() != MVT::i8)
24589 SDValue ShAmt1 = N1.getOperand(1);
24590 if (ShAmt1.getValueType() != MVT::i8)
24592 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24593 ShAmt0 = ShAmt0.getOperand(0);
24594 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24595 ShAmt1 = ShAmt1.getOperand(0);
24598 unsigned Opc = X86ISD::SHLD;
24599 SDValue Op0 = N0.getOperand(0);
24600 SDValue Op1 = N1.getOperand(0);
24601 if (ShAmt0.getOpcode() == ISD::SUB) {
24602 Opc = X86ISD::SHRD;
24603 std::swap(Op0, Op1);
24604 std::swap(ShAmt0, ShAmt1);
24607 unsigned Bits = VT.getSizeInBits();
24608 if (ShAmt1.getOpcode() == ISD::SUB) {
24609 SDValue Sum = ShAmt1.getOperand(0);
24610 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24611 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24612 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24613 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24614 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24615 return DAG.getNode(Opc, DL, VT,
24617 DAG.getNode(ISD::TRUNCATE, DL,
24620 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24621 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24623 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24624 return DAG.getNode(Opc, DL, VT,
24625 N0.getOperand(0), N1.getOperand(0),
24626 DAG.getNode(ISD::TRUNCATE, DL,
24633 // Generate NEG and CMOV for integer abs.
24634 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24635 EVT VT = N->getValueType(0);
24637 // Since X86 does not have CMOV for 8-bit integer, we don't convert
24638 // 8-bit integer abs to NEG and CMOV.
24639 if (VT.isInteger() && VT.getSizeInBits() == 8)
24642 SDValue N0 = N->getOperand(0);
24643 SDValue N1 = N->getOperand(1);
24646 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24647 // and change it to SUB and CMOV.
24648 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24649 N0.getOpcode() == ISD::ADD &&
24650 N0.getOperand(1) == N1 &&
24651 N1.getOpcode() == ISD::SRA &&
24652 N1.getOperand(0) == N0.getOperand(0))
24653 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24654 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24655 // Generate SUB & CMOV.
24656 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24657 DAG.getConstant(0, DL, VT), N0.getOperand(0));
24659 SDValue Ops[] = { N0.getOperand(0), Neg,
24660 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24661 SDValue(Neg.getNode(), 1) };
24662 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24667 // Try to turn tests against the signbit in the form of:
24668 // XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24671 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24672 // This is only worth doing if the output type is i8.
24673 if (N->getValueType(0) != MVT::i8)
24676 SDValue N0 = N->getOperand(0);
24677 SDValue N1 = N->getOperand(1);
24679 // We should be performing an xor against a truncated shift.
24680 if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24683 // Make sure we are performing an xor against one.
24684 if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24687 // SetCC on x86 zero extends so only act on this if it's a logical shift.
24688 SDValue Shift = N0.getOperand(0);
24689 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24692 // Make sure we are truncating from one of i16, i32 or i64.
24693 EVT ShiftTy = Shift.getValueType();
24694 if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24697 // Make sure the shift amount extracts the sign bit.
24698 if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24699 Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24702 // Create a greater-than comparison against -1.
24703 // N.B. Using SETGE against 0 works but we want a canonical looking
24704 // comparison, using SETGT matches up with what TranslateX86CC.
24706 SDValue ShiftOp = Shift.getOperand(0);
24707 EVT ShiftOpTy = ShiftOp.getValueType();
24708 SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24709 DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24713 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24714 TargetLowering::DAGCombinerInfo &DCI,
24715 const X86Subtarget *Subtarget) {
24716 if (DCI.isBeforeLegalizeOps())
24719 if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24722 if (Subtarget->hasCMov())
24723 if (SDValue RV = performIntegerAbsCombine(N, DAG))
24729 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24730 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24731 TargetLowering::DAGCombinerInfo &DCI,
24732 const X86Subtarget *Subtarget) {
24733 LoadSDNode *Ld = cast<LoadSDNode>(N);
24734 EVT RegVT = Ld->getValueType(0);
24735 EVT MemVT = Ld->getMemoryVT();
24737 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24739 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24740 // into two 16-byte operations.
24741 ISD::LoadExtType Ext = Ld->getExtensionType();
24743 unsigned AddressSpace = Ld->getAddressSpace();
24744 unsigned Alignment = Ld->getAlignment();
24745 if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24746 Ext == ISD::NON_EXTLOAD &&
24747 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24748 AddressSpace, Alignment, &Fast) && !Fast) {
24749 unsigned NumElems = RegVT.getVectorNumElements();
24753 SDValue Ptr = Ld->getBasePtr();
24754 SDValue Increment =
24755 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24757 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24759 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24760 Ld->getPointerInfo(), Ld->isVolatile(),
24761 Ld->isNonTemporal(), Ld->isInvariant(),
24763 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24764 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24765 Ld->getPointerInfo(), Ld->isVolatile(),
24766 Ld->isNonTemporal(), Ld->isInvariant(),
24767 std::min(16U, Alignment));
24768 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24770 Load2.getValue(1));
24772 SDValue NewVec = DAG.getUNDEF(RegVT);
24773 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24774 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24775 return DCI.CombineTo(N, NewVec, TF, true);
24781 /// PerformMLOADCombine - Resolve extending loads
24782 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24783 TargetLowering::DAGCombinerInfo &DCI,
24784 const X86Subtarget *Subtarget) {
24785 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24786 if (Mld->getExtensionType() != ISD::SEXTLOAD)
24789 EVT VT = Mld->getValueType(0);
24790 unsigned NumElems = VT.getVectorNumElements();
24791 EVT LdVT = Mld->getMemoryVT();
24794 assert(LdVT != VT && "Cannot extend to the same type");
24795 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24796 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24797 // From, To sizes and ElemCount must be pow of two
24798 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24799 "Unexpected size for extending masked load");
24801 unsigned SizeRatio = ToSz / FromSz;
24802 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24804 // Create a type on which we perform the shuffle
24805 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24806 LdVT.getScalarType(), NumElems*SizeRatio);
24807 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24809 // Convert Src0 value
24810 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24811 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24812 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24813 for (unsigned i = 0; i != NumElems; ++i)
24814 ShuffleVec[i] = i * SizeRatio;
24816 // Can't shuffle using an illegal type.
24817 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24818 && "WideVecVT should be legal");
24819 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24820 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24822 // Prepare the new mask
24824 SDValue Mask = Mld->getMask();
24825 if (Mask.getValueType() == VT) {
24826 // Mask and original value have the same type
24827 NewMask = DAG.getBitcast(WideVecVT, Mask);
24828 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24829 for (unsigned i = 0; i != NumElems; ++i)
24830 ShuffleVec[i] = i * SizeRatio;
24831 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24832 ShuffleVec[i] = NumElems*SizeRatio;
24833 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24834 DAG.getConstant(0, dl, WideVecVT),
24838 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24839 unsigned WidenNumElts = NumElems*SizeRatio;
24840 unsigned MaskNumElts = VT.getVectorNumElements();
24841 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24844 unsigned NumConcat = WidenNumElts / MaskNumElts;
24845 SmallVector<SDValue, 16> Ops(NumConcat);
24846 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24848 for (unsigned i = 1; i != NumConcat; ++i)
24851 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24854 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24855 Mld->getBasePtr(), NewMask, WideSrc0,
24856 Mld->getMemoryVT(), Mld->getMemOperand(),
24858 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24859 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24861 /// PerformMSTORECombine - Resolve truncating stores
24862 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24863 const X86Subtarget *Subtarget) {
24864 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24865 if (!Mst->isTruncatingStore())
24868 EVT VT = Mst->getValue().getValueType();
24869 unsigned NumElems = VT.getVectorNumElements();
24870 EVT StVT = Mst->getMemoryVT();
24873 assert(StVT != VT && "Cannot truncate to the same type");
24874 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24875 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24877 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24879 // The truncating store is legal in some cases. For example
24880 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24881 // are designated for truncate store.
24882 // In this case we don't need any further transformations.
24883 if (TLI.isTruncStoreLegal(VT, StVT))
24886 // From, To sizes and ElemCount must be pow of two
24887 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24888 "Unexpected size for truncating masked store");
24889 // We are going to use the original vector elt for storing.
24890 // Accumulated smaller vector elements must be a multiple of the store size.
24891 assert (((NumElems * FromSz) % ToSz) == 0 &&
24892 "Unexpected ratio for truncating masked store");
24894 unsigned SizeRatio = FromSz / ToSz;
24895 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24897 // Create a type on which we perform the shuffle
24898 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24899 StVT.getScalarType(), NumElems*SizeRatio);
24901 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24903 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24904 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24905 for (unsigned i = 0; i != NumElems; ++i)
24906 ShuffleVec[i] = i * SizeRatio;
24908 // Can't shuffle using an illegal type.
24909 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24910 && "WideVecVT should be legal");
24912 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24913 DAG.getUNDEF(WideVecVT),
24917 SDValue Mask = Mst->getMask();
24918 if (Mask.getValueType() == VT) {
24919 // Mask and original value have the same type
24920 NewMask = DAG.getBitcast(WideVecVT, Mask);
24921 for (unsigned i = 0; i != NumElems; ++i)
24922 ShuffleVec[i] = i * SizeRatio;
24923 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24924 ShuffleVec[i] = NumElems*SizeRatio;
24925 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24926 DAG.getConstant(0, dl, WideVecVT),
24930 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24931 unsigned WidenNumElts = NumElems*SizeRatio;
24932 unsigned MaskNumElts = VT.getVectorNumElements();
24933 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24936 unsigned NumConcat = WidenNumElts / MaskNumElts;
24937 SmallVector<SDValue, 16> Ops(NumConcat);
24938 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24940 for (unsigned i = 1; i != NumConcat; ++i)
24943 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24946 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24947 NewMask, StVT, Mst->getMemOperand(), false);
24949 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24950 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24951 const X86Subtarget *Subtarget) {
24952 StoreSDNode *St = cast<StoreSDNode>(N);
24953 EVT VT = St->getValue().getValueType();
24954 EVT StVT = St->getMemoryVT();
24956 SDValue StoredVal = St->getOperand(1);
24957 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24959 // If we are saving a concatenation of two XMM registers and 32-byte stores
24960 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24962 unsigned AddressSpace = St->getAddressSpace();
24963 unsigned Alignment = St->getAlignment();
24964 if (VT.is256BitVector() && StVT == VT &&
24965 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24966 AddressSpace, Alignment, &Fast) && !Fast) {
24967 unsigned NumElems = VT.getVectorNumElements();
24971 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24972 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24975 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24976 SDValue Ptr0 = St->getBasePtr();
24977 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24979 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24980 St->getPointerInfo(), St->isVolatile(),
24981 St->isNonTemporal(), Alignment);
24982 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24983 St->getPointerInfo(), St->isVolatile(),
24984 St->isNonTemporal(),
24985 std::min(16U, Alignment));
24986 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24989 // Optimize trunc store (of multiple scalars) to shuffle and store.
24990 // First, pack all of the elements in one place. Next, store to memory
24991 // in fewer chunks.
24992 if (St->isTruncatingStore() && VT.isVector()) {
24993 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24994 unsigned NumElems = VT.getVectorNumElements();
24995 assert(StVT != VT && "Cannot truncate to the same type");
24996 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24997 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24999 // The truncating store is legal in some cases. For example
25000 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25001 // are designated for truncate store.
25002 // In this case we don't need any further transformations.
25003 if (TLI.isTruncStoreLegal(VT, StVT))
25006 // From, To sizes and ElemCount must be pow of two
25007 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
25008 // We are going to use the original vector elt for storing.
25009 // Accumulated smaller vector elements must be a multiple of the store size.
25010 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
25012 unsigned SizeRatio = FromSz / ToSz;
25014 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25016 // Create a type on which we perform the shuffle
25017 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25018 StVT.getScalarType(), NumElems*SizeRatio);
25020 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25022 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
25023 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
25024 for (unsigned i = 0; i != NumElems; ++i)
25025 ShuffleVec[i] = i * SizeRatio;
25027 // Can't shuffle using an illegal type.
25028 if (!TLI.isTypeLegal(WideVecVT))
25031 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25032 DAG.getUNDEF(WideVecVT),
25034 // At this point all of the data is stored at the bottom of the
25035 // register. We now need to save it to mem.
25037 // Find the largest store unit
25038 MVT StoreType = MVT::i8;
25039 for (MVT Tp : MVT::integer_valuetypes()) {
25040 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
25044 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
25045 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
25046 (64 <= NumElems * ToSz))
25047 StoreType = MVT::f64;
25049 // Bitcast the original vector into a vector of store-size units
25050 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
25051 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
25052 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
25053 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
25054 SmallVector<SDValue, 8> Chains;
25055 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
25056 TLI.getPointerTy(DAG.getDataLayout()));
25057 SDValue Ptr = St->getBasePtr();
25059 // Perform one or more big stores into memory.
25060 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
25061 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
25062 StoreType, ShuffWide,
25063 DAG.getIntPtrConstant(i, dl));
25064 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
25065 St->getPointerInfo(), St->isVolatile(),
25066 St->isNonTemporal(), St->getAlignment());
25067 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25068 Chains.push_back(Ch);
25071 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
25074 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
25075 // the FP state in cases where an emms may be missing.
25076 // A preferable solution to the general problem is to figure out the right
25077 // places to insert EMMS. This qualifies as a quick hack.
25079 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
25080 if (VT.getSizeInBits() != 64)
25083 const Function *F = DAG.getMachineFunction().getFunction();
25084 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
25086 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
25087 if ((VT.isVector() ||
25088 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
25089 isa<LoadSDNode>(St->getValue()) &&
25090 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
25091 St->getChain().hasOneUse() && !St->isVolatile()) {
25092 SDNode* LdVal = St->getValue().getNode();
25093 LoadSDNode *Ld = nullptr;
25094 int TokenFactorIndex = -1;
25095 SmallVector<SDValue, 8> Ops;
25096 SDNode* ChainVal = St->getChain().getNode();
25097 // Must be a store of a load. We currently handle two cases: the load
25098 // is a direct child, and it's under an intervening TokenFactor. It is
25099 // possible to dig deeper under nested TokenFactors.
25100 if (ChainVal == LdVal)
25101 Ld = cast<LoadSDNode>(St->getChain());
25102 else if (St->getValue().hasOneUse() &&
25103 ChainVal->getOpcode() == ISD::TokenFactor) {
25104 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
25105 if (ChainVal->getOperand(i).getNode() == LdVal) {
25106 TokenFactorIndex = i;
25107 Ld = cast<LoadSDNode>(St->getValue());
25109 Ops.push_back(ChainVal->getOperand(i));
25113 if (!Ld || !ISD::isNormalLoad(Ld))
25116 // If this is not the MMX case, i.e. we are just turning i64 load/store
25117 // into f64 load/store, avoid the transformation if there are multiple
25118 // uses of the loaded value.
25119 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
25124 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
25125 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
25127 if (Subtarget->is64Bit() || F64IsLegal) {
25128 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
25129 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
25130 Ld->getPointerInfo(), Ld->isVolatile(),
25131 Ld->isNonTemporal(), Ld->isInvariant(),
25132 Ld->getAlignment());
25133 SDValue NewChain = NewLd.getValue(1);
25134 if (TokenFactorIndex != -1) {
25135 Ops.push_back(NewChain);
25136 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25138 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
25139 St->getPointerInfo(),
25140 St->isVolatile(), St->isNonTemporal(),
25141 St->getAlignment());
25144 // Otherwise, lower to two pairs of 32-bit loads / stores.
25145 SDValue LoAddr = Ld->getBasePtr();
25146 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
25147 DAG.getConstant(4, LdDL, MVT::i32));
25149 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
25150 Ld->getPointerInfo(),
25151 Ld->isVolatile(), Ld->isNonTemporal(),
25152 Ld->isInvariant(), Ld->getAlignment());
25153 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
25154 Ld->getPointerInfo().getWithOffset(4),
25155 Ld->isVolatile(), Ld->isNonTemporal(),
25157 MinAlign(Ld->getAlignment(), 4));
25159 SDValue NewChain = LoLd.getValue(1);
25160 if (TokenFactorIndex != -1) {
25161 Ops.push_back(LoLd);
25162 Ops.push_back(HiLd);
25163 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
25166 LoAddr = St->getBasePtr();
25167 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
25168 DAG.getConstant(4, StDL, MVT::i32));
25170 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
25171 St->getPointerInfo(),
25172 St->isVolatile(), St->isNonTemporal(),
25173 St->getAlignment());
25174 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
25175 St->getPointerInfo().getWithOffset(4),
25177 St->isNonTemporal(),
25178 MinAlign(St->getAlignment(), 4));
25179 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
25182 // This is similar to the above case, but here we handle a scalar 64-bit
25183 // integer store that is extracted from a vector on a 32-bit target.
25184 // If we have SSE2, then we can treat it like a floating-point double
25185 // to get past legalization. The execution dependencies fixup pass will
25186 // choose the optimal machine instruction for the store if this really is
25187 // an integer or v2f32 rather than an f64.
25188 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
25189 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
25190 SDValue OldExtract = St->getOperand(1);
25191 SDValue ExtOp0 = OldExtract.getOperand(0);
25192 unsigned VecSize = ExtOp0.getValueSizeInBits();
25193 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
25194 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
25195 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
25196 BitCast, OldExtract.getOperand(1));
25197 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
25198 St->getPointerInfo(), St->isVolatile(),
25199 St->isNonTemporal(), St->getAlignment());
25205 /// Return 'true' if this vector operation is "horizontal"
25206 /// and return the operands for the horizontal operation in LHS and RHS. A
25207 /// horizontal operation performs the binary operation on successive elements
25208 /// of its first operand, then on successive elements of its second operand,
25209 /// returning the resulting values in a vector. For example, if
25210 /// A = < float a0, float a1, float a2, float a3 >
25212 /// B = < float b0, float b1, float b2, float b3 >
25213 /// then the result of doing a horizontal operation on A and B is
25214 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
25215 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
25216 /// A horizontal-op B, for some already available A and B, and if so then LHS is
25217 /// set to A, RHS to B, and the routine returns 'true'.
25218 /// Note that the binary operation should have the property that if one of the
25219 /// operands is UNDEF then the result is UNDEF.
25220 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
25221 // Look for the following pattern: if
25222 // A = < float a0, float a1, float a2, float a3 >
25223 // B = < float b0, float b1, float b2, float b3 >
25225 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
25226 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
25227 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
25228 // which is A horizontal-op B.
25230 // At least one of the operands should be a vector shuffle.
25231 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
25232 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
25235 MVT VT = LHS.getSimpleValueType();
25237 assert((VT.is128BitVector() || VT.is256BitVector()) &&
25238 "Unsupported vector type for horizontal add/sub");
25240 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
25241 // operate independently on 128-bit lanes.
25242 unsigned NumElts = VT.getVectorNumElements();
25243 unsigned NumLanes = VT.getSizeInBits()/128;
25244 unsigned NumLaneElts = NumElts / NumLanes;
25245 assert((NumLaneElts % 2 == 0) &&
25246 "Vector type should have an even number of elements in each lane");
25247 unsigned HalfLaneElts = NumLaneElts/2;
25249 // View LHS in the form
25250 // LHS = VECTOR_SHUFFLE A, B, LMask
25251 // If LHS is not a shuffle then pretend it is the shuffle
25252 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
25253 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
25256 SmallVector<int, 16> LMask(NumElts);
25257 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25258 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
25259 A = LHS.getOperand(0);
25260 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
25261 B = LHS.getOperand(1);
25262 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
25263 std::copy(Mask.begin(), Mask.end(), LMask.begin());
25265 if (LHS.getOpcode() != ISD::UNDEF)
25267 for (unsigned i = 0; i != NumElts; ++i)
25271 // Likewise, view RHS in the form
25272 // RHS = VECTOR_SHUFFLE C, D, RMask
25274 SmallVector<int, 16> RMask(NumElts);
25275 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
25276 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
25277 C = RHS.getOperand(0);
25278 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
25279 D = RHS.getOperand(1);
25280 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
25281 std::copy(Mask.begin(), Mask.end(), RMask.begin());
25283 if (RHS.getOpcode() != ISD::UNDEF)
25285 for (unsigned i = 0; i != NumElts; ++i)
25289 // Check that the shuffles are both shuffling the same vectors.
25290 if (!(A == C && B == D) && !(A == D && B == C))
25293 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
25294 if (!A.getNode() && !B.getNode())
25297 // If A and B occur in reverse order in RHS, then "swap" them (which means
25298 // rewriting the mask).
25300 ShuffleVectorSDNode::commuteMask(RMask);
25302 // At this point LHS and RHS are equivalent to
25303 // LHS = VECTOR_SHUFFLE A, B, LMask
25304 // RHS = VECTOR_SHUFFLE A, B, RMask
25305 // Check that the masks correspond to performing a horizontal operation.
25306 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
25307 for (unsigned i = 0; i != NumLaneElts; ++i) {
25308 int LIdx = LMask[i+l], RIdx = RMask[i+l];
25310 // Ignore any UNDEF components.
25311 if (LIdx < 0 || RIdx < 0 ||
25312 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
25313 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
25316 // Check that successive elements are being operated on. If not, this is
25317 // not a horizontal operation.
25318 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
25319 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
25320 if (!(LIdx == Index && RIdx == Index + 1) &&
25321 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
25326 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
25327 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
25331 /// Do target-specific dag combines on floating point adds.
25332 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
25333 const X86Subtarget *Subtarget) {
25334 EVT VT = N->getValueType(0);
25335 SDValue LHS = N->getOperand(0);
25336 SDValue RHS = N->getOperand(1);
25338 // Try to synthesize horizontal adds from adds of shuffles.
25339 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25340 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25341 isHorizontalBinOp(LHS, RHS, true))
25342 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
25346 /// Do target-specific dag combines on floating point subs.
25347 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
25348 const X86Subtarget *Subtarget) {
25349 EVT VT = N->getValueType(0);
25350 SDValue LHS = N->getOperand(0);
25351 SDValue RHS = N->getOperand(1);
25353 // Try to synthesize horizontal subs from subs of shuffles.
25354 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
25355 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
25356 isHorizontalBinOp(LHS, RHS, false))
25357 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
25361 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
25362 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
25363 const X86Subtarget *Subtarget) {
25364 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
25366 // F[X]OR(0.0, x) -> x
25367 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25368 if (C->getValueAPF().isPosZero())
25369 return N->getOperand(1);
25371 // F[X]OR(x, 0.0) -> x
25372 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25373 if (C->getValueAPF().isPosZero())
25374 return N->getOperand(0);
25376 EVT VT = N->getValueType(0);
25377 if (VT.is512BitVector() && !Subtarget->hasDQI()) {
25379 MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
25380 MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
25382 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
25383 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
25384 unsigned IntOpcode = (N->getOpcode() == X86ISD::FOR) ? ISD::OR : ISD::XOR;
25385 SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
25386 return DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
25391 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
25392 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
25393 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
25395 // Only perform optimizations if UnsafeMath is used.
25396 if (!DAG.getTarget().Options.UnsafeFPMath)
25399 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25400 // into FMINC and FMAXC, which are Commutative operations.
25401 unsigned NewOp = 0;
25402 switch (N->getOpcode()) {
25403 default: llvm_unreachable("unknown opcode");
25404 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
25405 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
25408 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25409 N->getOperand(0), N->getOperand(1));
25412 /// Do target-specific dag combines on X86ISD::FAND nodes.
25413 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25414 // FAND(0.0, x) -> 0.0
25415 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25416 if (C->getValueAPF().isPosZero())
25417 return N->getOperand(0);
25419 // FAND(x, 0.0) -> 0.0
25420 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25421 if (C->getValueAPF().isPosZero())
25422 return N->getOperand(1);
25427 /// Do target-specific dag combines on X86ISD::FANDN nodes
25428 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25429 // FANDN(0.0, x) -> x
25430 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25431 if (C->getValueAPF().isPosZero())
25432 return N->getOperand(1);
25434 // FANDN(x, 0.0) -> 0.0
25435 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25436 if (C->getValueAPF().isPosZero())
25437 return N->getOperand(1);
25442 static SDValue PerformBTCombine(SDNode *N,
25444 TargetLowering::DAGCombinerInfo &DCI) {
25445 // BT ignores high bits in the bit index operand.
25446 SDValue Op1 = N->getOperand(1);
25447 if (Op1.hasOneUse()) {
25448 unsigned BitWidth = Op1.getValueSizeInBits();
25449 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25450 APInt KnownZero, KnownOne;
25451 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25452 !DCI.isBeforeLegalizeOps());
25453 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25454 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25455 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25456 DCI.CommitTargetLoweringOpt(TLO);
25461 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25462 SDValue Op = N->getOperand(0);
25463 if (Op.getOpcode() == ISD::BITCAST)
25464 Op = Op.getOperand(0);
25465 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25466 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25467 VT.getVectorElementType().getSizeInBits() ==
25468 OpVT.getVectorElementType().getSizeInBits()) {
25469 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25474 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25475 const X86Subtarget *Subtarget) {
25476 EVT VT = N->getValueType(0);
25477 if (!VT.isVector())
25480 SDValue N0 = N->getOperand(0);
25481 SDValue N1 = N->getOperand(1);
25482 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25485 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25486 // both SSE and AVX2 since there is no sign-extended shift right
25487 // operation on a vector with 64-bit elements.
25488 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25489 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25490 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25491 N0.getOpcode() == ISD::SIGN_EXTEND)) {
25492 SDValue N00 = N0.getOperand(0);
25494 // EXTLOAD has a better solution on AVX2,
25495 // it may be replaced with X86ISD::VSEXT node.
25496 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25497 if (!ISD::isNormalLoad(N00.getNode()))
25500 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25501 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25503 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25509 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25510 TargetLowering::DAGCombinerInfo &DCI,
25511 const X86Subtarget *Subtarget) {
25512 SDValue N0 = N->getOperand(0);
25513 EVT VT = N->getValueType(0);
25514 EVT SVT = VT.getScalarType();
25515 EVT InVT = N0.getValueType();
25516 EVT InSVT = InVT.getScalarType();
25519 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25520 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25521 // This exposes the sext to the sdivrem lowering, so that it directly extends
25522 // from AH (which we otherwise need to do contortions to access).
25523 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25524 InVT == MVT::i8 && VT == MVT::i32) {
25525 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25526 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25527 N0.getOperand(0), N0.getOperand(1));
25528 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25529 return R.getValue(1);
25532 if (!DCI.isBeforeLegalizeOps()) {
25533 if (InVT == MVT::i1) {
25534 SDValue Zero = DAG.getConstant(0, DL, VT);
25536 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25537 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25542 if (VT.isVector() && Subtarget->hasSSE2()) {
25543 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25544 EVT InVT = N.getValueType();
25545 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25546 Size / InVT.getScalarSizeInBits());
25547 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25548 DAG.getUNDEF(InVT));
25550 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25553 // If target-size is less than 128-bits, extend to a type that would extend
25554 // to 128 bits, extend that and extract the original target vector.
25555 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25556 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25557 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25558 unsigned Scale = 128 / VT.getSizeInBits();
25560 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25561 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25562 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25563 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25564 DAG.getIntPtrConstant(0, DL));
25567 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25568 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25569 if (VT.getSizeInBits() == 128 &&
25570 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25571 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25572 SDValue ExOp = ExtendVecSize(DL, N0, 128);
25573 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25576 // On pre-AVX2 targets, split into 128-bit nodes of
25577 // ISD::SIGN_EXTEND_VECTOR_INREG.
25578 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25579 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25580 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25581 unsigned NumVecs = VT.getSizeInBits() / 128;
25582 unsigned NumSubElts = 128 / SVT.getSizeInBits();
25583 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25584 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25586 SmallVector<SDValue, 8> Opnds;
25587 for (unsigned i = 0, Offset = 0; i != NumVecs;
25588 ++i, Offset += NumSubElts) {
25589 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25590 DAG.getIntPtrConstant(Offset, DL));
25591 SrcVec = ExtendVecSize(DL, SrcVec, 128);
25592 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25593 Opnds.push_back(SrcVec);
25595 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25599 if (!Subtarget->hasFp256())
25602 if (VT.isVector() && VT.getSizeInBits() == 256)
25603 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25609 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25610 const X86Subtarget* Subtarget) {
25612 EVT VT = N->getValueType(0);
25614 // Let legalize expand this if it isn't a legal type yet.
25615 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25618 EVT ScalarVT = VT.getScalarType();
25619 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25620 (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25621 !Subtarget->hasAVX512()))
25624 SDValue A = N->getOperand(0);
25625 SDValue B = N->getOperand(1);
25626 SDValue C = N->getOperand(2);
25628 bool NegA = (A.getOpcode() == ISD::FNEG);
25629 bool NegB = (B.getOpcode() == ISD::FNEG);
25630 bool NegC = (C.getOpcode() == ISD::FNEG);
25632 // Negative multiplication when NegA xor NegB
25633 bool NegMul = (NegA != NegB);
25635 A = A.getOperand(0);
25637 B = B.getOperand(0);
25639 C = C.getOperand(0);
25643 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25645 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25647 return DAG.getNode(Opcode, dl, VT, A, B, C);
25650 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25651 TargetLowering::DAGCombinerInfo &DCI,
25652 const X86Subtarget *Subtarget) {
25653 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
25654 // (and (i32 x86isd::setcc_carry), 1)
25655 // This eliminates the zext. This transformation is necessary because
25656 // ISD::SETCC is always legalized to i8.
25658 SDValue N0 = N->getOperand(0);
25659 EVT VT = N->getValueType(0);
25661 if (N0.getOpcode() == ISD::AND &&
25663 N0.getOperand(0).hasOneUse()) {
25664 SDValue N00 = N0.getOperand(0);
25665 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25666 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25667 if (!C || C->getZExtValue() != 1)
25669 return DAG.getNode(ISD::AND, dl, VT,
25670 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25671 N00.getOperand(0), N00.getOperand(1)),
25672 DAG.getConstant(1, dl, VT));
25676 if (N0.getOpcode() == ISD::TRUNCATE &&
25678 N0.getOperand(0).hasOneUse()) {
25679 SDValue N00 = N0.getOperand(0);
25680 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25681 return DAG.getNode(ISD::AND, dl, VT,
25682 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25683 N00.getOperand(0), N00.getOperand(1)),
25684 DAG.getConstant(1, dl, VT));
25688 if (VT.is256BitVector())
25689 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25692 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25693 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25694 // This exposes the zext to the udivrem lowering, so that it directly extends
25695 // from AH (which we otherwise need to do contortions to access).
25696 if (N0.getOpcode() == ISD::UDIVREM &&
25697 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25698 (VT == MVT::i32 || VT == MVT::i64)) {
25699 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25700 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25701 N0.getOperand(0), N0.getOperand(1));
25702 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25703 return R.getValue(1);
25709 // Optimize x == -y --> x+y == 0
25710 // x != -y --> x+y != 0
25711 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25712 const X86Subtarget* Subtarget) {
25713 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25714 SDValue LHS = N->getOperand(0);
25715 SDValue RHS = N->getOperand(1);
25716 EVT VT = N->getValueType(0);
25719 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25720 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25721 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25722 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25723 LHS.getOperand(1));
25724 return DAG.getSetCC(DL, N->getValueType(0), addV,
25725 DAG.getConstant(0, DL, addV.getValueType()), CC);
25727 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25728 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25729 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25730 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25731 RHS.getOperand(1));
25732 return DAG.getSetCC(DL, N->getValueType(0), addV,
25733 DAG.getConstant(0, DL, addV.getValueType()), CC);
25736 if (VT.getScalarType() == MVT::i1 &&
25737 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25739 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25740 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25741 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25743 if (!IsSEXT0 || !IsVZero1) {
25744 // Swap the operands and update the condition code.
25745 std::swap(LHS, RHS);
25746 CC = ISD::getSetCCSwappedOperands(CC);
25748 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25749 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25750 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25753 if (IsSEXT0 && IsVZero1) {
25754 assert(VT == LHS.getOperand(0).getValueType() &&
25755 "Uexpected operand type");
25756 if (CC == ISD::SETGT)
25757 return DAG.getConstant(0, DL, VT);
25758 if (CC == ISD::SETLE)
25759 return DAG.getConstant(1, DL, VT);
25760 if (CC == ISD::SETEQ || CC == ISD::SETGE)
25761 return DAG.getNOT(DL, LHS.getOperand(0), VT);
25763 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25764 "Unexpected condition code!");
25765 return LHS.getOperand(0);
25772 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25773 SelectionDAG &DAG) {
25775 MVT VT = Load->getSimpleValueType(0);
25776 MVT EVT = VT.getVectorElementType();
25777 SDValue Addr = Load->getOperand(1);
25778 SDValue NewAddr = DAG.getNode(
25779 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25780 DAG.getConstant(Index * EVT.getStoreSize(), dl,
25781 Addr.getSimpleValueType()));
25784 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25785 DAG.getMachineFunction().getMachineMemOperand(
25786 Load->getMemOperand(), 0, EVT.getStoreSize()));
25790 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25791 const X86Subtarget *Subtarget) {
25793 MVT VT = N->getOperand(1)->getSimpleValueType(0);
25794 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25795 "X86insertps is only defined for v4x32");
25797 SDValue Ld = N->getOperand(1);
25798 if (MayFoldLoad(Ld)) {
25799 // Extract the countS bits from the immediate so we can get the proper
25800 // address when narrowing the vector load to a specific element.
25801 // When the second source op is a memory address, insertps doesn't use
25802 // countS and just gets an f32 from that address.
25803 unsigned DestIndex =
25804 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25806 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25808 // Create this as a scalar to vector to match the instruction pattern.
25809 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25810 // countS bits are ignored when loading from memory on insertps, which
25811 // means we don't need to explicitly set them to 0.
25812 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25813 LoadScalarToVector, N->getOperand(2));
25818 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25819 SDValue V0 = N->getOperand(0);
25820 SDValue V1 = N->getOperand(1);
25822 EVT VT = N->getValueType(0);
25824 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25825 // operands and changing the mask to 1. This saves us a bunch of
25826 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25827 // x86InstrInfo knows how to commute this back after instruction selection
25828 // if it would help register allocation.
25830 // TODO: If optimizing for size or a processor that doesn't suffer from
25831 // partial register update stalls, this should be transformed into a MOVSD
25832 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25834 if (VT == MVT::v2f64)
25835 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25836 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25837 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25838 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25844 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25845 // as "sbb reg,reg", since it can be extended without zext and produces
25846 // an all-ones bit which is more useful than 0/1 in some cases.
25847 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25850 return DAG.getNode(ISD::AND, DL, VT,
25851 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25852 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25854 DAG.getConstant(1, DL, VT));
25855 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25856 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25857 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25858 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25862 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25863 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25864 TargetLowering::DAGCombinerInfo &DCI,
25865 const X86Subtarget *Subtarget) {
25867 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25868 SDValue EFLAGS = N->getOperand(1);
25870 if (CC == X86::COND_A) {
25871 // Try to convert COND_A into COND_B in an attempt to facilitate
25872 // materializing "setb reg".
25874 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25875 // cannot take an immediate as its first operand.
25877 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25878 EFLAGS.getValueType().isInteger() &&
25879 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25880 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25881 EFLAGS.getNode()->getVTList(),
25882 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25883 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25884 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25888 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25889 // a zext and produces an all-ones bit which is more useful than 0/1 in some
25891 if (CC == X86::COND_B)
25892 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25894 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25895 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25896 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25902 // Optimize branch condition evaluation.
25904 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25905 TargetLowering::DAGCombinerInfo &DCI,
25906 const X86Subtarget *Subtarget) {
25908 SDValue Chain = N->getOperand(0);
25909 SDValue Dest = N->getOperand(1);
25910 SDValue EFLAGS = N->getOperand(3);
25911 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25913 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25914 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25915 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25922 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25923 SelectionDAG &DAG) {
25924 // Take advantage of vector comparisons producing 0 or -1 in each lane to
25925 // optimize away operation when it's from a constant.
25927 // The general transformation is:
25928 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25929 // AND(VECTOR_CMP(x,y), constant2)
25930 // constant2 = UNARYOP(constant)
25932 // Early exit if this isn't a vector operation, the operand of the
25933 // unary operation isn't a bitwise AND, or if the sizes of the operations
25934 // aren't the same.
25935 EVT VT = N->getValueType(0);
25936 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25937 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25938 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25941 // Now check that the other operand of the AND is a constant. We could
25942 // make the transformation for non-constant splats as well, but it's unclear
25943 // that would be a benefit as it would not eliminate any operations, just
25944 // perform one more step in scalar code before moving to the vector unit.
25945 if (BuildVectorSDNode *BV =
25946 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25947 // Bail out if the vector isn't a constant.
25948 if (!BV->isConstant())
25951 // Everything checks out. Build up the new and improved node.
25953 EVT IntVT = BV->getValueType(0);
25954 // Create a new constant of the appropriate type for the transformed
25956 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25957 // The AND node needs bitcasts to/from an integer vector type around it.
25958 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25959 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25960 N->getOperand(0)->getOperand(0), MaskConst);
25961 SDValue Res = DAG.getBitcast(VT, NewAnd);
25968 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25969 const X86Subtarget *Subtarget) {
25970 SDValue Op0 = N->getOperand(0);
25971 EVT VT = N->getValueType(0);
25972 EVT InVT = Op0.getValueType();
25973 EVT InSVT = InVT.getScalarType();
25974 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25976 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25977 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25978 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25980 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25981 InVT.getVectorNumElements());
25982 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25984 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25985 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25987 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25993 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25994 const X86Subtarget *Subtarget) {
25995 // First try to optimize away the conversion entirely when it's
25996 // conditionally from a constant. Vectors only.
25997 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
26000 // Now move on to more general possibilities.
26001 SDValue Op0 = N->getOperand(0);
26002 EVT VT = N->getValueType(0);
26003 EVT InVT = Op0.getValueType();
26004 EVT InSVT = InVT.getScalarType();
26006 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
26007 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
26008 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
26010 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
26011 InVT.getVectorNumElements());
26012 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
26013 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
26016 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
26017 // a 32-bit target where SSE doesn't support i64->FP operations.
26018 if (Op0.getOpcode() == ISD::LOAD) {
26019 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
26020 EVT LdVT = Ld->getValueType(0);
26022 // This transformation is not supported if the result type is f16
26023 if (VT == MVT::f16)
26026 if (!Ld->isVolatile() && !VT.isVector() &&
26027 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
26028 !Subtarget->is64Bit() && LdVT == MVT::i64) {
26029 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
26030 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
26031 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
26038 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
26039 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
26040 X86TargetLowering::DAGCombinerInfo &DCI) {
26041 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
26042 // the result is either zero or one (depending on the input carry bit).
26043 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
26044 if (X86::isZeroNode(N->getOperand(0)) &&
26045 X86::isZeroNode(N->getOperand(1)) &&
26046 // We don't have a good way to replace an EFLAGS use, so only do this when
26048 SDValue(N, 1).use_empty()) {
26050 EVT VT = N->getValueType(0);
26051 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
26052 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
26053 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
26054 DAG.getConstant(X86::COND_B, DL,
26057 DAG.getConstant(1, DL, VT));
26058 return DCI.CombineTo(N, Res1, CarryOut);
26064 // fold (add Y, (sete X, 0)) -> adc 0, Y
26065 // (add Y, (setne X, 0)) -> sbb -1, Y
26066 // (sub (sete X, 0), Y) -> sbb 0, Y
26067 // (sub (setne X, 0), Y) -> adc -1, Y
26068 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
26071 // Look through ZExts.
26072 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
26073 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
26076 SDValue SetCC = Ext.getOperand(0);
26077 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
26080 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
26081 if (CC != X86::COND_E && CC != X86::COND_NE)
26084 SDValue Cmp = SetCC.getOperand(1);
26085 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
26086 !X86::isZeroNode(Cmp.getOperand(1)) ||
26087 !Cmp.getOperand(0).getValueType().isInteger())
26090 SDValue CmpOp0 = Cmp.getOperand(0);
26091 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
26092 DAG.getConstant(1, DL, CmpOp0.getValueType()));
26094 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
26095 if (CC == X86::COND_NE)
26096 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
26097 DL, OtherVal.getValueType(), OtherVal,
26098 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
26100 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
26101 DL, OtherVal.getValueType(), OtherVal,
26102 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
26105 /// PerformADDCombine - Do target-specific dag combines on integer adds.
26106 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
26107 const X86Subtarget *Subtarget) {
26108 EVT VT = N->getValueType(0);
26109 SDValue Op0 = N->getOperand(0);
26110 SDValue Op1 = N->getOperand(1);
26112 // Try to synthesize horizontal adds from adds of shuffles.
26113 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26114 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26115 isHorizontalBinOp(Op0, Op1, true))
26116 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
26118 return OptimizeConditionalInDecrement(N, DAG);
26121 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
26122 const X86Subtarget *Subtarget) {
26123 SDValue Op0 = N->getOperand(0);
26124 SDValue Op1 = N->getOperand(1);
26126 // X86 can't encode an immediate LHS of a sub. See if we can push the
26127 // negation into a preceding instruction.
26128 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
26129 // If the RHS of the sub is a XOR with one use and a constant, invert the
26130 // immediate. Then add one to the LHS of the sub so we can turn
26131 // X-Y -> X+~Y+1, saving one register.
26132 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
26133 isa<ConstantSDNode>(Op1.getOperand(1))) {
26134 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
26135 EVT VT = Op0.getValueType();
26136 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
26138 DAG.getConstant(~XorC, SDLoc(Op1), VT));
26139 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
26140 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
26144 // Try to synthesize horizontal adds from adds of shuffles.
26145 EVT VT = N->getValueType(0);
26146 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
26147 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
26148 isHorizontalBinOp(Op0, Op1, true))
26149 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
26151 return OptimizeConditionalInDecrement(N, DAG);
26154 /// performVZEXTCombine - Performs build vector combines
26155 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
26156 TargetLowering::DAGCombinerInfo &DCI,
26157 const X86Subtarget *Subtarget) {
26159 MVT VT = N->getSimpleValueType(0);
26160 SDValue Op = N->getOperand(0);
26161 MVT OpVT = Op.getSimpleValueType();
26162 MVT OpEltVT = OpVT.getVectorElementType();
26163 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
26165 // (vzext (bitcast (vzext (x)) -> (vzext x)
26167 while (V.getOpcode() == ISD::BITCAST)
26168 V = V.getOperand(0);
26170 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
26171 MVT InnerVT = V.getSimpleValueType();
26172 MVT InnerEltVT = InnerVT.getVectorElementType();
26174 // If the element sizes match exactly, we can just do one larger vzext. This
26175 // is always an exact type match as vzext operates on integer types.
26176 if (OpEltVT == InnerEltVT) {
26177 assert(OpVT == InnerVT && "Types must match for vzext!");
26178 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
26181 // The only other way we can combine them is if only a single element of the
26182 // inner vzext is used in the input to the outer vzext.
26183 if (InnerEltVT.getSizeInBits() < InputBits)
26186 // In this case, the inner vzext is completely dead because we're going to
26187 // only look at bits inside of the low element. Just do the outer vzext on
26188 // a bitcast of the input to the inner.
26189 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
26192 // Check if we can bypass extracting and re-inserting an element of an input
26193 // vector. Essentially:
26194 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
26195 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
26196 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
26197 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
26198 SDValue ExtractedV = V.getOperand(0);
26199 SDValue OrigV = ExtractedV.getOperand(0);
26200 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
26201 if (ExtractIdx->getZExtValue() == 0) {
26202 MVT OrigVT = OrigV.getSimpleValueType();
26203 // Extract a subvector if necessary...
26204 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
26205 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
26206 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
26207 OrigVT.getVectorNumElements() / Ratio);
26208 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
26209 DAG.getIntPtrConstant(0, DL));
26211 Op = DAG.getBitcast(OpVT, OrigV);
26212 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
26219 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
26220 DAGCombinerInfo &DCI) const {
26221 SelectionDAG &DAG = DCI.DAG;
26222 switch (N->getOpcode()) {
26224 case ISD::EXTRACT_VECTOR_ELT:
26225 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
26228 case X86ISD::SHRUNKBLEND:
26229 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
26230 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
26231 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
26232 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
26233 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
26234 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
26235 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
26238 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
26239 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
26240 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
26241 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
26242 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
26243 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
26244 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
26245 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
26246 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
26247 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
26248 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
26249 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
26251 case X86ISD::FOR: return PerformFORCombine(N, DAG, Subtarget);
26253 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
26254 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
26255 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
26256 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
26257 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
26258 case ISD::ANY_EXTEND:
26259 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
26260 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
26261 case ISD::SIGN_EXTEND_INREG:
26262 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
26263 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
26264 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
26265 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
26266 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
26267 case X86ISD::SHUFP: // Handle all target specific shuffles
26268 case X86ISD::PALIGNR:
26269 case X86ISD::UNPCKH:
26270 case X86ISD::UNPCKL:
26271 case X86ISD::MOVHLPS:
26272 case X86ISD::MOVLHPS:
26273 case X86ISD::PSHUFB:
26274 case X86ISD::PSHUFD:
26275 case X86ISD::PSHUFHW:
26276 case X86ISD::PSHUFLW:
26277 case X86ISD::MOVSS:
26278 case X86ISD::MOVSD:
26279 case X86ISD::VPERMILPI:
26280 case X86ISD::VPERM2X128:
26281 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
26282 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
26283 case X86ISD::INSERTPS: {
26284 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
26285 return PerformINSERTPSCombine(N, DAG, Subtarget);
26288 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
26294 /// isTypeDesirableForOp - Return true if the target has native support for
26295 /// the specified value type and it is 'desirable' to use the type for the
26296 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
26297 /// instruction encodings are longer and some i16 instructions are slow.
26298 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
26299 if (!isTypeLegal(VT))
26301 if (VT != MVT::i16)
26308 case ISD::SIGN_EXTEND:
26309 case ISD::ZERO_EXTEND:
26310 case ISD::ANY_EXTEND:
26323 /// IsDesirableToPromoteOp - This method query the target whether it is
26324 /// beneficial for dag combiner to promote the specified node. If true, it
26325 /// should return the desired promotion type by reference.
26326 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
26327 EVT VT = Op.getValueType();
26328 if (VT != MVT::i16)
26331 bool Promote = false;
26332 bool Commute = false;
26333 switch (Op.getOpcode()) {
26336 LoadSDNode *LD = cast<LoadSDNode>(Op);
26337 // If the non-extending load has a single use and it's not live out, then it
26338 // might be folded.
26339 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
26340 Op.hasOneUse()*/) {
26341 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
26342 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
26343 // The only case where we'd want to promote LOAD (rather then it being
26344 // promoted as an operand is when it's only use is liveout.
26345 if (UI->getOpcode() != ISD::CopyToReg)
26352 case ISD::SIGN_EXTEND:
26353 case ISD::ZERO_EXTEND:
26354 case ISD::ANY_EXTEND:
26359 SDValue N0 = Op.getOperand(0);
26360 // Look out for (store (shl (load), x)).
26361 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
26374 SDValue N0 = Op.getOperand(0);
26375 SDValue N1 = Op.getOperand(1);
26376 if (!Commute && MayFoldLoad(N1))
26378 // Avoid disabling potential load folding opportunities.
26379 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
26381 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
26391 //===----------------------------------------------------------------------===//
26392 // X86 Inline Assembly Support
26393 //===----------------------------------------------------------------------===//
26395 // Helper to match a string separated by whitespace.
26396 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26397 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26399 for (StringRef Piece : Pieces) {
26400 if (!S.startswith(Piece)) // Check if the piece matches.
26403 S = S.substr(Piece.size());
26404 StringRef::size_type Pos = S.find_first_not_of(" \t");
26405 if (Pos == 0) // We matched a prefix.
26414 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26416 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26417 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26418 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26419 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26421 if (AsmPieces.size() == 3)
26423 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26430 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26431 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26433 std::string AsmStr = IA->getAsmString();
26435 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26436 if (!Ty || Ty->getBitWidth() % 16 != 0)
26439 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26440 SmallVector<StringRef, 4> AsmPieces;
26441 SplitString(AsmStr, AsmPieces, ";\n");
26443 switch (AsmPieces.size()) {
26444 default: return false;
26446 // FIXME: this should verify that we are targeting a 486 or better. If not,
26447 // we will turn this bswap into something that will be lowered to logical
26448 // ops instead of emitting the bswap asm. For now, we don't support 486 or
26449 // lower so don't worry about this.
26451 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26452 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26453 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26454 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26455 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26456 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26457 // No need to check constraints, nothing other than the equivalent of
26458 // "=r,0" would be valid here.
26459 return IntrinsicLowering::LowerToByteSwap(CI);
26462 // rorw $$8, ${0:w} --> llvm.bswap.i16
26463 if (CI->getType()->isIntegerTy(16) &&
26464 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26465 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26466 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26468 StringRef ConstraintsStr = IA->getConstraintString();
26469 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26470 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26471 if (clobbersFlagRegisters(AsmPieces))
26472 return IntrinsicLowering::LowerToByteSwap(CI);
26476 if (CI->getType()->isIntegerTy(32) &&
26477 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26478 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26479 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26480 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26482 StringRef ConstraintsStr = IA->getConstraintString();
26483 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26484 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26485 if (clobbersFlagRegisters(AsmPieces))
26486 return IntrinsicLowering::LowerToByteSwap(CI);
26489 if (CI->getType()->isIntegerTy(64)) {
26490 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26491 if (Constraints.size() >= 2 &&
26492 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26493 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26494 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
26495 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26496 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26497 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26498 return IntrinsicLowering::LowerToByteSwap(CI);
26506 /// getConstraintType - Given a constraint letter, return the type of
26507 /// constraint it is for this target.
26508 X86TargetLowering::ConstraintType
26509 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26510 if (Constraint.size() == 1) {
26511 switch (Constraint[0]) {
26522 return C_RegisterClass;
26546 return TargetLowering::getConstraintType(Constraint);
26549 /// Examine constraint type and operand type and determine a weight value.
26550 /// This object must already have been set up with the operand type
26551 /// and the current alternative constraint selected.
26552 TargetLowering::ConstraintWeight
26553 X86TargetLowering::getSingleConstraintMatchWeight(
26554 AsmOperandInfo &info, const char *constraint) const {
26555 ConstraintWeight weight = CW_Invalid;
26556 Value *CallOperandVal = info.CallOperandVal;
26557 // If we don't have a value, we can't do a match,
26558 // but allow it at the lowest weight.
26559 if (!CallOperandVal)
26561 Type *type = CallOperandVal->getType();
26562 // Look at the constraint type.
26563 switch (*constraint) {
26565 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26576 if (CallOperandVal->getType()->isIntegerTy())
26577 weight = CW_SpecificReg;
26582 if (type->isFloatingPointTy())
26583 weight = CW_SpecificReg;
26586 if (type->isX86_MMXTy() && Subtarget->hasMMX())
26587 weight = CW_SpecificReg;
26591 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26592 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26593 weight = CW_Register;
26596 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26597 if (C->getZExtValue() <= 31)
26598 weight = CW_Constant;
26602 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26603 if (C->getZExtValue() <= 63)
26604 weight = CW_Constant;
26608 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26609 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26610 weight = CW_Constant;
26614 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26615 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26616 weight = CW_Constant;
26620 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26621 if (C->getZExtValue() <= 3)
26622 weight = CW_Constant;
26626 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26627 if (C->getZExtValue() <= 0xff)
26628 weight = CW_Constant;
26633 if (isa<ConstantFP>(CallOperandVal)) {
26634 weight = CW_Constant;
26638 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26639 if ((C->getSExtValue() >= -0x80000000LL) &&
26640 (C->getSExtValue() <= 0x7fffffffLL))
26641 weight = CW_Constant;
26645 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26646 if (C->getZExtValue() <= 0xffffffff)
26647 weight = CW_Constant;
26654 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26655 /// with another that has more specific requirements based on the type of the
26656 /// corresponding operand.
26657 const char *X86TargetLowering::
26658 LowerXConstraint(EVT ConstraintVT) const {
26659 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26660 // 'f' like normal targets.
26661 if (ConstraintVT.isFloatingPoint()) {
26662 if (Subtarget->hasSSE2())
26664 if (Subtarget->hasSSE1())
26668 return TargetLowering::LowerXConstraint(ConstraintVT);
26671 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26672 /// vector. If it is invalid, don't add anything to Ops.
26673 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26674 std::string &Constraint,
26675 std::vector<SDValue>&Ops,
26676 SelectionDAG &DAG) const {
26679 // Only support length 1 constraints for now.
26680 if (Constraint.length() > 1) return;
26682 char ConstraintLetter = Constraint[0];
26683 switch (ConstraintLetter) {
26686 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26687 if (C->getZExtValue() <= 31) {
26688 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26689 Op.getValueType());
26695 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26696 if (C->getZExtValue() <= 63) {
26697 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26698 Op.getValueType());
26704 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26705 if (isInt<8>(C->getSExtValue())) {
26706 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26707 Op.getValueType());
26713 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26714 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26715 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26716 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26717 Op.getValueType());
26723 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26724 if (C->getZExtValue() <= 3) {
26725 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26726 Op.getValueType());
26732 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26733 if (C->getZExtValue() <= 255) {
26734 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26735 Op.getValueType());
26741 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26742 if (C->getZExtValue() <= 127) {
26743 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26744 Op.getValueType());
26750 // 32-bit signed value
26751 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26752 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26753 C->getSExtValue())) {
26754 // Widen to 64 bits here to get it sign extended.
26755 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26758 // FIXME gcc accepts some relocatable values here too, but only in certain
26759 // memory models; it's complicated.
26764 // 32-bit unsigned value
26765 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26766 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26767 C->getZExtValue())) {
26768 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26769 Op.getValueType());
26773 // FIXME gcc accepts some relocatable values here too, but only in certain
26774 // memory models; it's complicated.
26778 // Literal immediates are always ok.
26779 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26780 // Widen to 64 bits here to get it sign extended.
26781 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26785 // In any sort of PIC mode addresses need to be computed at runtime by
26786 // adding in a register or some sort of table lookup. These can't
26787 // be used as immediates.
26788 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26791 // If we are in non-pic codegen mode, we allow the address of a global (with
26792 // an optional displacement) to be used with 'i'.
26793 GlobalAddressSDNode *GA = nullptr;
26794 int64_t Offset = 0;
26796 // Match either (GA), (GA+C), (GA+C1+C2), etc.
26798 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26799 Offset += GA->getOffset();
26801 } else if (Op.getOpcode() == ISD::ADD) {
26802 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26803 Offset += C->getZExtValue();
26804 Op = Op.getOperand(0);
26807 } else if (Op.getOpcode() == ISD::SUB) {
26808 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26809 Offset += -C->getZExtValue();
26810 Op = Op.getOperand(0);
26815 // Otherwise, this isn't something we can handle, reject it.
26819 const GlobalValue *GV = GA->getGlobal();
26820 // If we require an extra load to get this address, as in PIC mode, we
26821 // can't accept it.
26822 if (isGlobalStubReference(
26823 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26826 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26827 GA->getValueType(0), Offset);
26832 if (Result.getNode()) {
26833 Ops.push_back(Result);
26836 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26839 std::pair<unsigned, const TargetRegisterClass *>
26840 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26841 StringRef Constraint,
26843 // First, see if this is a constraint that directly corresponds to an LLVM
26845 if (Constraint.size() == 1) {
26846 // GCC Constraint Letters
26847 switch (Constraint[0]) {
26849 // TODO: Slight differences here in allocation order and leaving
26850 // RIP in the class. Do they matter any more here than they do
26851 // in the normal allocation?
26852 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26853 if (Subtarget->is64Bit()) {
26854 if (VT == MVT::i32 || VT == MVT::f32)
26855 return std::make_pair(0U, &X86::GR32RegClass);
26856 if (VT == MVT::i16)
26857 return std::make_pair(0U, &X86::GR16RegClass);
26858 if (VT == MVT::i8 || VT == MVT::i1)
26859 return std::make_pair(0U, &X86::GR8RegClass);
26860 if (VT == MVT::i64 || VT == MVT::f64)
26861 return std::make_pair(0U, &X86::GR64RegClass);
26864 // 32-bit fallthrough
26865 case 'Q': // Q_REGS
26866 if (VT == MVT::i32 || VT == MVT::f32)
26867 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26868 if (VT == MVT::i16)
26869 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26870 if (VT == MVT::i8 || VT == MVT::i1)
26871 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26872 if (VT == MVT::i64)
26873 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26875 case 'r': // GENERAL_REGS
26876 case 'l': // INDEX_REGS
26877 if (VT == MVT::i8 || VT == MVT::i1)
26878 return std::make_pair(0U, &X86::GR8RegClass);
26879 if (VT == MVT::i16)
26880 return std::make_pair(0U, &X86::GR16RegClass);
26881 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26882 return std::make_pair(0U, &X86::GR32RegClass);
26883 return std::make_pair(0U, &X86::GR64RegClass);
26884 case 'R': // LEGACY_REGS
26885 if (VT == MVT::i8 || VT == MVT::i1)
26886 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26887 if (VT == MVT::i16)
26888 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26889 if (VT == MVT::i32 || !Subtarget->is64Bit())
26890 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26891 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26892 case 'f': // FP Stack registers.
26893 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26894 // value to the correct fpstack register class.
26895 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26896 return std::make_pair(0U, &X86::RFP32RegClass);
26897 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26898 return std::make_pair(0U, &X86::RFP64RegClass);
26899 return std::make_pair(0U, &X86::RFP80RegClass);
26900 case 'y': // MMX_REGS if MMX allowed.
26901 if (!Subtarget->hasMMX()) break;
26902 return std::make_pair(0U, &X86::VR64RegClass);
26903 case 'Y': // SSE_REGS if SSE2 allowed
26904 if (!Subtarget->hasSSE2()) break;
26906 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26907 if (!Subtarget->hasSSE1()) break;
26909 switch (VT.SimpleTy) {
26911 // Scalar SSE types.
26914 return std::make_pair(0U, &X86::FR32RegClass);
26917 return std::make_pair(0U, &X86::FR64RegClass);
26925 return std::make_pair(0U, &X86::VR128RegClass);
26933 return std::make_pair(0U, &X86::VR256RegClass);
26938 return std::make_pair(0U, &X86::VR512RegClass);
26944 // Use the default implementation in TargetLowering to convert the register
26945 // constraint into a member of a register class.
26946 std::pair<unsigned, const TargetRegisterClass*> Res;
26947 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26949 // Not found as a standard register?
26951 // Map st(0) -> st(7) -> ST0
26952 if (Constraint.size() == 7 && Constraint[0] == '{' &&
26953 tolower(Constraint[1]) == 's' &&
26954 tolower(Constraint[2]) == 't' &&
26955 Constraint[3] == '(' &&
26956 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26957 Constraint[5] == ')' &&
26958 Constraint[6] == '}') {
26960 Res.first = X86::FP0+Constraint[4]-'0';
26961 Res.second = &X86::RFP80RegClass;
26965 // GCC allows "st(0)" to be called just plain "st".
26966 if (StringRef("{st}").equals_lower(Constraint)) {
26967 Res.first = X86::FP0;
26968 Res.second = &X86::RFP80RegClass;
26973 if (StringRef("{flags}").equals_lower(Constraint)) {
26974 Res.first = X86::EFLAGS;
26975 Res.second = &X86::CCRRegClass;
26979 // 'A' means EAX + EDX.
26980 if (Constraint == "A") {
26981 Res.first = X86::EAX;
26982 Res.second = &X86::GR32_ADRegClass;
26988 // Otherwise, check to see if this is a register class of the wrong value
26989 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26990 // turn into {ax},{dx}.
26991 // MVT::Other is used to specify clobber names.
26992 if (Res.second->hasType(VT) || VT == MVT::Other)
26993 return Res; // Correct type already, nothing to do.
26995 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26996 // return "eax". This should even work for things like getting 64bit integer
26997 // registers when given an f64 type.
26998 const TargetRegisterClass *Class = Res.second;
26999 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
27000 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
27001 unsigned Size = VT.getSizeInBits();
27002 MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
27003 : Size == 16 ? MVT::i16
27004 : Size == 32 ? MVT::i32
27005 : Size == 64 ? MVT::i64
27007 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
27009 Res.first = DestReg;
27010 Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
27011 : SimpleTy == MVT::i16 ? &X86::GR16RegClass
27012 : SimpleTy == MVT::i32 ? &X86::GR32RegClass
27013 : &X86::GR64RegClass;
27014 assert(Res.second->contains(Res.first) && "Register in register class");
27016 // No register found/type mismatch.
27018 Res.second = nullptr;
27020 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
27021 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
27022 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
27023 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
27024 Class == &X86::VR512RegClass) {
27025 // Handle references to XMM physical registers that got mapped into the
27026 // wrong class. This can happen with constraints like {xmm0} where the
27027 // target independent register mapper will just pick the first match it can
27028 // find, ignoring the required type.
27030 if (VT == MVT::f32 || VT == MVT::i32)
27031 Res.second = &X86::FR32RegClass;
27032 else if (VT == MVT::f64 || VT == MVT::i64)
27033 Res.second = &X86::FR64RegClass;
27034 else if (X86::VR128RegClass.hasType(VT))
27035 Res.second = &X86::VR128RegClass;
27036 else if (X86::VR256RegClass.hasType(VT))
27037 Res.second = &X86::VR256RegClass;
27038 else if (X86::VR512RegClass.hasType(VT))
27039 Res.second = &X86::VR512RegClass;
27041 // Type mismatch and not a clobber: Return an error;
27043 Res.second = nullptr;
27050 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
27051 const AddrMode &AM, Type *Ty,
27052 unsigned AS) const {
27053 // Scaling factors are not free at all.
27054 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
27055 // will take 2 allocations in the out of order engine instead of 1
27056 // for plain addressing mode, i.e. inst (reg1).
27058 // vaddps (%rsi,%drx), %ymm0, %ymm1
27059 // Requires two allocations (one for the load, one for the computation)
27061 // vaddps (%rsi), %ymm0, %ymm1
27062 // Requires just 1 allocation, i.e., freeing allocations for other operations
27063 // and having less micro operations to execute.
27065 // For some X86 architectures, this is even worse because for instance for
27066 // stores, the complex addressing mode forces the instruction to use the
27067 // "load" ports instead of the dedicated "store" port.
27068 // E.g., on Haswell:
27069 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
27070 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
27071 if (isLegalAddressingMode(DL, AM, Ty, AS))
27072 // Scale represents reg2 * scale, thus account for 1
27073 // as soon as we use a second register.
27074 return AM.Scale != 0;
27078 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
27079 // Integer division on x86 is expensive. However, when aggressively optimizing
27080 // for code size, we prefer to use a div instruction, as it is usually smaller
27081 // than the alternative sequence.
27082 // The exception to this is vector division. Since x86 doesn't have vector
27083 // integer division, leaving the division as-is is a loss even in terms of
27084 // size, because it will have to be scalarized, while the alternative code
27085 // sequence can be performed in vector form.
27086 bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
27087 Attribute::MinSize);
27088 return OptSize && !VT.isVector();