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 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
168 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
169 } else if (!Subtarget->useSoftFloat()) {
170 // We have an algorithm for SSE2->double, and we turn this into a
171 // 64-bit FILD followed by conditional FADD for other targets.
172 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
173 // We have an algorithm for SSE2, and we turn this into a 64-bit
174 // FILD for other targets.
175 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
178 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
180 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
181 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
183 if (!Subtarget->useSoftFloat()) {
184 // SSE has no i16 to fp conversion, only i32
185 if (X86ScalarSSEf32) {
186 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
187 // f32 and f64 cases are Legal, f80 case is not
188 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
190 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
191 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
194 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
195 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
198 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
199 // are Legal, f80 is custom lowered.
200 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
201 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
203 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
205 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
206 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
208 if (X86ScalarSSEf32) {
209 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
210 // f32 and f64 cases are Legal, f80 case is not
211 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
213 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
214 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
217 // Handle FP_TO_UINT by promoting the destination to a larger signed
219 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
220 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
221 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
223 if (Subtarget->is64Bit()) {
224 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
225 // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
226 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
227 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
229 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
230 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
232 } else if (!Subtarget->useSoftFloat()) {
233 // Since AVX is a superset of SSE3, only check for SSE here.
234 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
235 // Expand FP_TO_UINT into a select.
236 // FIXME: We would like to use a Custom expander here eventually to do
237 // the optimal thing for SSE vs. the default expansion in the legalizer.
238 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
240 // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
241 // With SSE3 we can use fisttpll to convert to a signed i64; without
242 // SSE, we're stuck with a fistpll.
243 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
245 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
248 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
249 if (!X86ScalarSSEf64) {
250 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
251 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
252 if (Subtarget->is64Bit()) {
253 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
254 // Without SSE, i64->f64 goes through memory.
255 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
259 // Scalar integer divide and remainder are lowered to use operations that
260 // produce two results, to match the available instructions. This exposes
261 // the two-result form to trivial CSE, which is able to combine x/y and x%y
262 // into a single instruction.
264 // Scalar integer multiply-high is also lowered to use two-result
265 // operations, to match the available instructions. However, plain multiply
266 // (low) operations are left as Legal, as there are single-result
267 // instructions for this in x86. Using the two-result multiply instructions
268 // when both high and low results are needed must be arranged by dagcombine.
269 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
271 setOperationAction(ISD::MULHS, VT, Expand);
272 setOperationAction(ISD::MULHU, VT, Expand);
273 setOperationAction(ISD::SDIV, VT, Expand);
274 setOperationAction(ISD::UDIV, VT, Expand);
275 setOperationAction(ISD::SREM, VT, Expand);
276 setOperationAction(ISD::UREM, VT, Expand);
278 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
279 setOperationAction(ISD::ADDC, VT, Custom);
280 setOperationAction(ISD::ADDE, VT, Custom);
281 setOperationAction(ISD::SUBC, VT, Custom);
282 setOperationAction(ISD::SUBE, VT, Custom);
285 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
286 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
287 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
288 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
289 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
290 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
291 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
292 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
293 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
294 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
295 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
296 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
297 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
298 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
299 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
300 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
301 if (Subtarget->is64Bit())
302 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
303 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
304 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
305 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
306 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
308 if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
309 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
310 // is. We should promote the value to 64-bits to solve this.
311 // This is what the CRT headers do - `fmodf` is an inline header
312 // function casting to f64 and calling `fmod`.
313 setOperationAction(ISD::FREM , MVT::f32 , Promote);
315 setOperationAction(ISD::FREM , MVT::f32 , Expand);
318 setOperationAction(ISD::FREM , MVT::f64 , Expand);
319 setOperationAction(ISD::FREM , MVT::f80 , Expand);
320 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
322 // Promote the i8 variants and force them on up to i32 which has a shorter
324 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
325 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
326 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
327 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
328 if (Subtarget->hasBMI()) {
329 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
330 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
331 if (Subtarget->is64Bit())
332 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
334 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
335 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
336 if (Subtarget->is64Bit())
337 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
340 if (Subtarget->hasLZCNT()) {
341 // When promoting the i8 variants, force them to i32 for a shorter
343 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
344 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
345 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
346 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
347 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
348 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
349 if (Subtarget->is64Bit())
350 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
352 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
353 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
354 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
355 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
356 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
357 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
358 if (Subtarget->is64Bit()) {
359 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
360 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
364 // Special handling for half-precision floating point conversions.
365 // If we don't have F16C support, then lower half float conversions
366 // into library calls.
367 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
368 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
369 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
372 // There's never any support for operations beyond MVT::f32.
373 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
374 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
375 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
376 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
378 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
379 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
380 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
381 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
382 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
383 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
385 if (Subtarget->hasPOPCNT()) {
386 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
388 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
389 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
390 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
391 if (Subtarget->is64Bit())
392 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
395 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
397 if (!Subtarget->hasMOVBE())
398 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
400 // These should be promoted to a larger select which is supported.
401 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
402 // X86 wants to expand cmov itself.
403 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
404 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
405 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
406 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
407 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
408 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
409 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
410 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
411 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
412 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
413 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
414 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
415 if (Subtarget->is64Bit()) {
416 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
417 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
419 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
420 setOperationAction(ISD::CATCHRET , MVT::Other, Custom);
421 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
422 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
423 // support continuation, user-level threading, and etc.. As a result, no
424 // other SjLj exception interfaces are implemented and please don't build
425 // your own exception handling based on them.
426 // LLVM/Clang supports zero-cost DWARF exception handling.
427 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
428 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
431 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
432 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
433 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
434 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
435 if (Subtarget->is64Bit())
436 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
437 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
438 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
439 if (Subtarget->is64Bit()) {
440 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
441 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
442 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
443 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
444 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
446 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
447 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
448 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
449 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
450 if (Subtarget->is64Bit()) {
451 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
452 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
453 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
456 if (Subtarget->hasSSE1())
457 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
459 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
461 // Expand certain atomics
462 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
464 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
465 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
466 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
469 if (Subtarget->hasCmpxchg16b()) {
470 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
473 // FIXME - use subtarget debug flags
474 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
475 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
476 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
479 if (Subtarget->isTarget64BitLP64()) {
480 setExceptionPointerRegister(X86::RAX);
481 setExceptionSelectorRegister(X86::RDX);
483 setExceptionPointerRegister(X86::EAX);
484 setExceptionSelectorRegister(X86::EDX);
486 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
487 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
489 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
490 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
492 setOperationAction(ISD::TRAP, MVT::Other, Legal);
493 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
495 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
496 setOperationAction(ISD::VASTART , MVT::Other, Custom);
497 setOperationAction(ISD::VAEND , MVT::Other, Expand);
498 if (Subtarget->is64Bit()) {
499 setOperationAction(ISD::VAARG , MVT::Other, Custom);
500 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
502 // TargetInfo::CharPtrBuiltinVaList
503 setOperationAction(ISD::VAARG , MVT::Other, Expand);
504 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
507 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
508 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
510 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
512 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
513 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
514 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
516 if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
517 // f32 and f64 use SSE.
518 // Set up the FP register classes.
519 addRegisterClass(MVT::f32, &X86::FR32RegClass);
520 addRegisterClass(MVT::f64, &X86::FR64RegClass);
522 // Use ANDPD to simulate FABS.
523 setOperationAction(ISD::FABS , MVT::f64, Custom);
524 setOperationAction(ISD::FABS , MVT::f32, Custom);
526 // Use XORP to simulate FNEG.
527 setOperationAction(ISD::FNEG , MVT::f64, Custom);
528 setOperationAction(ISD::FNEG , MVT::f32, Custom);
530 // Use ANDPD and ORPD to simulate FCOPYSIGN.
531 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
532 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
534 // Lower this to FGETSIGNx86 plus an AND.
535 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
536 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
538 // We don't support sin/cos/fmod
539 setOperationAction(ISD::FSIN , MVT::f64, Expand);
540 setOperationAction(ISD::FCOS , MVT::f64, Expand);
541 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
542 setOperationAction(ISD::FSIN , MVT::f32, Expand);
543 setOperationAction(ISD::FCOS , MVT::f32, Expand);
544 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
546 // Expand FP immediates into loads from the stack, except for the special
548 addLegalFPImmediate(APFloat(+0.0)); // xorpd
549 addLegalFPImmediate(APFloat(+0.0f)); // xorps
550 } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
551 // Use SSE for f32, x87 for f64.
552 // Set up the FP register classes.
553 addRegisterClass(MVT::f32, &X86::FR32RegClass);
554 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
556 // Use ANDPS to simulate FABS.
557 setOperationAction(ISD::FABS , MVT::f32, Custom);
559 // Use XORP to simulate FNEG.
560 setOperationAction(ISD::FNEG , MVT::f32, Custom);
562 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
564 // Use ANDPS and ORPS to simulate FCOPYSIGN.
565 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
566 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
568 // We don't support sin/cos/fmod
569 setOperationAction(ISD::FSIN , MVT::f32, Expand);
570 setOperationAction(ISD::FCOS , MVT::f32, Expand);
571 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
573 // Special cases we handle for FP constants.
574 addLegalFPImmediate(APFloat(+0.0f)); // xorps
575 addLegalFPImmediate(APFloat(+0.0)); // FLD0
576 addLegalFPImmediate(APFloat(+1.0)); // FLD1
577 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
578 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
580 if (!TM.Options.UnsafeFPMath) {
581 setOperationAction(ISD::FSIN , MVT::f64, Expand);
582 setOperationAction(ISD::FCOS , MVT::f64, Expand);
583 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
585 } else if (!Subtarget->useSoftFloat()) {
586 // f32 and f64 in x87.
587 // Set up the FP register classes.
588 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
589 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
591 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
592 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
593 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
594 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
596 if (!TM.Options.UnsafeFPMath) {
597 setOperationAction(ISD::FSIN , MVT::f64, Expand);
598 setOperationAction(ISD::FSIN , MVT::f32, Expand);
599 setOperationAction(ISD::FCOS , MVT::f64, Expand);
600 setOperationAction(ISD::FCOS , MVT::f32, Expand);
601 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
602 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
604 addLegalFPImmediate(APFloat(+0.0)); // FLD0
605 addLegalFPImmediate(APFloat(+1.0)); // FLD1
606 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
607 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
608 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
609 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
610 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
611 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
614 // We don't support FMA.
615 setOperationAction(ISD::FMA, MVT::f64, Expand);
616 setOperationAction(ISD::FMA, MVT::f32, Expand);
618 // Long double always uses X87.
619 if (!Subtarget->useSoftFloat()) {
620 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
621 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
622 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
624 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
625 addLegalFPImmediate(TmpFlt); // FLD0
627 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
630 APFloat TmpFlt2(+1.0);
631 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
633 addLegalFPImmediate(TmpFlt2); // FLD1
634 TmpFlt2.changeSign();
635 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
638 if (!TM.Options.UnsafeFPMath) {
639 setOperationAction(ISD::FSIN , MVT::f80, Expand);
640 setOperationAction(ISD::FCOS , MVT::f80, Expand);
641 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
644 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
645 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
646 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
647 setOperationAction(ISD::FRINT, MVT::f80, Expand);
648 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
649 setOperationAction(ISD::FMA, MVT::f80, Expand);
652 // Always use a library call for pow.
653 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
654 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
655 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
657 setOperationAction(ISD::FLOG, MVT::f80, Expand);
658 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
659 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
660 setOperationAction(ISD::FEXP, MVT::f80, Expand);
661 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
662 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
663 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
665 // First set operation action for all vector types to either promote
666 // (for widening) or expand (for scalarization). Then we will selectively
667 // turn on ones that can be effectively codegen'd.
668 for (MVT VT : MVT::vector_valuetypes()) {
669 setOperationAction(ISD::ADD , VT, Expand);
670 setOperationAction(ISD::SUB , VT, Expand);
671 setOperationAction(ISD::FADD, VT, Expand);
672 setOperationAction(ISD::FNEG, VT, Expand);
673 setOperationAction(ISD::FSUB, VT, Expand);
674 setOperationAction(ISD::MUL , VT, Expand);
675 setOperationAction(ISD::FMUL, VT, Expand);
676 setOperationAction(ISD::SDIV, VT, Expand);
677 setOperationAction(ISD::UDIV, VT, Expand);
678 setOperationAction(ISD::FDIV, VT, Expand);
679 setOperationAction(ISD::SREM, VT, Expand);
680 setOperationAction(ISD::UREM, VT, Expand);
681 setOperationAction(ISD::LOAD, VT, Expand);
682 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
683 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
684 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
685 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
686 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
687 setOperationAction(ISD::FABS, VT, Expand);
688 setOperationAction(ISD::FSIN, VT, Expand);
689 setOperationAction(ISD::FSINCOS, VT, Expand);
690 setOperationAction(ISD::FCOS, VT, Expand);
691 setOperationAction(ISD::FSINCOS, VT, Expand);
692 setOperationAction(ISD::FREM, VT, Expand);
693 setOperationAction(ISD::FMA, VT, Expand);
694 setOperationAction(ISD::FPOWI, VT, Expand);
695 setOperationAction(ISD::FSQRT, VT, Expand);
696 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
697 setOperationAction(ISD::FFLOOR, VT, Expand);
698 setOperationAction(ISD::FCEIL, VT, Expand);
699 setOperationAction(ISD::FTRUNC, VT, Expand);
700 setOperationAction(ISD::FRINT, VT, Expand);
701 setOperationAction(ISD::FNEARBYINT, VT, Expand);
702 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
703 setOperationAction(ISD::MULHS, VT, Expand);
704 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
705 setOperationAction(ISD::MULHU, VT, Expand);
706 setOperationAction(ISD::SDIVREM, VT, Expand);
707 setOperationAction(ISD::UDIVREM, VT, Expand);
708 setOperationAction(ISD::FPOW, VT, Expand);
709 setOperationAction(ISD::CTPOP, VT, Expand);
710 setOperationAction(ISD::CTTZ, VT, Expand);
711 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
712 setOperationAction(ISD::CTLZ, VT, Expand);
713 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
714 setOperationAction(ISD::SHL, VT, Expand);
715 setOperationAction(ISD::SRA, VT, Expand);
716 setOperationAction(ISD::SRL, VT, Expand);
717 setOperationAction(ISD::ROTL, VT, Expand);
718 setOperationAction(ISD::ROTR, VT, Expand);
719 setOperationAction(ISD::BSWAP, VT, Expand);
720 setOperationAction(ISD::SETCC, VT, Expand);
721 setOperationAction(ISD::FLOG, VT, Expand);
722 setOperationAction(ISD::FLOG2, VT, Expand);
723 setOperationAction(ISD::FLOG10, VT, Expand);
724 setOperationAction(ISD::FEXP, VT, Expand);
725 setOperationAction(ISD::FEXP2, VT, Expand);
726 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
727 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
728 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
729 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
730 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
731 setOperationAction(ISD::TRUNCATE, VT, Expand);
732 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
733 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
734 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
735 setOperationAction(ISD::VSELECT, VT, Expand);
736 setOperationAction(ISD::SELECT_CC, VT, Expand);
737 for (MVT InnerVT : MVT::vector_valuetypes()) {
738 setTruncStoreAction(InnerVT, VT, Expand);
740 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
741 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
743 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
744 // types, we have to deal with them whether we ask for Expansion or not.
745 // Setting Expand causes its own optimisation problems though, so leave
747 if (VT.getVectorElementType() == MVT::i1)
748 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
750 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
751 // split/scalarized right now.
752 if (VT.getVectorElementType() == MVT::f16)
753 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
757 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
758 // with -msoft-float, disable use of MMX as well.
759 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
760 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
761 // No operations on x86mmx supported, everything uses intrinsics.
764 // MMX-sized vectors (other than x86mmx) are expected to be expanded
765 // into smaller operations.
766 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
767 setOperationAction(ISD::MULHS, MMXTy, Expand);
768 setOperationAction(ISD::AND, MMXTy, Expand);
769 setOperationAction(ISD::OR, MMXTy, Expand);
770 setOperationAction(ISD::XOR, MMXTy, Expand);
771 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
772 setOperationAction(ISD::SELECT, MMXTy, Expand);
773 setOperationAction(ISD::BITCAST, MMXTy, Expand);
775 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
777 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
778 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
780 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
781 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
782 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
783 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
784 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
785 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
786 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
787 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
788 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
789 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
790 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
791 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
792 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
793 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
796 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
797 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
799 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
800 // registers cannot be used even for integer operations.
801 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
802 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
803 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
804 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
806 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
807 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
808 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
809 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
810 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
811 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
812 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
813 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
814 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
815 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
816 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
817 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
818 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
819 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
820 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
821 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
822 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
823 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
824 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
825 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
826 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
827 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
828 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
830 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
831 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
832 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
833 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
835 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
836 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
837 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
838 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
840 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
841 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
842 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
843 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
844 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
846 setOperationAction(ISD::CTPOP, MVT::v16i8, Custom);
847 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
848 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
849 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
851 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
852 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
853 MVT VT = (MVT::SimpleValueType)i;
854 // Do not attempt to custom lower non-power-of-2 vectors
855 if (!isPowerOf2_32(VT.getVectorNumElements()))
857 // Do not attempt to custom lower non-128-bit vectors
858 if (!VT.is128BitVector())
860 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
861 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
862 setOperationAction(ISD::VSELECT, VT, Custom);
863 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
866 // We support custom legalizing of sext and anyext loads for specific
867 // memory vector types which we can load as a scalar (or sequence of
868 // scalars) and extend in-register to a legal 128-bit vector type. For sext
869 // loads these must work with a single scalar load.
870 for (MVT VT : MVT::integer_vector_valuetypes()) {
871 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
872 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
873 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
874 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
875 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
876 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
877 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
878 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
879 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
882 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
883 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
884 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
885 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
886 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
887 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
888 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
889 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
891 if (Subtarget->is64Bit()) {
892 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
893 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
896 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
897 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
898 MVT VT = (MVT::SimpleValueType)i;
900 // Do not attempt to promote non-128-bit vectors
901 if (!VT.is128BitVector())
904 setOperationAction(ISD::AND, VT, Promote);
905 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
906 setOperationAction(ISD::OR, VT, Promote);
907 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
908 setOperationAction(ISD::XOR, VT, Promote);
909 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
910 setOperationAction(ISD::LOAD, VT, Promote);
911 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
912 setOperationAction(ISD::SELECT, VT, Promote);
913 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
916 // Custom lower v2i64 and v2f64 selects.
917 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
918 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
919 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
920 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
922 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
923 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
925 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
927 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
928 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
929 // As there is no 64-bit GPR available, we need build a special custom
930 // sequence to convert from v2i32 to v2f32.
931 if (!Subtarget->is64Bit())
932 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
934 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
935 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
937 for (MVT VT : MVT::fp_vector_valuetypes())
938 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
940 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
941 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
942 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
945 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
946 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
947 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
948 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
949 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
950 setOperationAction(ISD::FRINT, RoundedTy, Legal);
951 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
954 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
955 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
956 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
957 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
958 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
959 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
960 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
961 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
963 // FIXME: Do we need to handle scalar-to-vector here?
964 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
966 // We directly match byte blends in the backend as they match the VSELECT
968 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
970 // SSE41 brings specific instructions for doing vector sign extend even in
971 // cases where we don't have SRA.
972 for (MVT VT : MVT::integer_vector_valuetypes()) {
973 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
974 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
975 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
978 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
979 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
980 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
981 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
982 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
983 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
984 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
986 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
987 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
988 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
989 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
990 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
991 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
993 // i8 and i16 vectors are custom because the source register and source
994 // source memory operand types are not the same width. f32 vectors are
995 // custom since the immediate controlling the insert encodes additional
997 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
998 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
999 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1000 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1002 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1003 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1004 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1005 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1007 // FIXME: these should be Legal, but that's only for the case where
1008 // the index is constant. For now custom expand to deal with that.
1009 if (Subtarget->is64Bit()) {
1010 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1011 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1015 if (Subtarget->hasSSE2()) {
1016 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1017 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1018 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1020 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1021 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1023 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1024 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1026 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1027 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1029 // In the customized shift lowering, the legal cases in AVX2 will be
1031 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1032 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1034 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1035 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1037 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1038 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1041 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1042 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1043 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1044 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1045 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1046 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1047 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1049 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1050 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1051 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1053 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1054 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1055 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1056 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1057 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1058 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1059 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1060 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1061 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1062 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1063 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1064 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1066 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1067 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1068 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1069 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1070 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1071 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1072 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1073 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1074 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1075 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1076 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1077 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1079 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1080 // even though v8i16 is a legal type.
1081 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1082 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1083 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1085 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1086 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1087 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1089 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1090 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1092 for (MVT VT : MVT::fp_vector_valuetypes())
1093 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1095 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1096 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1098 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1099 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1101 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1102 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1104 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1105 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1106 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1107 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1109 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1110 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1111 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1113 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1114 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1115 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1116 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1117 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1118 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1119 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1120 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1121 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1122 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1123 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1124 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1126 setOperationAction(ISD::CTPOP, MVT::v32i8, Custom);
1127 setOperationAction(ISD::CTPOP, MVT::v16i16, Custom);
1128 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1129 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1131 if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1132 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1133 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1134 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1135 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1136 setOperationAction(ISD::FMA, MVT::f32, Legal);
1137 setOperationAction(ISD::FMA, MVT::f64, Legal);
1140 if (Subtarget->hasInt256()) {
1141 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1142 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1143 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1144 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1146 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1147 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1148 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1149 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1151 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1152 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1153 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1154 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1156 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1157 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1158 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1159 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1161 setOperationAction(ISD::SMAX, MVT::v32i8, Legal);
1162 setOperationAction(ISD::SMAX, MVT::v16i16, Legal);
1163 setOperationAction(ISD::SMAX, MVT::v8i32, Legal);
1164 setOperationAction(ISD::UMAX, MVT::v32i8, Legal);
1165 setOperationAction(ISD::UMAX, MVT::v16i16, Legal);
1166 setOperationAction(ISD::UMAX, MVT::v8i32, Legal);
1167 setOperationAction(ISD::SMIN, MVT::v32i8, Legal);
1168 setOperationAction(ISD::SMIN, MVT::v16i16, Legal);
1169 setOperationAction(ISD::SMIN, MVT::v8i32, Legal);
1170 setOperationAction(ISD::UMIN, MVT::v32i8, Legal);
1171 setOperationAction(ISD::UMIN, MVT::v16i16, Legal);
1172 setOperationAction(ISD::UMIN, MVT::v8i32, Legal);
1174 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1175 // when we have a 256bit-wide blend with immediate.
1176 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1178 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1179 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1180 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1181 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1182 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1183 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1184 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1186 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1187 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1188 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1189 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1190 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1191 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1193 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1194 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1195 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1196 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1198 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1199 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1200 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1201 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1203 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1204 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1205 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1206 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1208 setOperationAction(ISD::SMAX, MVT::v32i8, Custom);
1209 setOperationAction(ISD::SMAX, MVT::v16i16, Custom);
1210 setOperationAction(ISD::SMAX, MVT::v8i32, Custom);
1211 setOperationAction(ISD::UMAX, MVT::v32i8, Custom);
1212 setOperationAction(ISD::UMAX, MVT::v16i16, Custom);
1213 setOperationAction(ISD::UMAX, MVT::v8i32, Custom);
1214 setOperationAction(ISD::SMIN, MVT::v32i8, Custom);
1215 setOperationAction(ISD::SMIN, MVT::v16i16, Custom);
1216 setOperationAction(ISD::SMIN, MVT::v8i32, Custom);
1217 setOperationAction(ISD::UMIN, MVT::v32i8, Custom);
1218 setOperationAction(ISD::UMIN, MVT::v16i16, Custom);
1219 setOperationAction(ISD::UMIN, MVT::v8i32, Custom);
1222 // In the customized shift lowering, the legal cases in AVX2 will be
1224 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1225 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1227 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1228 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1230 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1231 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1233 // Custom lower several nodes for 256-bit types.
1234 for (MVT VT : MVT::vector_valuetypes()) {
1235 if (VT.getScalarSizeInBits() >= 32) {
1236 setOperationAction(ISD::MLOAD, VT, Legal);
1237 setOperationAction(ISD::MSTORE, VT, Legal);
1239 // Extract subvector is special because the value type
1240 // (result) is 128-bit but the source is 256-bit wide.
1241 if (VT.is128BitVector()) {
1242 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1244 // Do not attempt to custom lower other non-256-bit vectors
1245 if (!VT.is256BitVector())
1248 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1249 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1250 setOperationAction(ISD::VSELECT, VT, Custom);
1251 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1252 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1253 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1254 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1255 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1258 if (Subtarget->hasInt256())
1259 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1262 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1263 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1264 MVT VT = (MVT::SimpleValueType)i;
1266 // Do not attempt to promote non-256-bit vectors
1267 if (!VT.is256BitVector())
1270 setOperationAction(ISD::AND, VT, Promote);
1271 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1272 setOperationAction(ISD::OR, VT, Promote);
1273 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1274 setOperationAction(ISD::XOR, VT, Promote);
1275 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1276 setOperationAction(ISD::LOAD, VT, Promote);
1277 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1278 setOperationAction(ISD::SELECT, VT, Promote);
1279 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1283 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1284 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1285 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1286 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1287 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1289 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1290 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1291 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1293 for (MVT VT : MVT::fp_vector_valuetypes())
1294 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1296 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1297 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1298 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1299 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1300 setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1301 setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1302 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1303 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1304 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1305 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1306 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1307 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1309 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1310 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1311 setOperationAction(ISD::XOR, MVT::i1, Legal);
1312 setOperationAction(ISD::OR, MVT::i1, Legal);
1313 setOperationAction(ISD::AND, MVT::i1, Legal);
1314 setOperationAction(ISD::SUB, MVT::i1, Custom);
1315 setOperationAction(ISD::ADD, MVT::i1, Custom);
1316 setOperationAction(ISD::MUL, MVT::i1, Custom);
1317 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1318 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1319 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1320 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1321 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1323 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1324 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1325 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1326 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1327 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1328 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1330 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1331 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1332 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1333 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1334 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1335 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1336 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1337 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1339 // FIXME: [US]INT_TO_FP are not legal for f80.
1340 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1341 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1342 if (Subtarget->is64Bit()) {
1343 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1344 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1346 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1347 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1348 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1349 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1350 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1351 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1352 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1353 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1354 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1355 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1356 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1357 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1358 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1359 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1360 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1361 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1363 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1364 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1365 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1366 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1367 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1368 if (Subtarget->hasVLX()){
1369 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1370 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1371 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1372 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1373 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1375 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1376 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1377 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1378 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1379 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1381 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1382 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1383 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1384 if (Subtarget->hasDQI()) {
1385 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1386 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1388 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1389 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1390 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1391 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1392 if (Subtarget->hasVLX()) {
1393 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1394 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1395 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1396 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1397 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1398 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1399 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1400 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1403 if (Subtarget->hasVLX()) {
1404 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1405 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1406 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1407 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1408 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1409 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1410 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1411 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1413 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1414 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1415 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1416 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1417 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1418 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1419 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1420 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1421 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1422 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1423 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1424 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1425 if (Subtarget->hasDQI()) {
1426 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1427 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1429 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1430 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1431 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1432 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1433 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1434 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1435 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1436 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1437 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1438 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1440 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1441 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1442 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1443 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1444 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1446 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1447 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1449 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1451 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1452 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1453 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1454 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1455 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1456 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1457 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1458 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1459 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1460 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1461 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1463 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1464 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1465 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1466 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1467 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1468 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1469 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1470 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1472 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1473 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1475 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1476 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1478 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1480 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1481 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1483 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1484 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1486 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1487 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1489 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1490 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1491 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1492 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1493 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1494 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1496 if (Subtarget->hasCDI()) {
1497 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1498 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1499 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i64, Legal);
1500 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i32, Legal);
1502 if (Subtarget->hasVLX() && Subtarget->hasCDI()) {
1503 setOperationAction(ISD::CTLZ, MVT::v4i64, Legal);
1504 setOperationAction(ISD::CTLZ, MVT::v8i32, Legal);
1505 setOperationAction(ISD::CTLZ, MVT::v2i64, Legal);
1506 setOperationAction(ISD::CTLZ, MVT::v4i32, Legal);
1507 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i64, Legal);
1508 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i32, Legal);
1509 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v2i64, Legal);
1510 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i32, Legal);
1512 if (Subtarget->hasDQI()) {
1513 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1514 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1515 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1517 // Custom lower several nodes.
1518 for (MVT VT : MVT::vector_valuetypes()) {
1519 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1521 setOperationAction(ISD::AND, VT, Legal);
1522 setOperationAction(ISD::OR, VT, Legal);
1523 setOperationAction(ISD::XOR, VT, Legal);
1525 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1526 setOperationAction(ISD::MGATHER, VT, Custom);
1527 setOperationAction(ISD::MSCATTER, VT, Custom);
1529 // Extract subvector is special because the value type
1530 // (result) is 256/128-bit but the source is 512-bit wide.
1531 if (VT.is128BitVector() || VT.is256BitVector()) {
1532 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1534 if (VT.getVectorElementType() == MVT::i1)
1535 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1537 // Do not attempt to custom lower other non-512-bit vectors
1538 if (!VT.is512BitVector())
1541 if (EltSize >= 32) {
1542 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1543 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1544 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1545 setOperationAction(ISD::VSELECT, VT, Legal);
1546 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1547 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1548 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1549 setOperationAction(ISD::MLOAD, VT, Legal);
1550 setOperationAction(ISD::MSTORE, VT, Legal);
1553 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1554 MVT VT = (MVT::SimpleValueType)i;
1556 // Do not attempt to promote non-512-bit vectors.
1557 if (!VT.is512BitVector())
1560 setOperationAction(ISD::SELECT, VT, Promote);
1561 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1565 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1566 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1567 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1569 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1570 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1572 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1573 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1574 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1575 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1576 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1577 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1578 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1579 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1580 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1581 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1582 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1583 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1584 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1585 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1586 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1587 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1588 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1589 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1590 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1591 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1592 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1593 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1594 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1595 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1596 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1597 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1598 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1599 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1600 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1601 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1603 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1604 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1605 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1606 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1607 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1608 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1609 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1610 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1612 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1613 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1614 if (Subtarget->hasVLX())
1615 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1617 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1618 const MVT VT = (MVT::SimpleValueType)i;
1620 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1622 // Do not attempt to promote non-512-bit vectors.
1623 if (!VT.is512BitVector())
1627 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1628 setOperationAction(ISD::VSELECT, VT, Legal);
1633 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1634 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1635 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1637 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1638 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1639 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1640 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1641 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1642 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1643 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1644 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1645 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1646 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1648 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1649 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1650 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1651 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1652 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1653 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1654 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1655 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1657 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1658 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1659 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1660 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1661 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1662 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1663 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1664 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1667 // We want to custom lower some of our intrinsics.
1668 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1669 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1670 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1671 if (!Subtarget->is64Bit())
1672 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1674 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1675 // handle type legalization for these operations here.
1677 // FIXME: We really should do custom legalization for addition and
1678 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1679 // than generic legalization for 64-bit multiplication-with-overflow, though.
1680 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1681 // Add/Sub/Mul with overflow operations are custom lowered.
1683 setOperationAction(ISD::SADDO, VT, Custom);
1684 setOperationAction(ISD::UADDO, VT, Custom);
1685 setOperationAction(ISD::SSUBO, VT, Custom);
1686 setOperationAction(ISD::USUBO, VT, Custom);
1687 setOperationAction(ISD::SMULO, VT, Custom);
1688 setOperationAction(ISD::UMULO, VT, Custom);
1692 if (!Subtarget->is64Bit()) {
1693 // These libcalls are not available in 32-bit.
1694 setLibcallName(RTLIB::SHL_I128, nullptr);
1695 setLibcallName(RTLIB::SRL_I128, nullptr);
1696 setLibcallName(RTLIB::SRA_I128, nullptr);
1699 // Combine sin / cos into one node or libcall if possible.
1700 if (Subtarget->hasSinCos()) {
1701 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1702 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1703 if (Subtarget->isTargetDarwin()) {
1704 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1705 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1706 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1707 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1711 if (Subtarget->isTargetWin64()) {
1712 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1713 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1714 setOperationAction(ISD::SREM, MVT::i128, Custom);
1715 setOperationAction(ISD::UREM, MVT::i128, Custom);
1716 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1717 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1720 // We have target-specific dag combine patterns for the following nodes:
1721 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1722 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1723 setTargetDAGCombine(ISD::BITCAST);
1724 setTargetDAGCombine(ISD::VSELECT);
1725 setTargetDAGCombine(ISD::SELECT);
1726 setTargetDAGCombine(ISD::SHL);
1727 setTargetDAGCombine(ISD::SRA);
1728 setTargetDAGCombine(ISD::SRL);
1729 setTargetDAGCombine(ISD::OR);
1730 setTargetDAGCombine(ISD::AND);
1731 setTargetDAGCombine(ISD::ADD);
1732 setTargetDAGCombine(ISD::FADD);
1733 setTargetDAGCombine(ISD::FSUB);
1734 setTargetDAGCombine(ISD::FMA);
1735 setTargetDAGCombine(ISD::SUB);
1736 setTargetDAGCombine(ISD::LOAD);
1737 setTargetDAGCombine(ISD::MLOAD);
1738 setTargetDAGCombine(ISD::STORE);
1739 setTargetDAGCombine(ISD::MSTORE);
1740 setTargetDAGCombine(ISD::ZERO_EXTEND);
1741 setTargetDAGCombine(ISD::ANY_EXTEND);
1742 setTargetDAGCombine(ISD::SIGN_EXTEND);
1743 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1744 setTargetDAGCombine(ISD::SINT_TO_FP);
1745 setTargetDAGCombine(ISD::UINT_TO_FP);
1746 setTargetDAGCombine(ISD::SETCC);
1747 setTargetDAGCombine(ISD::BUILD_VECTOR);
1748 setTargetDAGCombine(ISD::MUL);
1749 setTargetDAGCombine(ISD::XOR);
1751 computeRegisterProperties(Subtarget->getRegisterInfo());
1753 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1754 MaxStoresPerMemsetOptSize = 8;
1755 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1756 MaxStoresPerMemcpyOptSize = 4;
1757 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1758 MaxStoresPerMemmoveOptSize = 4;
1759 setPrefLoopAlignment(4); // 2^4 bytes.
1761 // Predictable cmov don't hurt on atom because it's in-order.
1762 PredictableSelectIsExpensive = !Subtarget->isAtom();
1763 EnableExtLdPromotion = true;
1764 setPrefFunctionAlignment(4); // 2^4 bytes.
1766 verifyIntrinsicTables();
1769 // This has so far only been implemented for 64-bit MachO.
1770 bool X86TargetLowering::useLoadStackGuardNode() const {
1771 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1774 TargetLoweringBase::LegalizeTypeAction
1775 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1776 if (ExperimentalVectorWideningLegalization &&
1777 VT.getVectorNumElements() != 1 &&
1778 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1779 return TypeWidenVector;
1781 return TargetLoweringBase::getPreferredVectorAction(VT);
1784 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1787 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1789 const unsigned NumElts = VT.getVectorNumElements();
1790 const EVT EltVT = VT.getVectorElementType();
1791 if (VT.is512BitVector()) {
1792 if (Subtarget->hasAVX512())
1793 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1794 EltVT == MVT::f32 || EltVT == MVT::f64)
1796 case 8: return MVT::v8i1;
1797 case 16: return MVT::v16i1;
1799 if (Subtarget->hasBWI())
1800 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1802 case 32: return MVT::v32i1;
1803 case 64: return MVT::v64i1;
1807 if (VT.is256BitVector() || VT.is128BitVector()) {
1808 if (Subtarget->hasVLX())
1809 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1810 EltVT == MVT::f32 || EltVT == MVT::f64)
1812 case 2: return MVT::v2i1;
1813 case 4: return MVT::v4i1;
1814 case 8: return MVT::v8i1;
1816 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1817 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1819 case 8: return MVT::v8i1;
1820 case 16: return MVT::v16i1;
1821 case 32: return MVT::v32i1;
1825 return VT.changeVectorElementTypeToInteger();
1828 /// Helper for getByValTypeAlignment to determine
1829 /// the desired ByVal argument alignment.
1830 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1833 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1834 if (VTy->getBitWidth() == 128)
1836 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1837 unsigned EltAlign = 0;
1838 getMaxByValAlign(ATy->getElementType(), EltAlign);
1839 if (EltAlign > MaxAlign)
1840 MaxAlign = EltAlign;
1841 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1842 for (auto *EltTy : STy->elements()) {
1843 unsigned EltAlign = 0;
1844 getMaxByValAlign(EltTy, EltAlign);
1845 if (EltAlign > MaxAlign)
1846 MaxAlign = EltAlign;
1853 /// Return the desired alignment for ByVal aggregate
1854 /// function arguments in the caller parameter area. For X86, aggregates
1855 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1856 /// are at 4-byte boundaries.
1857 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1858 const DataLayout &DL) const {
1859 if (Subtarget->is64Bit()) {
1860 // Max of 8 and alignment of type.
1861 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1868 if (Subtarget->hasSSE1())
1869 getMaxByValAlign(Ty, Align);
1873 /// Returns the target specific optimal type for load
1874 /// and store operations as a result of memset, memcpy, and memmove
1875 /// lowering. If DstAlign is zero that means it's safe to destination
1876 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1877 /// means there isn't a need to check it against alignment requirement,
1878 /// probably because the source does not need to be loaded. If 'IsMemset' is
1879 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1880 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1881 /// source is constant so it does not need to be loaded.
1882 /// It returns EVT::Other if the type should be determined using generic
1883 /// target-independent logic.
1885 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1886 unsigned DstAlign, unsigned SrcAlign,
1887 bool IsMemset, bool ZeroMemset,
1889 MachineFunction &MF) const {
1890 const Function *F = MF.getFunction();
1891 if ((!IsMemset || ZeroMemset) &&
1892 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1894 (!Subtarget->isUnalignedMem16Slow() ||
1895 ((DstAlign == 0 || DstAlign >= 16) &&
1896 (SrcAlign == 0 || SrcAlign >= 16)))) {
1898 // FIXME: Check if unaligned 32-byte accesses are slow.
1899 if (Subtarget->hasInt256())
1901 if (Subtarget->hasFp256())
1904 if (Subtarget->hasSSE2())
1906 if (Subtarget->hasSSE1())
1908 } else if (!MemcpyStrSrc && Size >= 8 &&
1909 !Subtarget->is64Bit() &&
1910 Subtarget->hasSSE2()) {
1911 // Do not use f64 to lower memcpy if source is string constant. It's
1912 // better to use i32 to avoid the loads.
1916 // This is a compromise. If we reach here, unaligned accesses may be slow on
1917 // this target. However, creating smaller, aligned accesses could be even
1918 // slower and would certainly be a lot more code.
1919 if (Subtarget->is64Bit() && Size >= 8)
1924 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1926 return X86ScalarSSEf32;
1927 else if (VT == MVT::f64)
1928 return X86ScalarSSEf64;
1933 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1938 switch (VT.getSizeInBits()) {
1940 // 8-byte and under are always assumed to be fast.
1944 *Fast = !Subtarget->isUnalignedMem16Slow();
1947 *Fast = !Subtarget->isUnalignedMem32Slow();
1949 // TODO: What about AVX-512 (512-bit) accesses?
1952 // Misaligned accesses of any size are always allowed.
1956 /// Return the entry encoding for a jump table in the
1957 /// current function. The returned value is a member of the
1958 /// MachineJumpTableInfo::JTEntryKind enum.
1959 unsigned X86TargetLowering::getJumpTableEncoding() const {
1960 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1962 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1963 Subtarget->isPICStyleGOT())
1964 return MachineJumpTableInfo::EK_Custom32;
1966 // Otherwise, use the normal jump table encoding heuristics.
1967 return TargetLowering::getJumpTableEncoding();
1970 bool X86TargetLowering::useSoftFloat() const {
1971 return Subtarget->useSoftFloat();
1975 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1976 const MachineBasicBlock *MBB,
1977 unsigned uid,MCContext &Ctx) const{
1978 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1979 Subtarget->isPICStyleGOT());
1980 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1982 return MCSymbolRefExpr::create(MBB->getSymbol(),
1983 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1986 /// Returns relocation base for the given PIC jumptable.
1987 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1988 SelectionDAG &DAG) const {
1989 if (!Subtarget->is64Bit())
1990 // This doesn't have SDLoc associated with it, but is not really the
1991 // same as a Register.
1992 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1993 getPointerTy(DAG.getDataLayout()));
1997 /// This returns the relocation base for the given PIC jumptable,
1998 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1999 const MCExpr *X86TargetLowering::
2000 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2001 MCContext &Ctx) const {
2002 // X86-64 uses RIP relative addressing based on the jump table label.
2003 if (Subtarget->isPICStyleRIPRel())
2004 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2006 // Otherwise, the reference is relative to the PIC base.
2007 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2010 std::pair<const TargetRegisterClass *, uint8_t>
2011 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2013 const TargetRegisterClass *RRC = nullptr;
2015 switch (VT.SimpleTy) {
2017 return TargetLowering::findRepresentativeClass(TRI, VT);
2018 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2019 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2022 RRC = &X86::VR64RegClass;
2024 case MVT::f32: case MVT::f64:
2025 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2026 case MVT::v4f32: case MVT::v2f64:
2027 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2029 RRC = &X86::VR128RegClass;
2032 return std::make_pair(RRC, Cost);
2035 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2036 unsigned &Offset) const {
2037 if (!Subtarget->isTargetLinux())
2040 if (Subtarget->is64Bit()) {
2041 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2043 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2055 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2056 unsigned DestAS) const {
2057 assert(SrcAS != DestAS && "Expected different address spaces!");
2059 return SrcAS < 256 && DestAS < 256;
2062 //===----------------------------------------------------------------------===//
2063 // Return Value Calling Convention Implementation
2064 //===----------------------------------------------------------------------===//
2066 #include "X86GenCallingConv.inc"
2069 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2070 MachineFunction &MF, bool isVarArg,
2071 const SmallVectorImpl<ISD::OutputArg> &Outs,
2072 LLVMContext &Context) const {
2073 SmallVector<CCValAssign, 16> RVLocs;
2074 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2075 return CCInfo.CheckReturn(Outs, RetCC_X86);
2078 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2079 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2084 X86TargetLowering::LowerReturn(SDValue Chain,
2085 CallingConv::ID CallConv, bool isVarArg,
2086 const SmallVectorImpl<ISD::OutputArg> &Outs,
2087 const SmallVectorImpl<SDValue> &OutVals,
2088 SDLoc dl, SelectionDAG &DAG) const {
2089 MachineFunction &MF = DAG.getMachineFunction();
2090 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2092 SmallVector<CCValAssign, 16> RVLocs;
2093 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2094 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2097 SmallVector<SDValue, 6> RetOps;
2098 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2099 // Operand #1 = Bytes To Pop
2100 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2103 // Copy the result values into the output registers.
2104 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2105 CCValAssign &VA = RVLocs[i];
2106 assert(VA.isRegLoc() && "Can only return in registers!");
2107 SDValue ValToCopy = OutVals[i];
2108 EVT ValVT = ValToCopy.getValueType();
2110 // Promote values to the appropriate types.
2111 if (VA.getLocInfo() == CCValAssign::SExt)
2112 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2113 else if (VA.getLocInfo() == CCValAssign::ZExt)
2114 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2115 else if (VA.getLocInfo() == CCValAssign::AExt) {
2116 if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2117 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2119 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2121 else if (VA.getLocInfo() == CCValAssign::BCvt)
2122 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2124 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2125 "Unexpected FP-extend for return value.");
2127 // If this is x86-64, and we disabled SSE, we can't return FP values,
2128 // or SSE or MMX vectors.
2129 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2130 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2131 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2132 report_fatal_error("SSE register return with SSE disabled");
2134 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2135 // llvm-gcc has never done it right and no one has noticed, so this
2136 // should be OK for now.
2137 if (ValVT == MVT::f64 &&
2138 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2139 report_fatal_error("SSE2 register return with SSE2 disabled");
2141 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2142 // the RET instruction and handled by the FP Stackifier.
2143 if (VA.getLocReg() == X86::FP0 ||
2144 VA.getLocReg() == X86::FP1) {
2145 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2146 // change the value to the FP stack register class.
2147 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2148 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2149 RetOps.push_back(ValToCopy);
2150 // Don't emit a copytoreg.
2154 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2155 // which is returned in RAX / RDX.
2156 if (Subtarget->is64Bit()) {
2157 if (ValVT == MVT::x86mmx) {
2158 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2159 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2160 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2162 // If we don't have SSE2 available, convert to v4f32 so the generated
2163 // register is legal.
2164 if (!Subtarget->hasSSE2())
2165 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2170 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2171 Flag = Chain.getValue(1);
2172 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2175 // All x86 ABIs require that for returning structs by value we copy
2176 // the sret argument into %rax/%eax (depending on ABI) for the return.
2177 // We saved the argument into a virtual register in the entry block,
2178 // so now we copy the value out and into %rax/%eax.
2180 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2181 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2182 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2183 // either case FuncInfo->setSRetReturnReg() will have been called.
2184 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2185 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2186 getPointerTy(MF.getDataLayout()));
2189 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2190 X86::RAX : X86::EAX;
2191 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2192 Flag = Chain.getValue(1);
2194 // RAX/EAX now acts like a return value.
2196 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2199 RetOps[0] = Chain; // Update chain.
2201 // Add the flag if we have it.
2203 RetOps.push_back(Flag);
2205 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2208 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2209 if (N->getNumValues() != 1)
2211 if (!N->hasNUsesOfValue(1, 0))
2214 SDValue TCChain = Chain;
2215 SDNode *Copy = *N->use_begin();
2216 if (Copy->getOpcode() == ISD::CopyToReg) {
2217 // If the copy has a glue operand, we conservatively assume it isn't safe to
2218 // perform a tail call.
2219 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2221 TCChain = Copy->getOperand(0);
2222 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2225 bool HasRet = false;
2226 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2228 if (UI->getOpcode() != X86ISD::RET_FLAG)
2230 // If we are returning more than one value, we can definitely
2231 // not make a tail call see PR19530
2232 if (UI->getNumOperands() > 4)
2234 if (UI->getNumOperands() == 4 &&
2235 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2248 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2249 ISD::NodeType ExtendKind) const {
2251 // TODO: Is this also valid on 32-bit?
2252 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2253 ReturnMVT = MVT::i8;
2255 ReturnMVT = MVT::i32;
2257 EVT MinVT = getRegisterType(Context, ReturnMVT);
2258 return VT.bitsLT(MinVT) ? MinVT : VT;
2261 /// Lower the result values of a call into the
2262 /// appropriate copies out of appropriate physical registers.
2265 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2266 CallingConv::ID CallConv, bool isVarArg,
2267 const SmallVectorImpl<ISD::InputArg> &Ins,
2268 SDLoc dl, SelectionDAG &DAG,
2269 SmallVectorImpl<SDValue> &InVals) const {
2271 // Assign locations to each value returned by this call.
2272 SmallVector<CCValAssign, 16> RVLocs;
2273 bool Is64Bit = Subtarget->is64Bit();
2274 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2276 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2278 // Copy all of the result registers out of their specified physreg.
2279 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2280 CCValAssign &VA = RVLocs[i];
2281 EVT CopyVT = VA.getLocVT();
2283 // If this is x86-64, and we disabled SSE, we can't return FP values
2284 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2285 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2286 report_fatal_error("SSE register return with SSE disabled");
2289 // If we prefer to use the value in xmm registers, copy it out as f80 and
2290 // use a truncate to move it from fp stack reg to xmm reg.
2291 bool RoundAfterCopy = false;
2292 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2293 isScalarFPTypeInSSEReg(VA.getValVT())) {
2295 RoundAfterCopy = (CopyVT != VA.getLocVT());
2298 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2299 CopyVT, InFlag).getValue(1);
2300 SDValue Val = Chain.getValue(0);
2303 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2304 // This truncation won't change the value.
2305 DAG.getIntPtrConstant(1, dl));
2307 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2308 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2310 InFlag = Chain.getValue(2);
2311 InVals.push_back(Val);
2317 //===----------------------------------------------------------------------===//
2318 // C & StdCall & Fast Calling Convention implementation
2319 //===----------------------------------------------------------------------===//
2320 // StdCall calling convention seems to be standard for many Windows' API
2321 // routines and around. It differs from C calling convention just a little:
2322 // callee should clean up the stack, not caller. Symbols should be also
2323 // decorated in some fancy way :) It doesn't support any vector arguments.
2324 // For info on fast calling convention see Fast Calling Convention (tail call)
2325 // implementation LowerX86_32FastCCCallTo.
2327 /// CallIsStructReturn - Determines whether a call uses struct return
2329 enum StructReturnType {
2334 static StructReturnType
2335 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2337 return NotStructReturn;
2339 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2340 if (!Flags.isSRet())
2341 return NotStructReturn;
2342 if (Flags.isInReg())
2343 return RegStructReturn;
2344 return StackStructReturn;
2347 /// Determines whether a function uses struct return semantics.
2348 static StructReturnType
2349 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2351 return NotStructReturn;
2353 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2354 if (!Flags.isSRet())
2355 return NotStructReturn;
2356 if (Flags.isInReg())
2357 return RegStructReturn;
2358 return StackStructReturn;
2361 /// Make a copy of an aggregate at address specified by "Src" to address
2362 /// "Dst" with size and alignment information specified by the specific
2363 /// parameter attribute. The copy will be passed as a byval function parameter.
2365 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2366 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2368 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2370 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2371 /*isVolatile*/false, /*AlwaysInline=*/true,
2372 /*isTailCall*/false,
2373 MachinePointerInfo(), MachinePointerInfo());
2376 /// Return true if the calling convention is one that
2377 /// supports tail call optimization.
2378 static bool IsTailCallConvention(CallingConv::ID CC) {
2379 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2380 CC == CallingConv::HiPE);
2383 /// \brief Return true if the calling convention is a C calling convention.
2384 static bool IsCCallConvention(CallingConv::ID CC) {
2385 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2386 CC == CallingConv::X86_64_SysV);
2389 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2391 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2392 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2396 CallingConv::ID CalleeCC = CS.getCallingConv();
2397 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2403 /// Return true if the function is being made into
2404 /// a tailcall target by changing its ABI.
2405 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2406 bool GuaranteedTailCallOpt) {
2407 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2411 X86TargetLowering::LowerMemArgument(SDValue Chain,
2412 CallingConv::ID CallConv,
2413 const SmallVectorImpl<ISD::InputArg> &Ins,
2414 SDLoc dl, SelectionDAG &DAG,
2415 const CCValAssign &VA,
2416 MachineFrameInfo *MFI,
2418 // Create the nodes corresponding to a load from this parameter slot.
2419 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2420 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2421 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2422 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2425 // If value is passed by pointer we have address passed instead of the value
2427 bool ExtendedInMem = VA.isExtInLoc() &&
2428 VA.getValVT().getScalarType() == MVT::i1;
2430 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2431 ValVT = VA.getLocVT();
2433 ValVT = VA.getValVT();
2435 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2436 // changed with more analysis.
2437 // In case of tail call optimization mark all arguments mutable. Since they
2438 // could be overwritten by lowering of arguments in case of a tail call.
2439 if (Flags.isByVal()) {
2440 unsigned Bytes = Flags.getByValSize();
2441 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2442 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2443 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2445 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2446 VA.getLocMemOffset(), isImmutable);
2447 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2448 SDValue Val = DAG.getLoad(
2449 ValVT, dl, Chain, FIN,
2450 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2452 return ExtendedInMem ?
2453 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2457 // FIXME: Get this from tablegen.
2458 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2459 const X86Subtarget *Subtarget) {
2460 assert(Subtarget->is64Bit());
2462 if (Subtarget->isCallingConvWin64(CallConv)) {
2463 static const MCPhysReg GPR64ArgRegsWin64[] = {
2464 X86::RCX, X86::RDX, X86::R8, X86::R9
2466 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2469 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2470 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2472 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2475 // FIXME: Get this from tablegen.
2476 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2477 CallingConv::ID CallConv,
2478 const X86Subtarget *Subtarget) {
2479 assert(Subtarget->is64Bit());
2480 if (Subtarget->isCallingConvWin64(CallConv)) {
2481 // The XMM registers which might contain var arg parameters are shadowed
2482 // in their paired GPR. So we only need to save the GPR to their home
2484 // TODO: __vectorcall will change this.
2488 const Function *Fn = MF.getFunction();
2489 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2490 bool isSoftFloat = Subtarget->useSoftFloat();
2491 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2492 "SSE register cannot be used when SSE is disabled!");
2493 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2494 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2498 static const MCPhysReg XMMArgRegs64Bit[] = {
2499 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2500 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2502 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2506 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2507 CallingConv::ID CallConv,
2509 const SmallVectorImpl<ISD::InputArg> &Ins,
2512 SmallVectorImpl<SDValue> &InVals)
2514 MachineFunction &MF = DAG.getMachineFunction();
2515 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2516 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2518 const Function* Fn = MF.getFunction();
2519 if (Fn->hasExternalLinkage() &&
2520 Subtarget->isTargetCygMing() &&
2521 Fn->getName() == "main")
2522 FuncInfo->setForceFramePointer(true);
2524 MachineFrameInfo *MFI = MF.getFrameInfo();
2525 bool Is64Bit = Subtarget->is64Bit();
2526 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2528 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2529 "Var args not supported with calling convention fastcc, ghc or hipe");
2531 // Assign locations to all of the incoming arguments.
2532 SmallVector<CCValAssign, 16> ArgLocs;
2533 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2535 // Allocate shadow area for Win64
2537 CCInfo.AllocateStack(32, 8);
2539 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2541 unsigned LastVal = ~0U;
2543 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2544 CCValAssign &VA = ArgLocs[i];
2545 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2547 assert(VA.getValNo() != LastVal &&
2548 "Don't support value assigned to multiple locs yet");
2550 LastVal = VA.getValNo();
2552 if (VA.isRegLoc()) {
2553 EVT RegVT = VA.getLocVT();
2554 const TargetRegisterClass *RC;
2555 if (RegVT == MVT::i32)
2556 RC = &X86::GR32RegClass;
2557 else if (Is64Bit && RegVT == MVT::i64)
2558 RC = &X86::GR64RegClass;
2559 else if (RegVT == MVT::f32)
2560 RC = &X86::FR32RegClass;
2561 else if (RegVT == MVT::f64)
2562 RC = &X86::FR64RegClass;
2563 else if (RegVT.is512BitVector())
2564 RC = &X86::VR512RegClass;
2565 else if (RegVT.is256BitVector())
2566 RC = &X86::VR256RegClass;
2567 else if (RegVT.is128BitVector())
2568 RC = &X86::VR128RegClass;
2569 else if (RegVT == MVT::x86mmx)
2570 RC = &X86::VR64RegClass;
2571 else if (RegVT == MVT::i1)
2572 RC = &X86::VK1RegClass;
2573 else if (RegVT == MVT::v8i1)
2574 RC = &X86::VK8RegClass;
2575 else if (RegVT == MVT::v16i1)
2576 RC = &X86::VK16RegClass;
2577 else if (RegVT == MVT::v32i1)
2578 RC = &X86::VK32RegClass;
2579 else if (RegVT == MVT::v64i1)
2580 RC = &X86::VK64RegClass;
2582 llvm_unreachable("Unknown argument type!");
2584 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2585 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2587 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2588 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2590 if (VA.getLocInfo() == CCValAssign::SExt)
2591 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2592 DAG.getValueType(VA.getValVT()));
2593 else if (VA.getLocInfo() == CCValAssign::ZExt)
2594 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2595 DAG.getValueType(VA.getValVT()));
2596 else if (VA.getLocInfo() == CCValAssign::BCvt)
2597 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2599 if (VA.isExtInLoc()) {
2600 // Handle MMX values passed in XMM regs.
2601 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2602 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2604 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2607 assert(VA.isMemLoc());
2608 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2611 // If value is passed via pointer - do a load.
2612 if (VA.getLocInfo() == CCValAssign::Indirect)
2613 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2614 MachinePointerInfo(), false, false, false, 0);
2616 InVals.push_back(ArgValue);
2619 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2620 // All x86 ABIs require that for returning structs by value we copy the
2621 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2622 // the argument into a virtual register so that we can access it from the
2624 if (Ins[i].Flags.isSRet()) {
2625 unsigned Reg = FuncInfo->getSRetReturnReg();
2627 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2628 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2629 FuncInfo->setSRetReturnReg(Reg);
2631 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2632 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2637 unsigned StackSize = CCInfo.getNextStackOffset();
2638 // Align stack specially for tail calls.
2639 if (FuncIsMadeTailCallSafe(CallConv,
2640 MF.getTarget().Options.GuaranteedTailCallOpt))
2641 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2643 // If the function takes variable number of arguments, make a frame index for
2644 // the start of the first vararg value... for expansion of llvm.va_start. We
2645 // can skip this if there are no va_start calls.
2646 if (MFI->hasVAStart() &&
2647 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2648 CallConv != CallingConv::X86_ThisCall))) {
2649 FuncInfo->setVarArgsFrameIndex(
2650 MFI->CreateFixedObject(1, StackSize, true));
2653 MachineModuleInfo &MMI = MF.getMMI();
2654 const Function *WinEHParent = nullptr;
2655 if (MMI.hasWinEHFuncInfo(Fn))
2656 WinEHParent = MMI.getWinEHParent(Fn);
2657 bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2658 bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2660 // Figure out if XMM registers are in use.
2661 assert(!(Subtarget->useSoftFloat() &&
2662 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2663 "SSE register cannot be used when SSE is disabled!");
2665 // 64-bit calling conventions support varargs and register parameters, so we
2666 // have to do extra work to spill them in the prologue.
2667 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2668 // Find the first unallocated argument registers.
2669 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2670 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2671 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2672 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2673 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2674 "SSE register cannot be used when SSE is disabled!");
2676 // Gather all the live in physical registers.
2677 SmallVector<SDValue, 6> LiveGPRs;
2678 SmallVector<SDValue, 8> LiveXMMRegs;
2680 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2681 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2683 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2685 if (!ArgXMMs.empty()) {
2686 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2687 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2688 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2689 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2690 LiveXMMRegs.push_back(
2691 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2696 // Get to the caller-allocated home save location. Add 8 to account
2697 // for the return address.
2698 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2699 FuncInfo->setRegSaveFrameIndex(
2700 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2701 // Fixup to set vararg frame on shadow area (4 x i64).
2703 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2705 // For X86-64, if there are vararg parameters that are passed via
2706 // registers, then we must store them to their spots on the stack so
2707 // they may be loaded by deferencing the result of va_next.
2708 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2709 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2710 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2711 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2714 // Store the integer parameter registers.
2715 SmallVector<SDValue, 8> MemOps;
2716 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2717 getPointerTy(DAG.getDataLayout()));
2718 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2719 for (SDValue Val : LiveGPRs) {
2720 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2721 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2723 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2724 MachinePointerInfo::getFixedStack(
2725 DAG.getMachineFunction(),
2726 FuncInfo->getRegSaveFrameIndex(), Offset),
2728 MemOps.push_back(Store);
2732 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2733 // Now store the XMM (fp + vector) parameter registers.
2734 SmallVector<SDValue, 12> SaveXMMOps;
2735 SaveXMMOps.push_back(Chain);
2736 SaveXMMOps.push_back(ALVal);
2737 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2738 FuncInfo->getRegSaveFrameIndex(), dl));
2739 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2740 FuncInfo->getVarArgsFPOffset(), dl));
2741 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2743 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2744 MVT::Other, SaveXMMOps));
2747 if (!MemOps.empty())
2748 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2749 } else if (IsWin64 && IsWinEHOutlined) {
2750 // Get to the caller-allocated home save location. Add 8 to account
2751 // for the return address.
2752 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2753 FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2754 /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2756 MMI.getWinEHFuncInfo(Fn)
2757 .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2758 FuncInfo->getRegSaveFrameIndex();
2760 // Store the second integer parameter (rdx) into rsp+16 relative to the
2761 // stack pointer at the entry of the function.
2762 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2763 getPointerTy(DAG.getDataLayout()));
2764 unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2765 SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2766 Chain = DAG.getStore(
2767 Val.getValue(1), dl, Val, RSFIN,
2768 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2769 FuncInfo->getRegSaveFrameIndex()),
2770 /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2773 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2774 // Find the largest legal vector type.
2775 MVT VecVT = MVT::Other;
2776 // FIXME: Only some x86_32 calling conventions support AVX512.
2777 if (Subtarget->hasAVX512() &&
2778 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2779 CallConv == CallingConv::Intel_OCL_BI)))
2780 VecVT = MVT::v16f32;
2781 else if (Subtarget->hasAVX())
2783 else if (Subtarget->hasSSE2())
2786 // We forward some GPRs and some vector types.
2787 SmallVector<MVT, 2> RegParmTypes;
2788 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2789 RegParmTypes.push_back(IntVT);
2790 if (VecVT != MVT::Other)
2791 RegParmTypes.push_back(VecVT);
2793 // Compute the set of forwarded registers. The rest are scratch.
2794 SmallVectorImpl<ForwardedRegister> &Forwards =
2795 FuncInfo->getForwardedMustTailRegParms();
2796 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2798 // Conservatively forward AL on x86_64, since it might be used for varargs.
2799 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2800 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2801 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2804 // Copy all forwards from physical to virtual registers.
2805 for (ForwardedRegister &F : Forwards) {
2806 // FIXME: Can we use a less constrained schedule?
2807 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2808 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2809 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2813 // Some CCs need callee pop.
2814 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2815 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2816 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2818 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2819 // If this is an sret function, the return should pop the hidden pointer.
2820 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2821 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2822 argsAreStructReturn(Ins) == StackStructReturn)
2823 FuncInfo->setBytesToPopOnReturn(4);
2827 // RegSaveFrameIndex is X86-64 only.
2828 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2829 if (CallConv == CallingConv::X86_FastCall ||
2830 CallConv == CallingConv::X86_ThisCall)
2831 // fastcc functions can't have varargs.
2832 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2835 FuncInfo->setArgumentStackSize(StackSize);
2837 if (IsWinEHParent) {
2839 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2840 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2841 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2842 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2843 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2844 MachinePointerInfo::getFixedStack(
2845 DAG.getMachineFunction(), UnwindHelpFI),
2846 /*isVolatile=*/true,
2847 /*isNonTemporal=*/false, /*Alignment=*/0);
2849 // Functions using Win32 EH are considered to have opaque SP adjustments
2850 // to force local variables to be addressed from the frame or base
2852 MFI->setHasOpaqueSPAdjustment(true);
2860 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2861 SDValue StackPtr, SDValue Arg,
2862 SDLoc dl, SelectionDAG &DAG,
2863 const CCValAssign &VA,
2864 ISD::ArgFlagsTy Flags) const {
2865 unsigned LocMemOffset = VA.getLocMemOffset();
2866 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2867 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2869 if (Flags.isByVal())
2870 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2872 return DAG.getStore(
2873 Chain, dl, Arg, PtrOff,
2874 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2878 /// Emit a load of return address if tail call
2879 /// optimization is performed and it is required.
2881 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2882 SDValue &OutRetAddr, SDValue Chain,
2883 bool IsTailCall, bool Is64Bit,
2884 int FPDiff, SDLoc dl) const {
2885 // Adjust the Return address stack slot.
2886 EVT VT = getPointerTy(DAG.getDataLayout());
2887 OutRetAddr = getReturnAddressFrameIndex(DAG);
2889 // Load the "old" Return address.
2890 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2891 false, false, false, 0);
2892 return SDValue(OutRetAddr.getNode(), 1);
2895 /// Emit a store of the return address if tail call
2896 /// optimization is performed and it is required (FPDiff!=0).
2897 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2898 SDValue Chain, SDValue RetAddrFrIdx,
2899 EVT PtrVT, unsigned SlotSize,
2900 int FPDiff, SDLoc dl) {
2901 // Store the return address to the appropriate stack slot.
2902 if (!FPDiff) return Chain;
2903 // Calculate the new stack slot for the return address.
2904 int NewReturnAddrFI =
2905 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2907 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2908 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2909 MachinePointerInfo::getFixedStack(
2910 DAG.getMachineFunction(), NewReturnAddrFI),
2915 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2916 /// operation of specified width.
2917 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2919 unsigned NumElems = VT.getVectorNumElements();
2920 SmallVector<int, 8> Mask;
2921 Mask.push_back(NumElems);
2922 for (unsigned i = 1; i != NumElems; ++i)
2924 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2928 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2929 SmallVectorImpl<SDValue> &InVals) const {
2930 SelectionDAG &DAG = CLI.DAG;
2932 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2933 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2934 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2935 SDValue Chain = CLI.Chain;
2936 SDValue Callee = CLI.Callee;
2937 CallingConv::ID CallConv = CLI.CallConv;
2938 bool &isTailCall = CLI.IsTailCall;
2939 bool isVarArg = CLI.IsVarArg;
2941 MachineFunction &MF = DAG.getMachineFunction();
2942 bool Is64Bit = Subtarget->is64Bit();
2943 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2944 StructReturnType SR = callIsStructReturn(Outs);
2945 bool IsSibcall = false;
2946 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2947 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2949 if (Attr.getValueAsString() == "true")
2952 if (Subtarget->isPICStyleGOT() &&
2953 !MF.getTarget().Options.GuaranteedTailCallOpt) {
2954 // If we are using a GOT, disable tail calls to external symbols with
2955 // default visibility. Tail calling such a symbol requires using a GOT
2956 // relocation, which forces early binding of the symbol. This breaks code
2957 // that require lazy function symbol resolution. Using musttail or
2958 // GuaranteedTailCallOpt will override this.
2959 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2960 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2961 G->getGlobal()->hasDefaultVisibility()))
2965 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2967 // Force this to be a tail call. The verifier rules are enough to ensure
2968 // that we can lower this successfully without moving the return address
2971 } else if (isTailCall) {
2972 // Check if it's really possible to do a tail call.
2973 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2974 isVarArg, SR != NotStructReturn,
2975 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2976 Outs, OutVals, Ins, DAG);
2978 // Sibcalls are automatically detected tailcalls which do not require
2980 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2987 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2988 "Var args not supported with calling convention fastcc, ghc or hipe");
2990 // Analyze operands of the call, assigning locations to each operand.
2991 SmallVector<CCValAssign, 16> ArgLocs;
2992 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2994 // Allocate shadow area for Win64
2996 CCInfo.AllocateStack(32, 8);
2998 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3000 // Get a count of how many bytes are to be pushed on the stack.
3001 unsigned NumBytes = CCInfo.getNextStackOffset();
3003 // This is a sibcall. The memory operands are available in caller's
3004 // own caller's stack.
3006 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3007 IsTailCallConvention(CallConv))
3008 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3011 if (isTailCall && !IsSibcall && !IsMustTail) {
3012 // Lower arguments at fp - stackoffset + fpdiff.
3013 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3015 FPDiff = NumBytesCallerPushed - NumBytes;
3017 // Set the delta of movement of the returnaddr stackslot.
3018 // But only set if delta is greater than previous delta.
3019 if (FPDiff < X86Info->getTCReturnAddrDelta())
3020 X86Info->setTCReturnAddrDelta(FPDiff);
3023 unsigned NumBytesToPush = NumBytes;
3024 unsigned NumBytesToPop = NumBytes;
3026 // If we have an inalloca argument, all stack space has already been allocated
3027 // for us and be right at the top of the stack. We don't support multiple
3028 // arguments passed in memory when using inalloca.
3029 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3031 if (!ArgLocs.back().isMemLoc())
3032 report_fatal_error("cannot use inalloca attribute on a register "
3034 if (ArgLocs.back().getLocMemOffset() != 0)
3035 report_fatal_error("any parameter with the inalloca attribute must be "
3036 "the only memory argument");
3040 Chain = DAG.getCALLSEQ_START(
3041 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3043 SDValue RetAddrFrIdx;
3044 // Load return address for tail calls.
3045 if (isTailCall && FPDiff)
3046 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3047 Is64Bit, FPDiff, dl);
3049 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3050 SmallVector<SDValue, 8> MemOpChains;
3053 // Walk the register/memloc assignments, inserting copies/loads. In the case
3054 // of tail call optimization arguments are handle later.
3055 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3056 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3057 // Skip inalloca arguments, they have already been written.
3058 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3059 if (Flags.isInAlloca())
3062 CCValAssign &VA = ArgLocs[i];
3063 EVT RegVT = VA.getLocVT();
3064 SDValue Arg = OutVals[i];
3065 bool isByVal = Flags.isByVal();
3067 // Promote the value if needed.
3068 switch (VA.getLocInfo()) {
3069 default: llvm_unreachable("Unknown loc info!");
3070 case CCValAssign::Full: break;
3071 case CCValAssign::SExt:
3072 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3074 case CCValAssign::ZExt:
3075 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3077 case CCValAssign::AExt:
3078 if (Arg.getValueType().isVector() &&
3079 Arg.getValueType().getScalarType() == MVT::i1)
3080 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3081 else if (RegVT.is128BitVector()) {
3082 // Special case: passing MMX values in XMM registers.
3083 Arg = DAG.getBitcast(MVT::i64, Arg);
3084 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3085 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3087 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3089 case CCValAssign::BCvt:
3090 Arg = DAG.getBitcast(RegVT, Arg);
3092 case CCValAssign::Indirect: {
3093 // Store the argument.
3094 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3095 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3096 Chain = DAG.getStore(
3097 Chain, dl, Arg, SpillSlot,
3098 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3105 if (VA.isRegLoc()) {
3106 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3107 if (isVarArg && IsWin64) {
3108 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3109 // shadow reg if callee is a varargs function.
3110 unsigned ShadowReg = 0;
3111 switch (VA.getLocReg()) {
3112 case X86::XMM0: ShadowReg = X86::RCX; break;
3113 case X86::XMM1: ShadowReg = X86::RDX; break;
3114 case X86::XMM2: ShadowReg = X86::R8; break;
3115 case X86::XMM3: ShadowReg = X86::R9; break;
3118 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3120 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3121 assert(VA.isMemLoc());
3122 if (!StackPtr.getNode())
3123 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3124 getPointerTy(DAG.getDataLayout()));
3125 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3126 dl, DAG, VA, Flags));
3130 if (!MemOpChains.empty())
3131 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3133 if (Subtarget->isPICStyleGOT()) {
3134 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3137 RegsToPass.push_back(std::make_pair(
3138 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3139 getPointerTy(DAG.getDataLayout()))));
3141 // If we are tail calling and generating PIC/GOT style code load the
3142 // address of the callee into ECX. The value in ecx is used as target of
3143 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3144 // for tail calls on PIC/GOT architectures. Normally we would just put the
3145 // address of GOT into ebx and then call target@PLT. But for tail calls
3146 // ebx would be restored (since ebx is callee saved) before jumping to the
3149 // Note: The actual moving to ECX is done further down.
3150 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3151 if (G && !G->getGlobal()->hasLocalLinkage() &&
3152 G->getGlobal()->hasDefaultVisibility())
3153 Callee = LowerGlobalAddress(Callee, DAG);
3154 else if (isa<ExternalSymbolSDNode>(Callee))
3155 Callee = LowerExternalSymbol(Callee, DAG);
3159 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3160 // From AMD64 ABI document:
3161 // For calls that may call functions that use varargs or stdargs
3162 // (prototype-less calls or calls to functions containing ellipsis (...) in
3163 // the declaration) %al is used as hidden argument to specify the number
3164 // of SSE registers used. The contents of %al do not need to match exactly
3165 // the number of registers, but must be an ubound on the number of SSE
3166 // registers used and is in the range 0 - 8 inclusive.
3168 // Count the number of XMM registers allocated.
3169 static const MCPhysReg XMMArgRegs[] = {
3170 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3171 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3173 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3174 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3175 && "SSE registers cannot be used when SSE is disabled");
3177 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3178 DAG.getConstant(NumXMMRegs, dl,
3182 if (isVarArg && IsMustTail) {
3183 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3184 for (const auto &F : Forwards) {
3185 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3186 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3190 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3191 // don't need this because the eligibility check rejects calls that require
3192 // shuffling arguments passed in memory.
3193 if (!IsSibcall && isTailCall) {
3194 // Force all the incoming stack arguments to be loaded from the stack
3195 // before any new outgoing arguments are stored to the stack, because the
3196 // outgoing stack slots may alias the incoming argument stack slots, and
3197 // the alias isn't otherwise explicit. This is slightly more conservative
3198 // than necessary, because it means that each store effectively depends
3199 // on every argument instead of just those arguments it would clobber.
3200 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3202 SmallVector<SDValue, 8> MemOpChains2;
3205 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3206 CCValAssign &VA = ArgLocs[i];
3209 assert(VA.isMemLoc());
3210 SDValue Arg = OutVals[i];
3211 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3212 // Skip inalloca arguments. They don't require any work.
3213 if (Flags.isInAlloca())
3215 // Create frame index.
3216 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3217 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3218 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3219 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3221 if (Flags.isByVal()) {
3222 // Copy relative to framepointer.
3223 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3224 if (!StackPtr.getNode())
3225 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3226 getPointerTy(DAG.getDataLayout()));
3227 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3230 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3234 // Store relative to framepointer.
3235 MemOpChains2.push_back(DAG.getStore(
3236 ArgChain, dl, Arg, FIN,
3237 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3242 if (!MemOpChains2.empty())
3243 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3245 // Store the return address to the appropriate stack slot.
3246 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3247 getPointerTy(DAG.getDataLayout()),
3248 RegInfo->getSlotSize(), FPDiff, dl);
3251 // Build a sequence of copy-to-reg nodes chained together with token chain
3252 // and flag operands which copy the outgoing args into registers.
3254 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3255 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3256 RegsToPass[i].second, InFlag);
3257 InFlag = Chain.getValue(1);
3260 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3261 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3262 // In the 64-bit large code model, we have to make all calls
3263 // through a register, since the call instruction's 32-bit
3264 // pc-relative offset may not be large enough to hold the whole
3266 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3267 // If the callee is a GlobalAddress node (quite common, every direct call
3268 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3270 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3272 // We should use extra load for direct calls to dllimported functions in
3274 const GlobalValue *GV = G->getGlobal();
3275 if (!GV->hasDLLImportStorageClass()) {
3276 unsigned char OpFlags = 0;
3277 bool ExtraLoad = false;
3278 unsigned WrapperKind = ISD::DELETED_NODE;
3280 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3281 // external symbols most go through the PLT in PIC mode. If the symbol
3282 // has hidden or protected visibility, or if it is static or local, then
3283 // we don't need to use the PLT - we can directly call it.
3284 if (Subtarget->isTargetELF() &&
3285 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3286 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3287 OpFlags = X86II::MO_PLT;
3288 } else if (Subtarget->isPICStyleStubAny() &&
3289 !GV->isStrongDefinitionForLinker() &&
3290 (!Subtarget->getTargetTriple().isMacOSX() ||
3291 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3292 // PC-relative references to external symbols should go through $stub,
3293 // unless we're building with the leopard linker or later, which
3294 // automatically synthesizes these stubs.
3295 OpFlags = X86II::MO_DARWIN_STUB;
3296 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3297 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3298 // If the function is marked as non-lazy, generate an indirect call
3299 // which loads from the GOT directly. This avoids runtime overhead
3300 // at the cost of eager binding (and one extra byte of encoding).
3301 OpFlags = X86II::MO_GOTPCREL;
3302 WrapperKind = X86ISD::WrapperRIP;
3306 Callee = DAG.getTargetGlobalAddress(
3307 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3309 // Add a wrapper if needed.
3310 if (WrapperKind != ISD::DELETED_NODE)
3311 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3312 getPointerTy(DAG.getDataLayout()), Callee);
3313 // Add extra indirection if needed.
3315 Callee = DAG.getLoad(
3316 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3317 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3320 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3321 unsigned char OpFlags = 0;
3323 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3324 // external symbols should go through the PLT.
3325 if (Subtarget->isTargetELF() &&
3326 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3327 OpFlags = X86II::MO_PLT;
3328 } else if (Subtarget->isPICStyleStubAny() &&
3329 (!Subtarget->getTargetTriple().isMacOSX() ||
3330 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3331 // PC-relative references to external symbols should go through $stub,
3332 // unless we're building with the leopard linker or later, which
3333 // automatically synthesizes these stubs.
3334 OpFlags = X86II::MO_DARWIN_STUB;
3337 Callee = DAG.getTargetExternalSymbol(
3338 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3339 } else if (Subtarget->isTarget64BitILP32() &&
3340 Callee->getValueType(0) == MVT::i32) {
3341 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3342 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3345 // Returns a chain & a flag for retval copy to use.
3346 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3347 SmallVector<SDValue, 8> Ops;
3349 if (!IsSibcall && isTailCall) {
3350 Chain = DAG.getCALLSEQ_END(Chain,
3351 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3352 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3353 InFlag = Chain.getValue(1);
3356 Ops.push_back(Chain);
3357 Ops.push_back(Callee);
3360 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3362 // Add argument registers to the end of the list so that they are known live
3364 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3365 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3366 RegsToPass[i].second.getValueType()));
3368 // Add a register mask operand representing the call-preserved registers.
3369 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3370 assert(Mask && "Missing call preserved mask for calling convention");
3372 // If this is an invoke in a 32-bit function using an MSVC personality, assume
3373 // the function clobbers all registers. If an exception is thrown, the runtime
3374 // will not restore CSRs.
3375 // FIXME: Model this more precisely so that we can register allocate across
3376 // the normal edge and spill and fill across the exceptional edge.
3377 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3378 const Function *CallerFn = MF.getFunction();
3379 EHPersonality Pers =
3380 CallerFn->hasPersonalityFn()
3381 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3382 : EHPersonality::Unknown;
3383 if (isMSVCEHPersonality(Pers))
3384 Mask = RegInfo->getNoPreservedMask();
3387 Ops.push_back(DAG.getRegisterMask(Mask));
3389 if (InFlag.getNode())
3390 Ops.push_back(InFlag);
3394 //// If this is the first return lowered for this function, add the regs
3395 //// to the liveout set for the function.
3396 // This isn't right, although it's probably harmless on x86; liveouts
3397 // should be computed from returns not tail calls. Consider a void
3398 // function making a tail call to a function returning int.
3399 MF.getFrameInfo()->setHasTailCall();
3400 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3403 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3404 InFlag = Chain.getValue(1);
3406 // Create the CALLSEQ_END node.
3407 unsigned NumBytesForCalleeToPop;
3408 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3409 DAG.getTarget().Options.GuaranteedTailCallOpt))
3410 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3411 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3412 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3413 SR == StackStructReturn)
3414 // If this is a call to a struct-return function, the callee
3415 // pops the hidden struct pointer, so we have to push it back.
3416 // This is common for Darwin/X86, Linux & Mingw32 targets.
3417 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3418 NumBytesForCalleeToPop = 4;
3420 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3422 // Returns a flag for retval copy to use.
3424 Chain = DAG.getCALLSEQ_END(Chain,
3425 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3426 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3429 InFlag = Chain.getValue(1);
3432 // Handle result values, copying them out of physregs into vregs that we
3434 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3435 Ins, dl, DAG, InVals);
3438 //===----------------------------------------------------------------------===//
3439 // Fast Calling Convention (tail call) implementation
3440 //===----------------------------------------------------------------------===//
3442 // Like std call, callee cleans arguments, convention except that ECX is
3443 // reserved for storing the tail called function address. Only 2 registers are
3444 // free for argument passing (inreg). Tail call optimization is performed
3446 // * tailcallopt is enabled
3447 // * caller/callee are fastcc
3448 // On X86_64 architecture with GOT-style position independent code only local
3449 // (within module) calls are supported at the moment.
3450 // To keep the stack aligned according to platform abi the function
3451 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3452 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3453 // If a tail called function callee has more arguments than the caller the
3454 // caller needs to make sure that there is room to move the RETADDR to. This is
3455 // achieved by reserving an area the size of the argument delta right after the
3456 // original RETADDR, but before the saved framepointer or the spilled registers
3457 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3469 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3472 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3473 SelectionDAG& DAG) const {
3474 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3475 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3476 unsigned StackAlignment = TFI.getStackAlignment();
3477 uint64_t AlignMask = StackAlignment - 1;
3478 int64_t Offset = StackSize;
3479 unsigned SlotSize = RegInfo->getSlotSize();
3480 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3481 // Number smaller than 12 so just add the difference.
3482 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3484 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3485 Offset = ((~AlignMask) & Offset) + StackAlignment +
3486 (StackAlignment-SlotSize);
3491 /// Return true if the given stack call argument is already available in the
3492 /// same position (relatively) of the caller's incoming argument stack.
3494 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3495 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3496 const X86InstrInfo *TII) {
3497 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3499 if (Arg.getOpcode() == ISD::CopyFromReg) {
3500 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3501 if (!TargetRegisterInfo::isVirtualRegister(VR))
3503 MachineInstr *Def = MRI->getVRegDef(VR);
3506 if (!Flags.isByVal()) {
3507 if (!TII->isLoadFromStackSlot(Def, FI))
3510 unsigned Opcode = Def->getOpcode();
3511 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3512 Opcode == X86::LEA64_32r) &&
3513 Def->getOperand(1).isFI()) {
3514 FI = Def->getOperand(1).getIndex();
3515 Bytes = Flags.getByValSize();
3519 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3520 if (Flags.isByVal())
3521 // ByVal argument is passed in as a pointer but it's now being
3522 // dereferenced. e.g.
3523 // define @foo(%struct.X* %A) {
3524 // tail call @bar(%struct.X* byval %A)
3527 SDValue Ptr = Ld->getBasePtr();
3528 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3531 FI = FINode->getIndex();
3532 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3533 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3534 FI = FINode->getIndex();
3535 Bytes = Flags.getByValSize();
3539 assert(FI != INT_MAX);
3540 if (!MFI->isFixedObjectIndex(FI))
3542 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3545 /// Check whether the call is eligible for tail call optimization. Targets
3546 /// that want to do tail call optimization should implement this function.
3548 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3549 CallingConv::ID CalleeCC,
3551 bool isCalleeStructRet,
3552 bool isCallerStructRet,
3554 const SmallVectorImpl<ISD::OutputArg> &Outs,
3555 const SmallVectorImpl<SDValue> &OutVals,
3556 const SmallVectorImpl<ISD::InputArg> &Ins,
3557 SelectionDAG &DAG) const {
3558 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3561 // If -tailcallopt is specified, make fastcc functions tail-callable.
3562 const MachineFunction &MF = DAG.getMachineFunction();
3563 const Function *CallerF = MF.getFunction();
3565 // If the function return type is x86_fp80 and the callee return type is not,
3566 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3567 // perform a tailcall optimization here.
3568 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3571 CallingConv::ID CallerCC = CallerF->getCallingConv();
3572 bool CCMatch = CallerCC == CalleeCC;
3573 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3574 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3576 // Win64 functions have extra shadow space for argument homing. Don't do the
3577 // sibcall if the caller and callee have mismatched expectations for this
3579 if (IsCalleeWin64 != IsCallerWin64)
3582 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3583 if (IsTailCallConvention(CalleeCC) && CCMatch)
3588 // Look for obvious safe cases to perform tail call optimization that do not
3589 // require ABI changes. This is what gcc calls sibcall.
3591 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3592 // emit a special epilogue.
3593 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3594 if (RegInfo->needsStackRealignment(MF))
3597 // Also avoid sibcall optimization if either caller or callee uses struct
3598 // return semantics.
3599 if (isCalleeStructRet || isCallerStructRet)
3602 // An stdcall/thiscall caller is expected to clean up its arguments; the
3603 // callee isn't going to do that.
3604 // FIXME: this is more restrictive than needed. We could produce a tailcall
3605 // when the stack adjustment matches. For example, with a thiscall that takes
3606 // only one argument.
3607 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3608 CallerCC == CallingConv::X86_ThisCall))
3611 // Do not sibcall optimize vararg calls unless all arguments are passed via
3613 if (isVarArg && !Outs.empty()) {
3615 // Optimizing for varargs on Win64 is unlikely to be safe without
3616 // additional testing.
3617 if (IsCalleeWin64 || IsCallerWin64)
3620 SmallVector<CCValAssign, 16> ArgLocs;
3621 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3624 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3625 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3626 if (!ArgLocs[i].isRegLoc())
3630 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3631 // stack. Therefore, if it's not used by the call it is not safe to optimize
3632 // this into a sibcall.
3633 bool Unused = false;
3634 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3641 SmallVector<CCValAssign, 16> RVLocs;
3642 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3644 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3645 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3646 CCValAssign &VA = RVLocs[i];
3647 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3652 // If the calling conventions do not match, then we'd better make sure the
3653 // results are returned in the same way as what the caller expects.
3655 SmallVector<CCValAssign, 16> RVLocs1;
3656 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3658 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3660 SmallVector<CCValAssign, 16> RVLocs2;
3661 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3663 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3665 if (RVLocs1.size() != RVLocs2.size())
3667 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3668 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3670 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3672 if (RVLocs1[i].isRegLoc()) {
3673 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3676 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3682 // If the callee takes no arguments then go on to check the results of the
3684 if (!Outs.empty()) {
3685 // Check if stack adjustment is needed. For now, do not do this if any
3686 // argument is passed on the stack.
3687 SmallVector<CCValAssign, 16> ArgLocs;
3688 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3691 // Allocate shadow area for Win64
3693 CCInfo.AllocateStack(32, 8);
3695 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3696 if (CCInfo.getNextStackOffset()) {
3697 MachineFunction &MF = DAG.getMachineFunction();
3698 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3701 // Check if the arguments are already laid out in the right way as
3702 // the caller's fixed stack objects.
3703 MachineFrameInfo *MFI = MF.getFrameInfo();
3704 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3705 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3706 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3707 CCValAssign &VA = ArgLocs[i];
3708 SDValue Arg = OutVals[i];
3709 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3710 if (VA.getLocInfo() == CCValAssign::Indirect)
3712 if (!VA.isRegLoc()) {
3713 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3720 // If the tailcall address may be in a register, then make sure it's
3721 // possible to register allocate for it. In 32-bit, the call address can
3722 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3723 // callee-saved registers are restored. These happen to be the same
3724 // registers used to pass 'inreg' arguments so watch out for those.
3725 if (!Subtarget->is64Bit() &&
3726 ((!isa<GlobalAddressSDNode>(Callee) &&
3727 !isa<ExternalSymbolSDNode>(Callee)) ||
3728 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3729 unsigned NumInRegs = 0;
3730 // In PIC we need an extra register to formulate the address computation
3732 unsigned MaxInRegs =
3733 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3735 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3736 CCValAssign &VA = ArgLocs[i];
3739 unsigned Reg = VA.getLocReg();
3742 case X86::EAX: case X86::EDX: case X86::ECX:
3743 if (++NumInRegs == MaxInRegs)
3755 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3756 const TargetLibraryInfo *libInfo) const {
3757 return X86::createFastISel(funcInfo, libInfo);
3760 //===----------------------------------------------------------------------===//
3761 // Other Lowering Hooks
3762 //===----------------------------------------------------------------------===//
3764 static bool MayFoldLoad(SDValue Op) {
3765 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3768 static bool MayFoldIntoStore(SDValue Op) {
3769 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3772 static bool isTargetShuffle(unsigned Opcode) {
3774 default: return false;
3775 case X86ISD::BLENDI:
3776 case X86ISD::PSHUFB:
3777 case X86ISD::PSHUFD:
3778 case X86ISD::PSHUFHW:
3779 case X86ISD::PSHUFLW:
3781 case X86ISD::PALIGNR:
3782 case X86ISD::MOVLHPS:
3783 case X86ISD::MOVLHPD:
3784 case X86ISD::MOVHLPS:
3785 case X86ISD::MOVLPS:
3786 case X86ISD::MOVLPD:
3787 case X86ISD::MOVSHDUP:
3788 case X86ISD::MOVSLDUP:
3789 case X86ISD::MOVDDUP:
3792 case X86ISD::UNPCKL:
3793 case X86ISD::UNPCKH:
3794 case X86ISD::VPERMILPI:
3795 case X86ISD::VPERM2X128:
3796 case X86ISD::VPERMI:
3801 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3802 SDValue V1, unsigned TargetMask,
3803 SelectionDAG &DAG) {
3805 default: llvm_unreachable("Unknown x86 shuffle node");
3806 case X86ISD::PSHUFD:
3807 case X86ISD::PSHUFHW:
3808 case X86ISD::PSHUFLW:
3809 case X86ISD::VPERMILPI:
3810 case X86ISD::VPERMI:
3811 return DAG.getNode(Opc, dl, VT, V1,
3812 DAG.getConstant(TargetMask, dl, MVT::i8));
3816 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3817 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3819 default: llvm_unreachable("Unknown x86 shuffle node");
3820 case X86ISD::MOVLHPS:
3821 case X86ISD::MOVLHPD:
3822 case X86ISD::MOVHLPS:
3823 case X86ISD::MOVLPS:
3824 case X86ISD::MOVLPD:
3827 case X86ISD::UNPCKL:
3828 case X86ISD::UNPCKH:
3829 return DAG.getNode(Opc, dl, VT, V1, V2);
3833 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3834 MachineFunction &MF = DAG.getMachineFunction();
3835 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3836 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3837 int ReturnAddrIndex = FuncInfo->getRAIndex();
3839 if (ReturnAddrIndex == 0) {
3840 // Set up a frame object for the return address.
3841 unsigned SlotSize = RegInfo->getSlotSize();
3842 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3845 FuncInfo->setRAIndex(ReturnAddrIndex);
3848 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3851 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3852 bool hasSymbolicDisplacement) {
3853 // Offset should fit into 32 bit immediate field.
3854 if (!isInt<32>(Offset))
3857 // If we don't have a symbolic displacement - we don't have any extra
3859 if (!hasSymbolicDisplacement)
3862 // FIXME: Some tweaks might be needed for medium code model.
3863 if (M != CodeModel::Small && M != CodeModel::Kernel)
3866 // For small code model we assume that latest object is 16MB before end of 31
3867 // bits boundary. We may also accept pretty large negative constants knowing
3868 // that all objects are in the positive half of address space.
3869 if (M == CodeModel::Small && Offset < 16*1024*1024)
3872 // For kernel code model we know that all object resist in the negative half
3873 // of 32bits address space. We may not accept negative offsets, since they may
3874 // be just off and we may accept pretty large positive ones.
3875 if (M == CodeModel::Kernel && Offset >= 0)
3881 /// Determines whether the callee is required to pop its own arguments.
3882 /// Callee pop is necessary to support tail calls.
3883 bool X86::isCalleePop(CallingConv::ID CallingConv,
3884 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3885 switch (CallingConv) {
3888 case CallingConv::X86_StdCall:
3889 case CallingConv::X86_FastCall:
3890 case CallingConv::X86_ThisCall:
3892 case CallingConv::Fast:
3893 case CallingConv::GHC:
3894 case CallingConv::HiPE:
3901 /// \brief Return true if the condition is an unsigned comparison operation.
3902 static bool isX86CCUnsigned(unsigned X86CC) {
3904 default: llvm_unreachable("Invalid integer condition!");
3905 case X86::COND_E: return true;
3906 case X86::COND_G: return false;
3907 case X86::COND_GE: return false;
3908 case X86::COND_L: return false;
3909 case X86::COND_LE: return false;
3910 case X86::COND_NE: return true;
3911 case X86::COND_B: return true;
3912 case X86::COND_A: return true;
3913 case X86::COND_BE: return true;
3914 case X86::COND_AE: return true;
3916 llvm_unreachable("covered switch fell through?!");
3919 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3920 /// condition code, returning the condition code and the LHS/RHS of the
3921 /// comparison to make.
3922 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3923 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3925 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3926 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3927 // X > -1 -> X == 0, jump !sign.
3928 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3929 return X86::COND_NS;
3931 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3932 // X < 0 -> X == 0, jump on sign.
3935 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3937 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3938 return X86::COND_LE;
3942 switch (SetCCOpcode) {
3943 default: llvm_unreachable("Invalid integer condition!");
3944 case ISD::SETEQ: return X86::COND_E;
3945 case ISD::SETGT: return X86::COND_G;
3946 case ISD::SETGE: return X86::COND_GE;
3947 case ISD::SETLT: return X86::COND_L;
3948 case ISD::SETLE: return X86::COND_LE;
3949 case ISD::SETNE: return X86::COND_NE;
3950 case ISD::SETULT: return X86::COND_B;
3951 case ISD::SETUGT: return X86::COND_A;
3952 case ISD::SETULE: return X86::COND_BE;
3953 case ISD::SETUGE: return X86::COND_AE;
3957 // First determine if it is required or is profitable to flip the operands.
3959 // If LHS is a foldable load, but RHS is not, flip the condition.
3960 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3961 !ISD::isNON_EXTLoad(RHS.getNode())) {
3962 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3963 std::swap(LHS, RHS);
3966 switch (SetCCOpcode) {
3972 std::swap(LHS, RHS);
3976 // On a floating point condition, the flags are set as follows:
3978 // 0 | 0 | 0 | X > Y
3979 // 0 | 0 | 1 | X < Y
3980 // 1 | 0 | 0 | X == Y
3981 // 1 | 1 | 1 | unordered
3982 switch (SetCCOpcode) {
3983 default: llvm_unreachable("Condcode should be pre-legalized away");
3985 case ISD::SETEQ: return X86::COND_E;
3986 case ISD::SETOLT: // flipped
3988 case ISD::SETGT: return X86::COND_A;
3989 case ISD::SETOLE: // flipped
3991 case ISD::SETGE: return X86::COND_AE;
3992 case ISD::SETUGT: // flipped
3994 case ISD::SETLT: return X86::COND_B;
3995 case ISD::SETUGE: // flipped
3997 case ISD::SETLE: return X86::COND_BE;
3999 case ISD::SETNE: return X86::COND_NE;
4000 case ISD::SETUO: return X86::COND_P;
4001 case ISD::SETO: return X86::COND_NP;
4003 case ISD::SETUNE: return X86::COND_INVALID;
4007 /// Is there a floating point cmov for the specific X86 condition code?
4008 /// Current x86 isa includes the following FP cmov instructions:
4009 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4010 static bool hasFPCMov(unsigned X86CC) {
4026 /// Returns true if the target can instruction select the
4027 /// specified FP immediate natively. If false, the legalizer will
4028 /// materialize the FP immediate as a load from a constant pool.
4029 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4030 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4031 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4037 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4038 ISD::LoadExtType ExtTy,
4040 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4041 // relocation target a movq or addq instruction: don't let the load shrink.
4042 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4043 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4044 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4045 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4049 /// \brief Returns true if it is beneficial to convert a load of a constant
4050 /// to just the constant itself.
4051 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4053 assert(Ty->isIntegerTy());
4055 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4056 if (BitSize == 0 || BitSize > 64)
4061 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4062 unsigned Index) const {
4063 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4066 return (Index == 0 || Index == ResVT.getVectorNumElements());
4069 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4070 // Speculate cttz only if we can directly use TZCNT.
4071 return Subtarget->hasBMI();
4074 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4075 // Speculate ctlz only if we can directly use LZCNT.
4076 return Subtarget->hasLZCNT();
4079 /// Return true if every element in Mask, beginning
4080 /// from position Pos and ending in Pos+Size is undef.
4081 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4082 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4088 /// Return true if Val is undef or if its value falls within the
4089 /// specified range (L, H].
4090 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4091 return (Val < 0) || (Val >= Low && Val < Hi);
4094 /// Val is either less than zero (undef) or equal to the specified value.
4095 static bool isUndefOrEqual(int Val, int CmpVal) {
4096 return (Val < 0 || Val == CmpVal);
4099 /// Return true if every element in Mask, beginning
4100 /// from position Pos and ending in Pos+Size, falls within the specified
4101 /// sequential range (Low, Low+Size]. or is undef.
4102 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4103 unsigned Pos, unsigned Size, int Low) {
4104 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4105 if (!isUndefOrEqual(Mask[i], Low))
4110 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4111 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4112 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4113 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4114 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4117 // The index should be aligned on a vecWidth-bit boundary.
4119 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4121 MVT VT = N->getSimpleValueType(0);
4122 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4123 bool Result = (Index * ElSize) % vecWidth == 0;
4128 /// Return true if the specified INSERT_SUBVECTOR
4129 /// operand specifies a subvector insert that is suitable for input to
4130 /// insertion of 128 or 256-bit subvectors
4131 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4132 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4133 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4135 // The index should be aligned on a vecWidth-bit boundary.
4137 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4139 MVT VT = N->getSimpleValueType(0);
4140 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4141 bool Result = (Index * ElSize) % vecWidth == 0;
4146 bool X86::isVINSERT128Index(SDNode *N) {
4147 return isVINSERTIndex(N, 128);
4150 bool X86::isVINSERT256Index(SDNode *N) {
4151 return isVINSERTIndex(N, 256);
4154 bool X86::isVEXTRACT128Index(SDNode *N) {
4155 return isVEXTRACTIndex(N, 128);
4158 bool X86::isVEXTRACT256Index(SDNode *N) {
4159 return isVEXTRACTIndex(N, 256);
4162 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4163 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4164 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4165 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4168 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4170 MVT VecVT = N->getOperand(0).getSimpleValueType();
4171 MVT ElVT = VecVT.getVectorElementType();
4173 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4174 return Index / NumElemsPerChunk;
4177 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4178 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4179 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4180 llvm_unreachable("Illegal insert subvector for VINSERT");
4183 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4185 MVT VecVT = N->getSimpleValueType(0);
4186 MVT ElVT = VecVT.getVectorElementType();
4188 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4189 return Index / NumElemsPerChunk;
4192 /// Return the appropriate immediate to extract the specified
4193 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4194 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4195 return getExtractVEXTRACTImmediate(N, 128);
4198 /// Return the appropriate immediate to extract the specified
4199 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4200 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4201 return getExtractVEXTRACTImmediate(N, 256);
4204 /// Return the appropriate immediate to insert at the specified
4205 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4206 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4207 return getInsertVINSERTImmediate(N, 128);
4210 /// Return the appropriate immediate to insert at the specified
4211 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4212 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4213 return getInsertVINSERTImmediate(N, 256);
4216 /// Returns true if Elt is a constant integer zero
4217 static bool isZero(SDValue V) {
4218 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4219 return C && C->isNullValue();
4222 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4223 bool X86::isZeroNode(SDValue Elt) {
4226 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4227 return CFP->getValueAPF().isPosZero();
4231 /// Returns a vector of specified type with all zero elements.
4232 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4233 SelectionDAG &DAG, SDLoc dl) {
4234 assert(VT.isVector() && "Expected a vector type");
4236 // Always build SSE zero vectors as <4 x i32> bitcasted
4237 // to their dest type. This ensures they get CSE'd.
4239 if (VT.is128BitVector()) { // SSE
4240 if (Subtarget->hasSSE2()) { // SSE2
4241 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4242 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4244 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4245 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4247 } else if (VT.is256BitVector()) { // AVX
4248 if (Subtarget->hasInt256()) { // AVX2
4249 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4250 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4251 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4253 // 256-bit logic and arithmetic instructions in AVX are all
4254 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4255 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4256 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4257 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4259 } else if (VT.is512BitVector()) { // AVX-512
4260 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4261 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4262 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4263 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4264 } else if (VT.getScalarType() == MVT::i1) {
4266 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4267 && "Unexpected vector type");
4268 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4269 && "Unexpected vector type");
4270 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4271 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4272 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4274 llvm_unreachable("Unexpected vector type");
4276 return DAG.getBitcast(VT, Vec);
4279 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4280 SelectionDAG &DAG, SDLoc dl,
4281 unsigned vectorWidth) {
4282 assert((vectorWidth == 128 || vectorWidth == 256) &&
4283 "Unsupported vector width");
4284 EVT VT = Vec.getValueType();
4285 EVT ElVT = VT.getVectorElementType();
4286 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4287 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4288 VT.getVectorNumElements()/Factor);
4290 // Extract from UNDEF is UNDEF.
4291 if (Vec.getOpcode() == ISD::UNDEF)
4292 return DAG.getUNDEF(ResultVT);
4294 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4295 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4297 // This is the index of the first element of the vectorWidth-bit chunk
4299 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4302 // If the input is a buildvector just emit a smaller one.
4303 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4304 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4305 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4308 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4309 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4312 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4313 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4314 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4315 /// instructions or a simple subregister reference. Idx is an index in the
4316 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4317 /// lowering EXTRACT_VECTOR_ELT operations easier.
4318 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4319 SelectionDAG &DAG, SDLoc dl) {
4320 assert((Vec.getValueType().is256BitVector() ||
4321 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4322 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4325 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4326 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4327 SelectionDAG &DAG, SDLoc dl) {
4328 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4329 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4332 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4333 unsigned IdxVal, SelectionDAG &DAG,
4334 SDLoc dl, unsigned vectorWidth) {
4335 assert((vectorWidth == 128 || vectorWidth == 256) &&
4336 "Unsupported vector width");
4337 // Inserting UNDEF is Result
4338 if (Vec.getOpcode() == ISD::UNDEF)
4340 EVT VT = Vec.getValueType();
4341 EVT ElVT = VT.getVectorElementType();
4342 EVT ResultVT = Result.getValueType();
4344 // Insert the relevant vectorWidth bits.
4345 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4347 // This is the index of the first element of the vectorWidth-bit chunk
4349 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4352 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4353 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4356 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4357 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4358 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4359 /// simple superregister reference. Idx is an index in the 128 bits
4360 /// we want. It need not be aligned to a 128-bit boundary. That makes
4361 /// lowering INSERT_VECTOR_ELT operations easier.
4362 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4363 SelectionDAG &DAG, SDLoc dl) {
4364 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4366 // For insertion into the zero index (low half) of a 256-bit vector, it is
4367 // more efficient to generate a blend with immediate instead of an insert*128.
4368 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4369 // extend the subvector to the size of the result vector. Make sure that
4370 // we are not recursing on that node by checking for undef here.
4371 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4372 Result.getOpcode() != ISD::UNDEF) {
4373 EVT ResultVT = Result.getValueType();
4374 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4375 SDValue Undef = DAG.getUNDEF(ResultVT);
4376 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4379 // The blend instruction, and therefore its mask, depend on the data type.
4380 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4381 if (ScalarType.isFloatingPoint()) {
4382 // Choose either vblendps (float) or vblendpd (double).
4383 unsigned ScalarSize = ScalarType.getSizeInBits();
4384 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4385 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4386 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4387 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4390 const X86Subtarget &Subtarget =
4391 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4393 // AVX2 is needed for 256-bit integer blend support.
4394 // Integers must be cast to 32-bit because there is only vpblendd;
4395 // vpblendw can't be used for this because it has a handicapped mask.
4397 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4398 // is still more efficient than using the wrong domain vinsertf128 that
4399 // will be created by InsertSubVector().
4400 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4402 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4403 Vec256 = DAG.getBitcast(CastVT, Vec256);
4404 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4405 return DAG.getBitcast(ResultVT, Vec256);
4408 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4411 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4412 SelectionDAG &DAG, SDLoc dl) {
4413 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4414 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4417 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4418 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4419 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4420 /// large BUILD_VECTORS.
4421 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4422 unsigned NumElems, SelectionDAG &DAG,
4424 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4425 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4428 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4429 unsigned NumElems, SelectionDAG &DAG,
4431 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4432 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4435 /// Returns a vector of specified type with all bits set.
4436 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4437 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4438 /// Then bitcast to their original type, ensuring they get CSE'd.
4439 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4441 assert(VT.isVector() && "Expected a vector type");
4443 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4445 if (VT.is256BitVector()) {
4446 if (HasInt256) { // AVX2
4447 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4448 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4450 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4451 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4453 } else if (VT.is128BitVector()) {
4454 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4456 llvm_unreachable("Unexpected vector type");
4458 return DAG.getBitcast(VT, Vec);
4461 /// Returns a vector_shuffle node for an unpackl operation.
4462 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4464 unsigned NumElems = VT.getVectorNumElements();
4465 SmallVector<int, 8> Mask;
4466 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4468 Mask.push_back(i + NumElems);
4470 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4473 /// Returns a vector_shuffle node for an unpackh operation.
4474 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4476 unsigned NumElems = VT.getVectorNumElements();
4477 SmallVector<int, 8> Mask;
4478 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4479 Mask.push_back(i + Half);
4480 Mask.push_back(i + NumElems + Half);
4482 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4485 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4486 /// This produces a shuffle where the low element of V2 is swizzled into the
4487 /// zero/undef vector, landing at element Idx.
4488 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4489 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4491 const X86Subtarget *Subtarget,
4492 SelectionDAG &DAG) {
4493 MVT VT = V2.getSimpleValueType();
4495 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4496 unsigned NumElems = VT.getVectorNumElements();
4497 SmallVector<int, 16> MaskVec;
4498 for (unsigned i = 0; i != NumElems; ++i)
4499 // If this is the insertion idx, put the low elt of V2 here.
4500 MaskVec.push_back(i == Idx ? NumElems : i);
4501 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4504 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4505 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4506 /// uses one source. Note that this will set IsUnary for shuffles which use a
4507 /// single input multiple times, and in those cases it will
4508 /// adjust the mask to only have indices within that single input.
4509 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4510 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4511 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4512 unsigned NumElems = VT.getVectorNumElements();
4516 bool IsFakeUnary = false;
4517 switch(N->getOpcode()) {
4518 case X86ISD::BLENDI:
4519 ImmN = N->getOperand(N->getNumOperands()-1);
4520 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4523 ImmN = N->getOperand(N->getNumOperands()-1);
4524 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4525 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4527 case X86ISD::UNPCKH:
4528 DecodeUNPCKHMask(VT, Mask);
4529 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4531 case X86ISD::UNPCKL:
4532 DecodeUNPCKLMask(VT, Mask);
4533 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4535 case X86ISD::MOVHLPS:
4536 DecodeMOVHLPSMask(NumElems, Mask);
4537 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4539 case X86ISD::MOVLHPS:
4540 DecodeMOVLHPSMask(NumElems, Mask);
4541 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4543 case X86ISD::PALIGNR:
4544 ImmN = N->getOperand(N->getNumOperands()-1);
4545 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4547 case X86ISD::PSHUFD:
4548 case X86ISD::VPERMILPI:
4549 ImmN = N->getOperand(N->getNumOperands()-1);
4550 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4553 case X86ISD::PSHUFHW:
4554 ImmN = N->getOperand(N->getNumOperands()-1);
4555 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4558 case X86ISD::PSHUFLW:
4559 ImmN = N->getOperand(N->getNumOperands()-1);
4560 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4563 case X86ISD::PSHUFB: {
4565 SDValue MaskNode = N->getOperand(1);
4566 while (MaskNode->getOpcode() == ISD::BITCAST)
4567 MaskNode = MaskNode->getOperand(0);
4569 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4570 // If we have a build-vector, then things are easy.
4571 EVT VT = MaskNode.getValueType();
4572 assert(VT.isVector() &&
4573 "Can't produce a non-vector with a build_vector!");
4574 if (!VT.isInteger())
4577 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4579 SmallVector<uint64_t, 32> RawMask;
4580 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4581 SDValue Op = MaskNode->getOperand(i);
4582 if (Op->getOpcode() == ISD::UNDEF) {
4583 RawMask.push_back((uint64_t)SM_SentinelUndef);
4586 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4589 APInt MaskElement = CN->getAPIntValue();
4591 // We now have to decode the element which could be any integer size and
4592 // extract each byte of it.
4593 for (int j = 0; j < NumBytesPerElement; ++j) {
4594 // Note that this is x86 and so always little endian: the low byte is
4595 // the first byte of the mask.
4596 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4597 MaskElement = MaskElement.lshr(8);
4600 DecodePSHUFBMask(RawMask, Mask);
4604 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4608 SDValue Ptr = MaskLoad->getBasePtr();
4609 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4610 Ptr->getOpcode() == X86ISD::WrapperRIP)
4611 Ptr = Ptr->getOperand(0);
4613 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4614 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4617 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4618 DecodePSHUFBMask(C, Mask);
4626 case X86ISD::VPERMI:
4627 ImmN = N->getOperand(N->getNumOperands()-1);
4628 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4633 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4635 case X86ISD::VPERM2X128:
4636 ImmN = N->getOperand(N->getNumOperands()-1);
4637 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4638 if (Mask.empty()) return false;
4639 // Mask only contains negative index if an element is zero.
4640 if (std::any_of(Mask.begin(), Mask.end(),
4641 [](int M){ return M == SM_SentinelZero; }))
4644 case X86ISD::MOVSLDUP:
4645 DecodeMOVSLDUPMask(VT, Mask);
4648 case X86ISD::MOVSHDUP:
4649 DecodeMOVSHDUPMask(VT, Mask);
4652 case X86ISD::MOVDDUP:
4653 DecodeMOVDDUPMask(VT, Mask);
4656 case X86ISD::MOVLHPD:
4657 case X86ISD::MOVLPD:
4658 case X86ISD::MOVLPS:
4659 // Not yet implemented
4661 default: llvm_unreachable("unknown target shuffle node");
4664 // If we have a fake unary shuffle, the shuffle mask is spread across two
4665 // inputs that are actually the same node. Re-map the mask to always point
4666 // into the first input.
4669 if (M >= (int)Mask.size())
4675 /// Returns the scalar element that will make up the ith
4676 /// element of the result of the vector shuffle.
4677 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4680 return SDValue(); // Limit search depth.
4682 SDValue V = SDValue(N, 0);
4683 EVT VT = V.getValueType();
4684 unsigned Opcode = V.getOpcode();
4686 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4687 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4688 int Elt = SV->getMaskElt(Index);
4691 return DAG.getUNDEF(VT.getVectorElementType());
4693 unsigned NumElems = VT.getVectorNumElements();
4694 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4695 : SV->getOperand(1);
4696 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4699 // Recurse into target specific vector shuffles to find scalars.
4700 if (isTargetShuffle(Opcode)) {
4701 MVT ShufVT = V.getSimpleValueType();
4702 unsigned NumElems = ShufVT.getVectorNumElements();
4703 SmallVector<int, 16> ShuffleMask;
4706 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4709 int Elt = ShuffleMask[Index];
4711 return DAG.getUNDEF(ShufVT.getVectorElementType());
4713 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4715 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4719 // Actual nodes that may contain scalar elements
4720 if (Opcode == ISD::BITCAST) {
4721 V = V.getOperand(0);
4722 EVT SrcVT = V.getValueType();
4723 unsigned NumElems = VT.getVectorNumElements();
4725 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4729 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4730 return (Index == 0) ? V.getOperand(0)
4731 : DAG.getUNDEF(VT.getVectorElementType());
4733 if (V.getOpcode() == ISD::BUILD_VECTOR)
4734 return V.getOperand(Index);
4739 /// Custom lower build_vector of v16i8.
4740 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4741 unsigned NumNonZero, unsigned NumZero,
4743 const X86Subtarget* Subtarget,
4744 const TargetLowering &TLI) {
4752 // SSE4.1 - use PINSRB to insert each byte directly.
4753 if (Subtarget->hasSSE41()) {
4754 for (unsigned i = 0; i < 16; ++i) {
4755 bool isNonZero = (NonZeros & (1 << i)) != 0;
4759 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4761 V = DAG.getUNDEF(MVT::v16i8);
4764 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4765 MVT::v16i8, V, Op.getOperand(i),
4766 DAG.getIntPtrConstant(i, dl));
4773 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4774 for (unsigned i = 0; i < 16; ++i) {
4775 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4776 if (ThisIsNonZero && First) {
4778 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4780 V = DAG.getUNDEF(MVT::v8i16);
4785 SDValue ThisElt, LastElt;
4786 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4787 if (LastIsNonZero) {
4788 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4789 MVT::i16, Op.getOperand(i-1));
4791 if (ThisIsNonZero) {
4792 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4793 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4794 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4796 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4800 if (ThisElt.getNode())
4801 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4802 DAG.getIntPtrConstant(i/2, dl));
4806 return DAG.getBitcast(MVT::v16i8, V);
4809 /// Custom lower build_vector of v8i16.
4810 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4811 unsigned NumNonZero, unsigned NumZero,
4813 const X86Subtarget* Subtarget,
4814 const TargetLowering &TLI) {
4821 for (unsigned i = 0; i < 8; ++i) {
4822 bool isNonZero = (NonZeros & (1 << i)) != 0;
4826 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4828 V = DAG.getUNDEF(MVT::v8i16);
4831 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4832 MVT::v8i16, V, Op.getOperand(i),
4833 DAG.getIntPtrConstant(i, dl));
4840 /// Custom lower build_vector of v4i32 or v4f32.
4841 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4842 const X86Subtarget *Subtarget,
4843 const TargetLowering &TLI) {
4844 // Find all zeroable elements.
4845 std::bitset<4> Zeroable;
4846 for (int i=0; i < 4; ++i) {
4847 SDValue Elt = Op->getOperand(i);
4848 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4850 assert(Zeroable.size() - Zeroable.count() > 1 &&
4851 "We expect at least two non-zero elements!");
4853 // We only know how to deal with build_vector nodes where elements are either
4854 // zeroable or extract_vector_elt with constant index.
4855 SDValue FirstNonZero;
4856 unsigned FirstNonZeroIdx;
4857 for (unsigned i=0; i < 4; ++i) {
4860 SDValue Elt = Op->getOperand(i);
4861 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4862 !isa<ConstantSDNode>(Elt.getOperand(1)))
4864 // Make sure that this node is extracting from a 128-bit vector.
4865 MVT VT = Elt.getOperand(0).getSimpleValueType();
4866 if (!VT.is128BitVector())
4868 if (!FirstNonZero.getNode()) {
4870 FirstNonZeroIdx = i;
4874 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4875 SDValue V1 = FirstNonZero.getOperand(0);
4876 MVT VT = V1.getSimpleValueType();
4878 // See if this build_vector can be lowered as a blend with zero.
4880 unsigned EltMaskIdx, EltIdx;
4882 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4883 if (Zeroable[EltIdx]) {
4884 // The zero vector will be on the right hand side.
4885 Mask[EltIdx] = EltIdx+4;
4889 Elt = Op->getOperand(EltIdx);
4890 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4891 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4892 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4894 Mask[EltIdx] = EltIdx;
4898 // Let the shuffle legalizer deal with blend operations.
4899 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4900 if (V1.getSimpleValueType() != VT)
4901 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4902 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4905 // See if we can lower this build_vector to a INSERTPS.
4906 if (!Subtarget->hasSSE41())
4909 SDValue V2 = Elt.getOperand(0);
4910 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4913 bool CanFold = true;
4914 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4918 SDValue Current = Op->getOperand(i);
4919 SDValue SrcVector = Current->getOperand(0);
4922 CanFold = SrcVector == V1 &&
4923 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4929 assert(V1.getNode() && "Expected at least two non-zero elements!");
4930 if (V1.getSimpleValueType() != MVT::v4f32)
4931 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4932 if (V2.getSimpleValueType() != MVT::v4f32)
4933 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4935 // Ok, we can emit an INSERTPS instruction.
4936 unsigned ZMask = Zeroable.to_ulong();
4938 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4939 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4941 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4942 DAG.getIntPtrConstant(InsertPSMask, DL));
4943 return DAG.getBitcast(VT, Result);
4946 /// Return a vector logical shift node.
4947 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4948 unsigned NumBits, SelectionDAG &DAG,
4949 const TargetLowering &TLI, SDLoc dl) {
4950 assert(VT.is128BitVector() && "Unknown type for VShift");
4951 MVT ShVT = MVT::v2i64;
4952 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4953 SrcOp = DAG.getBitcast(ShVT, SrcOp);
4954 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4955 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4956 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4957 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4961 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4963 // Check if the scalar load can be widened into a vector load. And if
4964 // the address is "base + cst" see if the cst can be "absorbed" into
4965 // the shuffle mask.
4966 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4967 SDValue Ptr = LD->getBasePtr();
4968 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4970 EVT PVT = LD->getValueType(0);
4971 if (PVT != MVT::i32 && PVT != MVT::f32)
4976 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4977 FI = FINode->getIndex();
4979 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4980 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4981 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4982 Offset = Ptr.getConstantOperandVal(1);
4983 Ptr = Ptr.getOperand(0);
4988 // FIXME: 256-bit vector instructions don't require a strict alignment,
4989 // improve this code to support it better.
4990 unsigned RequiredAlign = VT.getSizeInBits()/8;
4991 SDValue Chain = LD->getChain();
4992 // Make sure the stack object alignment is at least 16 or 32.
4993 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4994 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4995 if (MFI->isFixedObjectIndex(FI)) {
4996 // Can't change the alignment. FIXME: It's possible to compute
4997 // the exact stack offset and reference FI + adjust offset instead.
4998 // If someone *really* cares about this. That's the way to implement it.
5001 MFI->setObjectAlignment(FI, RequiredAlign);
5005 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5006 // Ptr + (Offset & ~15).
5009 if ((Offset % RequiredAlign) & 3)
5011 int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5014 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5015 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5018 int EltNo = (Offset - StartOffset) >> 2;
5019 unsigned NumElems = VT.getVectorNumElements();
5021 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5022 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5023 LD->getPointerInfo().getWithOffset(StartOffset),
5024 false, false, false, 0);
5026 SmallVector<int, 8> Mask(NumElems, EltNo);
5028 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5034 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5035 /// elements can be replaced by a single large load which has the same value as
5036 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5038 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5040 /// FIXME: we'd also like to handle the case where the last elements are zero
5041 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5042 /// There's even a handy isZeroNode for that purpose.
5043 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5044 SDLoc &DL, SelectionDAG &DAG,
5045 bool isAfterLegalize) {
5046 unsigned NumElems = Elts.size();
5048 LoadSDNode *LDBase = nullptr;
5049 unsigned LastLoadedElt = -1U;
5051 // For each element in the initializer, see if we've found a load or an undef.
5052 // If we don't find an initial load element, or later load elements are
5053 // non-consecutive, bail out.
5054 for (unsigned i = 0; i < NumElems; ++i) {
5055 SDValue Elt = Elts[i];
5056 // Look through a bitcast.
5057 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5058 Elt = Elt.getOperand(0);
5059 if (!Elt.getNode() ||
5060 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5063 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5065 LDBase = cast<LoadSDNode>(Elt.getNode());
5069 if (Elt.getOpcode() == ISD::UNDEF)
5072 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5073 EVT LdVT = Elt.getValueType();
5074 // Each loaded element must be the correct fractional portion of the
5075 // requested vector load.
5076 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5078 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5083 // If we have found an entire vector of loads and undefs, then return a large
5084 // load of the entire vector width starting at the base pointer. If we found
5085 // consecutive loads for the low half, generate a vzext_load node.
5086 if (LastLoadedElt == NumElems - 1) {
5087 assert(LDBase && "Did not find base load for merging consecutive loads");
5088 EVT EltVT = LDBase->getValueType(0);
5089 // Ensure that the input vector size for the merged loads matches the
5090 // cumulative size of the input elements.
5091 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5094 if (isAfterLegalize &&
5095 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5098 SDValue NewLd = SDValue();
5100 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5101 LDBase->getPointerInfo(), LDBase->isVolatile(),
5102 LDBase->isNonTemporal(), LDBase->isInvariant(),
5103 LDBase->getAlignment());
5105 if (LDBase->hasAnyUseOfValue(1)) {
5106 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5108 SDValue(NewLd.getNode(), 1));
5109 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5110 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5111 SDValue(NewLd.getNode(), 1));
5117 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5118 //of a v4i32 / v4f32. It's probably worth generalizing.
5119 EVT EltVT = VT.getVectorElementType();
5120 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5121 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5122 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5123 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5125 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5126 LDBase->getPointerInfo(),
5127 LDBase->getAlignment(),
5128 false/*isVolatile*/, true/*ReadMem*/,
5131 // Make sure the newly-created LOAD is in the same position as LDBase in
5132 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5133 // update uses of LDBase's output chain to use the TokenFactor.
5134 if (LDBase->hasAnyUseOfValue(1)) {
5135 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5136 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5137 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5138 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5139 SDValue(ResNode.getNode(), 1));
5142 return DAG.getBitcast(VT, ResNode);
5147 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5148 /// to generate a splat value for the following cases:
5149 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5150 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5151 /// a scalar load, or a constant.
5152 /// The VBROADCAST node is returned when a pattern is found,
5153 /// or SDValue() otherwise.
5154 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5155 SelectionDAG &DAG) {
5156 // VBROADCAST requires AVX.
5157 // TODO: Splats could be generated for non-AVX CPUs using SSE
5158 // instructions, but there's less potential gain for only 128-bit vectors.
5159 if (!Subtarget->hasAVX())
5162 MVT VT = Op.getSimpleValueType();
5165 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5166 "Unsupported vector type for broadcast.");
5171 switch (Op.getOpcode()) {
5173 // Unknown pattern found.
5176 case ISD::BUILD_VECTOR: {
5177 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5178 BitVector UndefElements;
5179 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5181 // We need a splat of a single value to use broadcast, and it doesn't
5182 // make any sense if the value is only in one element of the vector.
5183 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5187 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5188 Ld.getOpcode() == ISD::ConstantFP);
5190 // Make sure that all of the users of a non-constant load are from the
5191 // BUILD_VECTOR node.
5192 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5197 case ISD::VECTOR_SHUFFLE: {
5198 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5200 // Shuffles must have a splat mask where the first element is
5202 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5205 SDValue Sc = Op.getOperand(0);
5206 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5207 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5209 if (!Subtarget->hasInt256())
5212 // Use the register form of the broadcast instruction available on AVX2.
5213 if (VT.getSizeInBits() >= 256)
5214 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5215 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5218 Ld = Sc.getOperand(0);
5219 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5220 Ld.getOpcode() == ISD::ConstantFP);
5222 // The scalar_to_vector node and the suspected
5223 // load node must have exactly one user.
5224 // Constants may have multiple users.
5226 // AVX-512 has register version of the broadcast
5227 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5228 Ld.getValueType().getSizeInBits() >= 32;
5229 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5236 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5237 bool IsGE256 = (VT.getSizeInBits() >= 256);
5239 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5240 // instruction to save 8 or more bytes of constant pool data.
5241 // TODO: If multiple splats are generated to load the same constant,
5242 // it may be detrimental to overall size. There needs to be a way to detect
5243 // that condition to know if this is truly a size win.
5244 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5246 // Handle broadcasting a single constant scalar from the constant pool
5248 // On Sandybridge (no AVX2), it is still better to load a constant vector
5249 // from the constant pool and not to broadcast it from a scalar.
5250 // But override that restriction when optimizing for size.
5251 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5252 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5253 EVT CVT = Ld.getValueType();
5254 assert(!CVT.isVector() && "Must not broadcast a vector type");
5256 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5257 // For size optimization, also splat v2f64 and v2i64, and for size opt
5258 // with AVX2, also splat i8 and i16.
5259 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5260 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5261 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5262 const Constant *C = nullptr;
5263 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5264 C = CI->getConstantIntValue();
5265 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5266 C = CF->getConstantFPValue();
5268 assert(C && "Invalid constant type");
5270 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5272 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5273 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5275 CVT, dl, DAG.getEntryNode(), CP,
5276 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5277 false, false, Alignment);
5279 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5283 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5285 // Handle AVX2 in-register broadcasts.
5286 if (!IsLoad && Subtarget->hasInt256() &&
5287 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5288 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5290 // The scalar source must be a normal load.
5294 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5295 (Subtarget->hasVLX() && ScalarSize == 64))
5296 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5298 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5299 // double since there is no vbroadcastsd xmm
5300 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5301 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5302 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5305 // Unsupported broadcast.
5309 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5310 /// underlying vector and index.
5312 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5314 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5316 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5317 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5320 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5322 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5324 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5325 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5328 // In this case the vector is the extract_subvector expression and the index
5329 // is 2, as specified by the shuffle.
5330 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5331 SDValue ShuffleVec = SVOp->getOperand(0);
5332 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5333 assert(ShuffleVecVT.getVectorElementType() ==
5334 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5336 int ShuffleIdx = SVOp->getMaskElt(Idx);
5337 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5338 ExtractedFromVec = ShuffleVec;
5344 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5345 MVT VT = Op.getSimpleValueType();
5347 // Skip if insert_vec_elt is not supported.
5348 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5349 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5353 unsigned NumElems = Op.getNumOperands();
5357 SmallVector<unsigned, 4> InsertIndices;
5358 SmallVector<int, 8> Mask(NumElems, -1);
5360 for (unsigned i = 0; i != NumElems; ++i) {
5361 unsigned Opc = Op.getOperand(i).getOpcode();
5363 if (Opc == ISD::UNDEF)
5366 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5367 // Quit if more than 1 elements need inserting.
5368 if (InsertIndices.size() > 1)
5371 InsertIndices.push_back(i);
5375 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5376 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5377 // Quit if non-constant index.
5378 if (!isa<ConstantSDNode>(ExtIdx))
5380 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5382 // Quit if extracted from vector of different type.
5383 if (ExtractedFromVec.getValueType() != VT)
5386 if (!VecIn1.getNode())
5387 VecIn1 = ExtractedFromVec;
5388 else if (VecIn1 != ExtractedFromVec) {
5389 if (!VecIn2.getNode())
5390 VecIn2 = ExtractedFromVec;
5391 else if (VecIn2 != ExtractedFromVec)
5392 // Quit if more than 2 vectors to shuffle
5396 if (ExtractedFromVec == VecIn1)
5398 else if (ExtractedFromVec == VecIn2)
5399 Mask[i] = Idx + NumElems;
5402 if (!VecIn1.getNode())
5405 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5406 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5407 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5408 unsigned Idx = InsertIndices[i];
5409 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5410 DAG.getIntPtrConstant(Idx, DL));
5416 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5417 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5418 Op.getScalarValueSizeInBits() == 1 &&
5419 "Can not convert non-constant vector");
5420 uint64_t Immediate = 0;
5421 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5422 SDValue In = Op.getOperand(idx);
5423 if (In.getOpcode() != ISD::UNDEF)
5424 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5428 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5429 return DAG.getConstant(Immediate, dl, VT);
5431 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5433 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5435 MVT VT = Op.getSimpleValueType();
5436 assert((VT.getVectorElementType() == MVT::i1) &&
5437 "Unexpected type in LowerBUILD_VECTORvXi1!");
5440 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5441 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5442 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5443 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5446 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5447 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5448 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5449 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5452 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5453 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5454 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5455 return DAG.getBitcast(VT, Imm);
5456 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5457 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5458 DAG.getIntPtrConstant(0, dl));
5461 // Vector has one or more non-const elements
5462 uint64_t Immediate = 0;
5463 SmallVector<unsigned, 16> NonConstIdx;
5464 bool IsSplat = true;
5465 bool HasConstElts = false;
5467 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5468 SDValue In = Op.getOperand(idx);
5469 if (In.getOpcode() == ISD::UNDEF)
5471 if (!isa<ConstantSDNode>(In))
5472 NonConstIdx.push_back(idx);
5474 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5475 HasConstElts = true;
5479 else if (In != Op.getOperand(SplatIdx))
5483 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5485 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5486 DAG.getConstant(1, dl, VT),
5487 DAG.getConstant(0, dl, VT));
5489 // insert elements one by one
5493 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5494 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5496 else if (HasConstElts)
5497 Imm = DAG.getConstant(0, dl, VT);
5499 Imm = DAG.getUNDEF(VT);
5500 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5501 DstVec = DAG.getBitcast(VT, Imm);
5503 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5504 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5505 DAG.getIntPtrConstant(0, dl));
5508 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5509 unsigned InsertIdx = NonConstIdx[i];
5510 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5511 Op.getOperand(InsertIdx),
5512 DAG.getIntPtrConstant(InsertIdx, dl));
5517 /// \brief Return true if \p N implements a horizontal binop and return the
5518 /// operands for the horizontal binop into V0 and V1.
5520 /// This is a helper function of LowerToHorizontalOp().
5521 /// This function checks that the build_vector \p N in input implements a
5522 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5523 /// operation to match.
5524 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5525 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5526 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5529 /// This function only analyzes elements of \p N whose indices are
5530 /// in range [BaseIdx, LastIdx).
5531 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5533 unsigned BaseIdx, unsigned LastIdx,
5534 SDValue &V0, SDValue &V1) {
5535 EVT VT = N->getValueType(0);
5537 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5538 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5539 "Invalid Vector in input!");
5541 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5542 bool CanFold = true;
5543 unsigned ExpectedVExtractIdx = BaseIdx;
5544 unsigned NumElts = LastIdx - BaseIdx;
5545 V0 = DAG.getUNDEF(VT);
5546 V1 = DAG.getUNDEF(VT);
5548 // Check if N implements a horizontal binop.
5549 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5550 SDValue Op = N->getOperand(i + BaseIdx);
5553 if (Op->getOpcode() == ISD::UNDEF) {
5554 // Update the expected vector extract index.
5555 if (i * 2 == NumElts)
5556 ExpectedVExtractIdx = BaseIdx;
5557 ExpectedVExtractIdx += 2;
5561 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5566 SDValue Op0 = Op.getOperand(0);
5567 SDValue Op1 = Op.getOperand(1);
5569 // Try to match the following pattern:
5570 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5571 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5572 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5573 Op0.getOperand(0) == Op1.getOperand(0) &&
5574 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5575 isa<ConstantSDNode>(Op1.getOperand(1)));
5579 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5580 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5582 if (i * 2 < NumElts) {
5583 if (V0.getOpcode() == ISD::UNDEF) {
5584 V0 = Op0.getOperand(0);
5585 if (V0.getValueType() != VT)
5589 if (V1.getOpcode() == ISD::UNDEF) {
5590 V1 = Op0.getOperand(0);
5591 if (V1.getValueType() != VT)
5594 if (i * 2 == NumElts)
5595 ExpectedVExtractIdx = BaseIdx;
5598 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5599 if (I0 == ExpectedVExtractIdx)
5600 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5601 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5602 // Try to match the following dag sequence:
5603 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5604 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5608 ExpectedVExtractIdx += 2;
5614 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5615 /// a concat_vector.
5617 /// This is a helper function of LowerToHorizontalOp().
5618 /// This function expects two 256-bit vectors called V0 and V1.
5619 /// At first, each vector is split into two separate 128-bit vectors.
5620 /// Then, the resulting 128-bit vectors are used to implement two
5621 /// horizontal binary operations.
5623 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5625 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5626 /// the two new horizontal binop.
5627 /// When Mode is set, the first horizontal binop dag node would take as input
5628 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5629 /// horizontal binop dag node would take as input the lower 128-bit of V1
5630 /// and the upper 128-bit of V1.
5632 /// HADD V0_LO, V0_HI
5633 /// HADD V1_LO, V1_HI
5635 /// Otherwise, the first horizontal binop dag node takes as input the lower
5636 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5637 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5639 /// HADD V0_LO, V1_LO
5640 /// HADD V0_HI, V1_HI
5642 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5643 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5644 /// the upper 128-bits of the result.
5645 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5646 SDLoc DL, SelectionDAG &DAG,
5647 unsigned X86Opcode, bool Mode,
5648 bool isUndefLO, bool isUndefHI) {
5649 EVT VT = V0.getValueType();
5650 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5651 "Invalid nodes in input!");
5653 unsigned NumElts = VT.getVectorNumElements();
5654 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5655 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5656 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5657 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5658 EVT NewVT = V0_LO.getValueType();
5660 SDValue LO = DAG.getUNDEF(NewVT);
5661 SDValue HI = DAG.getUNDEF(NewVT);
5664 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5665 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5666 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5667 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5668 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5670 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5671 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5672 V1_LO->getOpcode() != ISD::UNDEF))
5673 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5675 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5676 V1_HI->getOpcode() != ISD::UNDEF))
5677 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5680 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5683 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5685 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5686 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5687 EVT VT = BV->getValueType(0);
5688 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5689 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5693 unsigned NumElts = VT.getVectorNumElements();
5694 SDValue InVec0 = DAG.getUNDEF(VT);
5695 SDValue InVec1 = DAG.getUNDEF(VT);
5697 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5698 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5700 // Odd-numbered elements in the input build vector are obtained from
5701 // adding two integer/float elements.
5702 // Even-numbered elements in the input build vector are obtained from
5703 // subtracting two integer/float elements.
5704 unsigned ExpectedOpcode = ISD::FSUB;
5705 unsigned NextExpectedOpcode = ISD::FADD;
5706 bool AddFound = false;
5707 bool SubFound = false;
5709 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5710 SDValue Op = BV->getOperand(i);
5712 // Skip 'undef' values.
5713 unsigned Opcode = Op.getOpcode();
5714 if (Opcode == ISD::UNDEF) {
5715 std::swap(ExpectedOpcode, NextExpectedOpcode);
5719 // Early exit if we found an unexpected opcode.
5720 if (Opcode != ExpectedOpcode)
5723 SDValue Op0 = Op.getOperand(0);
5724 SDValue Op1 = Op.getOperand(1);
5726 // Try to match the following pattern:
5727 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5728 // Early exit if we cannot match that sequence.
5729 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5730 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5731 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5732 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5733 Op0.getOperand(1) != Op1.getOperand(1))
5736 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5740 // We found a valid add/sub node. Update the information accordingly.
5746 // Update InVec0 and InVec1.
5747 if (InVec0.getOpcode() == ISD::UNDEF) {
5748 InVec0 = Op0.getOperand(0);
5749 if (InVec0.getValueType() != VT)
5752 if (InVec1.getOpcode() == ISD::UNDEF) {
5753 InVec1 = Op1.getOperand(0);
5754 if (InVec1.getValueType() != VT)
5758 // Make sure that operands in input to each add/sub node always
5759 // come from a same pair of vectors.
5760 if (InVec0 != Op0.getOperand(0)) {
5761 if (ExpectedOpcode == ISD::FSUB)
5764 // FADD is commutable. Try to commute the operands
5765 // and then test again.
5766 std::swap(Op0, Op1);
5767 if (InVec0 != Op0.getOperand(0))
5771 if (InVec1 != Op1.getOperand(0))
5774 // Update the pair of expected opcodes.
5775 std::swap(ExpectedOpcode, NextExpectedOpcode);
5778 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5779 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5780 InVec1.getOpcode() != ISD::UNDEF)
5781 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5786 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5787 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5788 const X86Subtarget *Subtarget,
5789 SelectionDAG &DAG) {
5790 EVT VT = BV->getValueType(0);
5791 unsigned NumElts = VT.getVectorNumElements();
5792 unsigned NumUndefsLO = 0;
5793 unsigned NumUndefsHI = 0;
5794 unsigned Half = NumElts/2;
5796 // Count the number of UNDEF operands in the build_vector in input.
5797 for (unsigned i = 0, e = Half; i != e; ++i)
5798 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5801 for (unsigned i = Half, e = NumElts; i != e; ++i)
5802 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5805 // Early exit if this is either a build_vector of all UNDEFs or all the
5806 // operands but one are UNDEF.
5807 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5811 SDValue InVec0, InVec1;
5812 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5813 // Try to match an SSE3 float HADD/HSUB.
5814 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5815 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5817 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5818 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5819 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5820 // Try to match an SSSE3 integer HADD/HSUB.
5821 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5822 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5824 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5825 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5828 if (!Subtarget->hasAVX())
5831 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5832 // Try to match an AVX horizontal add/sub of packed single/double
5833 // precision floating point values from 256-bit vectors.
5834 SDValue InVec2, InVec3;
5835 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5836 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5837 ((InVec0.getOpcode() == ISD::UNDEF ||
5838 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5839 ((InVec1.getOpcode() == ISD::UNDEF ||
5840 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5841 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5843 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5844 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5845 ((InVec0.getOpcode() == ISD::UNDEF ||
5846 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5847 ((InVec1.getOpcode() == ISD::UNDEF ||
5848 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5849 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5850 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5851 // Try to match an AVX2 horizontal add/sub of signed integers.
5852 SDValue InVec2, InVec3;
5854 bool CanFold = true;
5856 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5857 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5858 ((InVec0.getOpcode() == ISD::UNDEF ||
5859 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5860 ((InVec1.getOpcode() == ISD::UNDEF ||
5861 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5862 X86Opcode = X86ISD::HADD;
5863 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5864 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5865 ((InVec0.getOpcode() == ISD::UNDEF ||
5866 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5867 ((InVec1.getOpcode() == ISD::UNDEF ||
5868 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5869 X86Opcode = X86ISD::HSUB;
5874 // Fold this build_vector into a single horizontal add/sub.
5875 // Do this only if the target has AVX2.
5876 if (Subtarget->hasAVX2())
5877 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5879 // Do not try to expand this build_vector into a pair of horizontal
5880 // add/sub if we can emit a pair of scalar add/sub.
5881 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5884 // Convert this build_vector into a pair of horizontal binop followed by
5886 bool isUndefLO = NumUndefsLO == Half;
5887 bool isUndefHI = NumUndefsHI == Half;
5888 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5889 isUndefLO, isUndefHI);
5893 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5894 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5896 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5897 X86Opcode = X86ISD::HADD;
5898 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5899 X86Opcode = X86ISD::HSUB;
5900 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5901 X86Opcode = X86ISD::FHADD;
5902 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5903 X86Opcode = X86ISD::FHSUB;
5907 // Don't try to expand this build_vector into a pair of horizontal add/sub
5908 // if we can simply emit a pair of scalar add/sub.
5909 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5912 // Convert this build_vector into two horizontal add/sub followed by
5914 bool isUndefLO = NumUndefsLO == Half;
5915 bool isUndefHI = NumUndefsHI == Half;
5916 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5917 isUndefLO, isUndefHI);
5924 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5927 MVT VT = Op.getSimpleValueType();
5928 MVT ExtVT = VT.getVectorElementType();
5929 unsigned NumElems = Op.getNumOperands();
5931 // Generate vectors for predicate vectors.
5932 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5933 return LowerBUILD_VECTORvXi1(Op, DAG);
5935 // Vectors containing all zeros can be matched by pxor and xorps later
5936 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5937 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5938 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5939 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5942 return getZeroVector(VT, Subtarget, DAG, dl);
5945 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5946 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5947 // vpcmpeqd on 256-bit vectors.
5948 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5949 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5952 if (!VT.is512BitVector())
5953 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5956 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5957 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5959 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5960 return HorizontalOp;
5961 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5964 unsigned EVTBits = ExtVT.getSizeInBits();
5966 unsigned NumZero = 0;
5967 unsigned NumNonZero = 0;
5968 unsigned NonZeros = 0;
5969 bool IsAllConstants = true;
5970 SmallSet<SDValue, 8> Values;
5971 for (unsigned i = 0; i < NumElems; ++i) {
5972 SDValue Elt = Op.getOperand(i);
5973 if (Elt.getOpcode() == ISD::UNDEF)
5976 if (Elt.getOpcode() != ISD::Constant &&
5977 Elt.getOpcode() != ISD::ConstantFP)
5978 IsAllConstants = false;
5979 if (X86::isZeroNode(Elt))
5982 NonZeros |= (1 << i);
5987 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5988 if (NumNonZero == 0)
5989 return DAG.getUNDEF(VT);
5991 // Special case for single non-zero, non-undef, element.
5992 if (NumNonZero == 1) {
5993 unsigned Idx = countTrailingZeros(NonZeros);
5994 SDValue Item = Op.getOperand(Idx);
5996 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5997 // the value are obviously zero, truncate the value to i32 and do the
5998 // insertion that way. Only do this if the value is non-constant or if the
5999 // value is a constant being inserted into element 0. It is cheaper to do
6000 // a constant pool load than it is to do a movd + shuffle.
6001 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6002 (!IsAllConstants || Idx == 0)) {
6003 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6005 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6006 EVT VecVT = MVT::v4i32;
6008 // Truncate the value (which may itself be a constant) to i32, and
6009 // convert it to a vector with movd (S2V+shuffle to zero extend).
6010 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6011 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6012 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6013 Item, Idx * 2, true, Subtarget, DAG));
6017 // If we have a constant or non-constant insertion into the low element of
6018 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6019 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6020 // depending on what the source datatype is.
6023 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6025 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6026 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6027 if (VT.is512BitVector()) {
6028 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6029 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6030 Item, DAG.getIntPtrConstant(0, dl));
6032 assert((VT.is128BitVector() || VT.is256BitVector()) &&
6033 "Expected an SSE value type!");
6034 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6035 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6036 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6039 // We can't directly insert an i8 or i16 into a vector, so zero extend
6041 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6042 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6043 if (VT.is256BitVector()) {
6044 if (Subtarget->hasAVX()) {
6045 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6046 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6048 // Without AVX, we need to extend to a 128-bit vector and then
6049 // insert into the 256-bit vector.
6050 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6051 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6052 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6055 assert(VT.is128BitVector() && "Expected an SSE value type!");
6056 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6057 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6059 return DAG.getBitcast(VT, Item);
6063 // Is it a vector logical left shift?
6064 if (NumElems == 2 && Idx == 1 &&
6065 X86::isZeroNode(Op.getOperand(0)) &&
6066 !X86::isZeroNode(Op.getOperand(1))) {
6067 unsigned NumBits = VT.getSizeInBits();
6068 return getVShift(true, VT,
6069 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6070 VT, Op.getOperand(1)),
6071 NumBits/2, DAG, *this, dl);
6074 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6077 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6078 // is a non-constant being inserted into an element other than the low one,
6079 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6080 // movd/movss) to move this into the low element, then shuffle it into
6082 if (EVTBits == 32) {
6083 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6084 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6088 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6089 if (Values.size() == 1) {
6090 if (EVTBits == 32) {
6091 // Instead of a shuffle like this:
6092 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6093 // Check if it's possible to issue this instead.
6094 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6095 unsigned Idx = countTrailingZeros(NonZeros);
6096 SDValue Item = Op.getOperand(Idx);
6097 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6098 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6103 // A vector full of immediates; various special cases are already
6104 // handled, so this is best done with a single constant-pool load.
6108 // For AVX-length vectors, see if we can use a vector load to get all of the
6109 // elements, otherwise build the individual 128-bit pieces and use
6110 // shuffles to put them in place.
6111 if (VT.is256BitVector() || VT.is512BitVector()) {
6112 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6114 // Check for a build vector of consecutive loads.
6115 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6118 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6120 // Build both the lower and upper subvector.
6121 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6122 makeArrayRef(&V[0], NumElems/2));
6123 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6124 makeArrayRef(&V[NumElems / 2], NumElems/2));
6126 // Recreate the wider vector with the lower and upper part.
6127 if (VT.is256BitVector())
6128 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6129 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6132 // Let legalizer expand 2-wide build_vectors.
6133 if (EVTBits == 64) {
6134 if (NumNonZero == 1) {
6135 // One half is zero or undef.
6136 unsigned Idx = countTrailingZeros(NonZeros);
6137 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6138 Op.getOperand(Idx));
6139 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6144 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6145 if (EVTBits == 8 && NumElems == 16)
6146 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6150 if (EVTBits == 16 && NumElems == 8)
6151 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6155 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6156 if (EVTBits == 32 && NumElems == 4)
6157 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6160 // If element VT is == 32 bits, turn it into a number of shuffles.
6161 SmallVector<SDValue, 8> V(NumElems);
6162 if (NumElems == 4 && NumZero > 0) {
6163 for (unsigned i = 0; i < 4; ++i) {
6164 bool isZero = !(NonZeros & (1 << i));
6166 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6168 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6171 for (unsigned i = 0; i < 2; ++i) {
6172 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6175 V[i] = V[i*2]; // Must be a zero vector.
6178 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6181 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6184 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6189 bool Reverse1 = (NonZeros & 0x3) == 2;
6190 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6194 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6195 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6197 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6200 if (Values.size() > 1 && VT.is128BitVector()) {
6201 // Check for a build vector of consecutive loads.
6202 for (unsigned i = 0; i < NumElems; ++i)
6203 V[i] = Op.getOperand(i);
6205 // Check for elements which are consecutive loads.
6206 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6209 // Check for a build vector from mostly shuffle plus few inserting.
6210 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6213 // For SSE 4.1, use insertps to put the high elements into the low element.
6214 if (Subtarget->hasSSE41()) {
6216 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6217 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6219 Result = DAG.getUNDEF(VT);
6221 for (unsigned i = 1; i < NumElems; ++i) {
6222 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6223 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6224 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6229 // Otherwise, expand into a number of unpckl*, start by extending each of
6230 // our (non-undef) elements to the full vector width with the element in the
6231 // bottom slot of the vector (which generates no code for SSE).
6232 for (unsigned i = 0; i < NumElems; ++i) {
6233 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6234 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6236 V[i] = DAG.getUNDEF(VT);
6239 // Next, we iteratively mix elements, e.g. for v4f32:
6240 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6241 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6242 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6243 unsigned EltStride = NumElems >> 1;
6244 while (EltStride != 0) {
6245 for (unsigned i = 0; i < EltStride; ++i) {
6246 // If V[i+EltStride] is undef and this is the first round of mixing,
6247 // then it is safe to just drop this shuffle: V[i] is already in the
6248 // right place, the one element (since it's the first round) being
6249 // inserted as undef can be dropped. This isn't safe for successive
6250 // rounds because they will permute elements within both vectors.
6251 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6252 EltStride == NumElems/2)
6255 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6264 // 256-bit AVX can use the vinsertf128 instruction
6265 // to create 256-bit vectors from two other 128-bit ones.
6266 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6268 MVT ResVT = Op.getSimpleValueType();
6270 assert((ResVT.is256BitVector() ||
6271 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6273 SDValue V1 = Op.getOperand(0);
6274 SDValue V2 = Op.getOperand(1);
6275 unsigned NumElems = ResVT.getVectorNumElements();
6276 if (ResVT.is256BitVector())
6277 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6279 if (Op.getNumOperands() == 4) {
6280 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6281 ResVT.getVectorNumElements()/2);
6282 SDValue V3 = Op.getOperand(2);
6283 SDValue V4 = Op.getOperand(3);
6284 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6285 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6287 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6290 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6291 const X86Subtarget *Subtarget,
6292 SelectionDAG & DAG) {
6294 MVT ResVT = Op.getSimpleValueType();
6295 unsigned NumOfOperands = Op.getNumOperands();
6297 assert(isPowerOf2_32(NumOfOperands) &&
6298 "Unexpected number of operands in CONCAT_VECTORS");
6300 if (NumOfOperands > 2) {
6301 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6302 ResVT.getVectorNumElements()/2);
6303 SmallVector<SDValue, 2> Ops;
6304 for (unsigned i = 0; i < NumOfOperands/2; i++)
6305 Ops.push_back(Op.getOperand(i));
6306 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6308 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6309 Ops.push_back(Op.getOperand(i));
6310 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6311 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6314 SDValue V1 = Op.getOperand(0);
6315 SDValue V2 = Op.getOperand(1);
6316 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6317 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6319 if (IsZeroV1 && IsZeroV2)
6320 return getZeroVector(ResVT, Subtarget, DAG, dl);
6322 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6323 SDValue Undef = DAG.getUNDEF(ResVT);
6324 unsigned NumElems = ResVT.getVectorNumElements();
6325 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6327 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6328 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6332 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6333 // Zero the upper bits of V1
6334 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6335 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6338 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6341 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6342 const X86Subtarget *Subtarget,
6343 SelectionDAG &DAG) {
6344 MVT VT = Op.getSimpleValueType();
6345 if (VT.getVectorElementType() == MVT::i1)
6346 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6348 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6349 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6350 Op.getNumOperands() == 4)));
6352 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6353 // from two other 128-bit ones.
6355 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6356 return LowerAVXCONCAT_VECTORS(Op, DAG);
6360 //===----------------------------------------------------------------------===//
6361 // Vector shuffle lowering
6363 // This is an experimental code path for lowering vector shuffles on x86. It is
6364 // designed to handle arbitrary vector shuffles and blends, gracefully
6365 // degrading performance as necessary. It works hard to recognize idiomatic
6366 // shuffles and lower them to optimal instruction patterns without leaving
6367 // a framework that allows reasonably efficient handling of all vector shuffle
6369 //===----------------------------------------------------------------------===//
6371 /// \brief Tiny helper function to identify a no-op mask.
6373 /// This is a somewhat boring predicate function. It checks whether the mask
6374 /// array input, which is assumed to be a single-input shuffle mask of the kind
6375 /// used by the X86 shuffle instructions (not a fully general
6376 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6377 /// in-place shuffle are 'no-op's.
6378 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6379 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6380 if (Mask[i] != -1 && Mask[i] != i)
6385 /// \brief Helper function to classify a mask as a single-input mask.
6387 /// This isn't a generic single-input test because in the vector shuffle
6388 /// lowering we canonicalize single inputs to be the first input operand. This
6389 /// means we can more quickly test for a single input by only checking whether
6390 /// an input from the second operand exists. We also assume that the size of
6391 /// mask corresponds to the size of the input vectors which isn't true in the
6392 /// fully general case.
6393 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6395 if (M >= (int)Mask.size())
6400 /// \brief Test whether there are elements crossing 128-bit lanes in this
6403 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6404 /// and we routinely test for these.
6405 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6406 int LaneSize = 128 / VT.getScalarSizeInBits();
6407 int Size = Mask.size();
6408 for (int i = 0; i < Size; ++i)
6409 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6414 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6416 /// This checks a shuffle mask to see if it is performing the same
6417 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6418 /// that it is also not lane-crossing. It may however involve a blend from the
6419 /// same lane of a second vector.
6421 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6422 /// non-trivial to compute in the face of undef lanes. The representation is
6423 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6424 /// entries from both V1 and V2 inputs to the wider mask.
6426 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6427 SmallVectorImpl<int> &RepeatedMask) {
6428 int LaneSize = 128 / VT.getScalarSizeInBits();
6429 RepeatedMask.resize(LaneSize, -1);
6430 int Size = Mask.size();
6431 for (int i = 0; i < Size; ++i) {
6434 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6435 // This entry crosses lanes, so there is no way to model this shuffle.
6438 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6439 if (RepeatedMask[i % LaneSize] == -1)
6440 // This is the first non-undef entry in this slot of a 128-bit lane.
6441 RepeatedMask[i % LaneSize] =
6442 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6443 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6444 // Found a mismatch with the repeated mask.
6450 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6453 /// This is a fast way to test a shuffle mask against a fixed pattern:
6455 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6457 /// It returns true if the mask is exactly as wide as the argument list, and
6458 /// each element of the mask is either -1 (signifying undef) or the value given
6459 /// in the argument.
6460 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6461 ArrayRef<int> ExpectedMask) {
6462 if (Mask.size() != ExpectedMask.size())
6465 int Size = Mask.size();
6467 // If the values are build vectors, we can look through them to find
6468 // equivalent inputs that make the shuffles equivalent.
6469 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6470 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6472 for (int i = 0; i < Size; ++i)
6473 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6474 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6475 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6476 if (!MaskBV || !ExpectedBV ||
6477 MaskBV->getOperand(Mask[i] % Size) !=
6478 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6485 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6487 /// This helper function produces an 8-bit shuffle immediate corresponding to
6488 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6489 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6492 /// NB: We rely heavily on "undef" masks preserving the input lane.
6493 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6494 SelectionDAG &DAG) {
6495 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6496 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6497 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6498 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6499 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6502 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6503 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6504 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6505 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6506 return DAG.getConstant(Imm, DL, MVT::i8);
6509 /// \brief Compute whether each element of a shuffle is zeroable.
6511 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6512 /// Either it is an undef element in the shuffle mask, the element of the input
6513 /// referenced is undef, or the element of the input referenced is known to be
6514 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6515 /// as many lanes with this technique as possible to simplify the remaining
6517 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6518 SDValue V1, SDValue V2) {
6519 SmallBitVector Zeroable(Mask.size(), false);
6521 while (V1.getOpcode() == ISD::BITCAST)
6522 V1 = V1->getOperand(0);
6523 while (V2.getOpcode() == ISD::BITCAST)
6524 V2 = V2->getOperand(0);
6526 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6527 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6529 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6531 // Handle the easy cases.
6532 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6537 // If this is an index into a build_vector node (which has the same number
6538 // of elements), dig out the input value and use it.
6539 SDValue V = M < Size ? V1 : V2;
6540 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6543 SDValue Input = V.getOperand(M % Size);
6544 // The UNDEF opcode check really should be dead code here, but not quite
6545 // worth asserting on (it isn't invalid, just unexpected).
6546 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6553 /// \brief Try to emit a bitmask instruction for a shuffle.
6555 /// This handles cases where we can model a blend exactly as a bitmask due to
6556 /// one of the inputs being zeroable.
6557 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6558 SDValue V2, ArrayRef<int> Mask,
6559 SelectionDAG &DAG) {
6560 MVT EltVT = VT.getScalarType();
6561 int NumEltBits = EltVT.getSizeInBits();
6562 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6563 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6564 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6566 if (EltVT.isFloatingPoint()) {
6567 Zero = DAG.getBitcast(EltVT, Zero);
6568 AllOnes = DAG.getBitcast(EltVT, AllOnes);
6570 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6571 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6573 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6576 if (Mask[i] % Size != i)
6577 return SDValue(); // Not a blend.
6579 V = Mask[i] < Size ? V1 : V2;
6580 else if (V != (Mask[i] < Size ? V1 : V2))
6581 return SDValue(); // Can only let one input through the mask.
6583 VMaskOps[i] = AllOnes;
6586 return SDValue(); // No non-zeroable elements!
6588 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6589 V = DAG.getNode(VT.isFloatingPoint()
6590 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6595 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6597 /// This is used as a fallback approach when first class blend instructions are
6598 /// unavailable. Currently it is only suitable for integer vectors, but could
6599 /// be generalized for floating point vectors if desirable.
6600 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6601 SDValue V2, ArrayRef<int> Mask,
6602 SelectionDAG &DAG) {
6603 assert(VT.isInteger() && "Only supports integer vector types!");
6604 MVT EltVT = VT.getScalarType();
6605 int NumEltBits = EltVT.getSizeInBits();
6606 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6607 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6609 SmallVector<SDValue, 16> MaskOps;
6610 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6611 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6612 return SDValue(); // Shuffled input!
6613 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6616 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6617 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6618 // We have to cast V2 around.
6619 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6620 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6621 DAG.getBitcast(MaskVT, V1Mask),
6622 DAG.getBitcast(MaskVT, V2)));
6623 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6626 /// \brief Try to emit a blend instruction for a shuffle.
6628 /// This doesn't do any checks for the availability of instructions for blending
6629 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6630 /// be matched in the backend with the type given. What it does check for is
6631 /// that the shuffle mask is in fact a blend.
6632 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6633 SDValue V2, ArrayRef<int> Mask,
6634 const X86Subtarget *Subtarget,
6635 SelectionDAG &DAG) {
6636 unsigned BlendMask = 0;
6637 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6638 if (Mask[i] >= Size) {
6639 if (Mask[i] != i + Size)
6640 return SDValue(); // Shuffled V2 input!
6641 BlendMask |= 1u << i;
6644 if (Mask[i] >= 0 && Mask[i] != i)
6645 return SDValue(); // Shuffled V1 input!
6647 switch (VT.SimpleTy) {
6652 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6653 DAG.getConstant(BlendMask, DL, MVT::i8));
6657 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6661 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6662 // that instruction.
6663 if (Subtarget->hasAVX2()) {
6664 // Scale the blend by the number of 32-bit dwords per element.
6665 int Scale = VT.getScalarSizeInBits() / 32;
6667 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6668 if (Mask[i] >= Size)
6669 for (int j = 0; j < Scale; ++j)
6670 BlendMask |= 1u << (i * Scale + j);
6672 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6673 V1 = DAG.getBitcast(BlendVT, V1);
6674 V2 = DAG.getBitcast(BlendVT, V2);
6675 return DAG.getBitcast(
6676 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6677 DAG.getConstant(BlendMask, DL, MVT::i8)));
6681 // For integer shuffles we need to expand the mask and cast the inputs to
6682 // v8i16s prior to blending.
6683 int Scale = 8 / VT.getVectorNumElements();
6685 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6686 if (Mask[i] >= Size)
6687 for (int j = 0; j < Scale; ++j)
6688 BlendMask |= 1u << (i * Scale + j);
6690 V1 = DAG.getBitcast(MVT::v8i16, V1);
6691 V2 = DAG.getBitcast(MVT::v8i16, V2);
6692 return DAG.getBitcast(VT,
6693 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6694 DAG.getConstant(BlendMask, DL, MVT::i8)));
6698 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6699 SmallVector<int, 8> RepeatedMask;
6700 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6701 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6702 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6704 for (int i = 0; i < 8; ++i)
6705 if (RepeatedMask[i] >= 16)
6706 BlendMask |= 1u << i;
6707 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6708 DAG.getConstant(BlendMask, DL, MVT::i8));
6714 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6715 "256-bit byte-blends require AVX2 support!");
6717 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6718 if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6721 // Scale the blend by the number of bytes per element.
6722 int Scale = VT.getScalarSizeInBits() / 8;
6724 // This form of blend is always done on bytes. Compute the byte vector
6726 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6728 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6729 // mix of LLVM's code generator and the x86 backend. We tell the code
6730 // generator that boolean values in the elements of an x86 vector register
6731 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6732 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6733 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6734 // of the element (the remaining are ignored) and 0 in that high bit would
6735 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6736 // the LLVM model for boolean values in vector elements gets the relevant
6737 // bit set, it is set backwards and over constrained relative to x86's
6739 SmallVector<SDValue, 32> VSELECTMask;
6740 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6741 for (int j = 0; j < Scale; ++j)
6742 VSELECTMask.push_back(
6743 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6744 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6747 V1 = DAG.getBitcast(BlendVT, V1);
6748 V2 = DAG.getBitcast(BlendVT, V2);
6749 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6750 DAG.getNode(ISD::BUILD_VECTOR, DL,
6751 BlendVT, VSELECTMask),
6756 llvm_unreachable("Not a supported integer vector type!");
6760 /// \brief Try to lower as a blend of elements from two inputs followed by
6761 /// a single-input permutation.
6763 /// This matches the pattern where we can blend elements from two inputs and
6764 /// then reduce the shuffle to a single-input permutation.
6765 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6768 SelectionDAG &DAG) {
6769 // We build up the blend mask while checking whether a blend is a viable way
6770 // to reduce the shuffle.
6771 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6772 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6774 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6778 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6780 if (BlendMask[Mask[i] % Size] == -1)
6781 BlendMask[Mask[i] % Size] = Mask[i];
6782 else if (BlendMask[Mask[i] % Size] != Mask[i])
6783 return SDValue(); // Can't blend in the needed input!
6785 PermuteMask[i] = Mask[i] % Size;
6788 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6789 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6792 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6793 /// blends and permutes.
6795 /// This matches the extremely common pattern for handling combined
6796 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6797 /// operations. It will try to pick the best arrangement of shuffles and
6799 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6803 SelectionDAG &DAG) {
6804 // Shuffle the input elements into the desired positions in V1 and V2 and
6805 // blend them together.
6806 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6807 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6808 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6809 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6810 if (Mask[i] >= 0 && Mask[i] < Size) {
6811 V1Mask[i] = Mask[i];
6813 } else if (Mask[i] >= Size) {
6814 V2Mask[i] = Mask[i] - Size;
6815 BlendMask[i] = i + Size;
6818 // Try to lower with the simpler initial blend strategy unless one of the
6819 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6820 // shuffle may be able to fold with a load or other benefit. However, when
6821 // we'll have to do 2x as many shuffles in order to achieve this, blending
6822 // first is a better strategy.
6823 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6824 if (SDValue BlendPerm =
6825 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6828 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6829 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6830 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6833 /// \brief Try to lower a vector shuffle as a byte rotation.
6835 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6836 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6837 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6838 /// try to generically lower a vector shuffle through such an pattern. It
6839 /// does not check for the profitability of lowering either as PALIGNR or
6840 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6841 /// This matches shuffle vectors that look like:
6843 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6845 /// Essentially it concatenates V1 and V2, shifts right by some number of
6846 /// elements, and takes the low elements as the result. Note that while this is
6847 /// specified as a *right shift* because x86 is little-endian, it is a *left
6848 /// rotate* of the vector lanes.
6849 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6852 const X86Subtarget *Subtarget,
6853 SelectionDAG &DAG) {
6854 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6856 int NumElts = Mask.size();
6857 int NumLanes = VT.getSizeInBits() / 128;
6858 int NumLaneElts = NumElts / NumLanes;
6860 // We need to detect various ways of spelling a rotation:
6861 // [11, 12, 13, 14, 15, 0, 1, 2]
6862 // [-1, 12, 13, 14, -1, -1, 1, -1]
6863 // [-1, -1, -1, -1, -1, -1, 1, 2]
6864 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6865 // [-1, 4, 5, 6, -1, -1, 9, -1]
6866 // [-1, 4, 5, 6, -1, -1, -1, -1]
6869 for (int l = 0; l < NumElts; l += NumLaneElts) {
6870 for (int i = 0; i < NumLaneElts; ++i) {
6871 if (Mask[l + i] == -1)
6873 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6875 // Get the mod-Size index and lane correct it.
6876 int LaneIdx = (Mask[l + i] % NumElts) - l;
6877 // Make sure it was in this lane.
6878 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6881 // Determine where a rotated vector would have started.
6882 int StartIdx = i - LaneIdx;
6884 // The identity rotation isn't interesting, stop.
6887 // If we found the tail of a vector the rotation must be the missing
6888 // front. If we found the head of a vector, it must be how much of the
6890 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6893 Rotation = CandidateRotation;
6894 else if (Rotation != CandidateRotation)
6895 // The rotations don't match, so we can't match this mask.
6898 // Compute which value this mask is pointing at.
6899 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6901 // Compute which of the two target values this index should be assigned
6902 // to. This reflects whether the high elements are remaining or the low
6903 // elements are remaining.
6904 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6906 // Either set up this value if we've not encountered it before, or check
6907 // that it remains consistent.
6910 else if (TargetV != MaskV)
6911 // This may be a rotation, but it pulls from the inputs in some
6912 // unsupported interleaving.
6917 // Check that we successfully analyzed the mask, and normalize the results.
6918 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6919 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6925 // The actual rotate instruction rotates bytes, so we need to scale the
6926 // rotation based on how many bytes are in the vector lane.
6927 int Scale = 16 / NumLaneElts;
6929 // SSSE3 targets can use the palignr instruction.
6930 if (Subtarget->hasSSSE3()) {
6931 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6932 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6933 Lo = DAG.getBitcast(AlignVT, Lo);
6934 Hi = DAG.getBitcast(AlignVT, Hi);
6936 return DAG.getBitcast(
6937 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
6938 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6941 assert(VT.getSizeInBits() == 128 &&
6942 "Rotate-based lowering only supports 128-bit lowering!");
6943 assert(Mask.size() <= 16 &&
6944 "Can shuffle at most 16 bytes in a 128-bit vector!");
6946 // Default SSE2 implementation
6947 int LoByteShift = 16 - Rotation * Scale;
6948 int HiByteShift = Rotation * Scale;
6950 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6951 Lo = DAG.getBitcast(MVT::v2i64, Lo);
6952 Hi = DAG.getBitcast(MVT::v2i64, Hi);
6954 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6955 DAG.getConstant(LoByteShift, DL, MVT::i8));
6956 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6957 DAG.getConstant(HiByteShift, DL, MVT::i8));
6958 return DAG.getBitcast(VT,
6959 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6962 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6964 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6965 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6966 /// matches elements from one of the input vectors shuffled to the left or
6967 /// right with zeroable elements 'shifted in'. It handles both the strictly
6968 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6971 /// PSHL : (little-endian) left bit shift.
6972 /// [ zz, 0, zz, 2 ]
6973 /// [ -1, 4, zz, -1 ]
6974 /// PSRL : (little-endian) right bit shift.
6976 /// [ -1, -1, 7, zz]
6977 /// PSLLDQ : (little-endian) left byte shift
6978 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6979 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6980 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6981 /// PSRLDQ : (little-endian) right byte shift
6982 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6983 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6984 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6985 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6986 SDValue V2, ArrayRef<int> Mask,
6987 SelectionDAG &DAG) {
6988 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6990 int Size = Mask.size();
6991 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6993 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6994 for (int i = 0; i < Size; i += Scale)
6995 for (int j = 0; j < Shift; ++j)
6996 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7002 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7003 for (int i = 0; i != Size; i += Scale) {
7004 unsigned Pos = Left ? i + Shift : i;
7005 unsigned Low = Left ? i : i + Shift;
7006 unsigned Len = Scale - Shift;
7007 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7008 Low + (V == V1 ? 0 : Size)))
7012 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7013 bool ByteShift = ShiftEltBits > 64;
7014 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7015 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7016 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7018 // Normalize the scale for byte shifts to still produce an i64 element
7020 Scale = ByteShift ? Scale / 2 : Scale;
7022 // We need to round trip through the appropriate type for the shift.
7023 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7024 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7025 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7026 "Illegal integer vector type");
7027 V = DAG.getBitcast(ShiftVT, V);
7029 V = DAG.getNode(OpCode, DL, ShiftVT, V,
7030 DAG.getConstant(ShiftAmt, DL, MVT::i8));
7031 return DAG.getBitcast(VT, V);
7034 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7035 // keep doubling the size of the integer elements up to that. We can
7036 // then shift the elements of the integer vector by whole multiples of
7037 // their width within the elements of the larger integer vector. Test each
7038 // multiple to see if we can find a match with the moved element indices
7039 // and that the shifted in elements are all zeroable.
7040 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7041 for (int Shift = 1; Shift != Scale; ++Shift)
7042 for (bool Left : {true, false})
7043 if (CheckZeros(Shift, Scale, Left))
7044 for (SDValue V : {V1, V2})
7045 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7052 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7053 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7054 SDValue V2, ArrayRef<int> Mask,
7055 SelectionDAG &DAG) {
7056 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7057 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7059 int Size = Mask.size();
7060 int HalfSize = Size / 2;
7061 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7063 // Upper half must be undefined.
7064 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7067 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7068 // Remainder of lower half result is zero and upper half is all undef.
7069 auto LowerAsEXTRQ = [&]() {
7070 // Determine the extraction length from the part of the
7071 // lower half that isn't zeroable.
7073 for (; Len >= 0; --Len)
7074 if (!Zeroable[Len - 1])
7076 assert(Len > 0 && "Zeroable shuffle mask");
7078 // Attempt to match first Len sequential elements from the lower half.
7081 for (int i = 0; i != Len; ++i) {
7085 SDValue &V = (M < Size ? V1 : V2);
7088 // All mask elements must be in the lower half.
7092 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7103 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7104 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7105 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7106 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7107 DAG.getConstant(BitLen, DL, MVT::i8),
7108 DAG.getConstant(BitIdx, DL, MVT::i8));
7111 if (SDValue ExtrQ = LowerAsEXTRQ())
7114 // INSERTQ: Extract lowest Len elements from lower half of second source and
7115 // insert over first source, starting at Idx.
7116 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7117 auto LowerAsInsertQ = [&]() {
7118 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7121 // Attempt to match first source from mask before insertion point.
7122 if (isUndefInRange(Mask, 0, Idx)) {
7124 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7126 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7132 // Extend the extraction length looking to match both the insertion of
7133 // the second source and the remaining elements of the first.
7134 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7139 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7141 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7147 // Match the remaining elements of the lower half.
7148 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7150 } else if ((!Base || (Base == V1)) &&
7151 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7153 } else if ((!Base || (Base == V2)) &&
7154 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7161 // We may not have a base (first source) - this can safely be undefined.
7163 Base = DAG.getUNDEF(VT);
7165 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7166 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7167 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7168 DAG.getConstant(BitLen, DL, MVT::i8),
7169 DAG.getConstant(BitIdx, DL, MVT::i8));
7176 if (SDValue InsertQ = LowerAsInsertQ())
7182 /// \brief Lower a vector shuffle as a zero or any extension.
7184 /// Given a specific number of elements, element bit width, and extension
7185 /// stride, produce either a zero or any extension based on the available
7186 /// features of the subtarget.
7187 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7188 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7189 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7190 assert(Scale > 1 && "Need a scale to extend.");
7191 int NumElements = VT.getVectorNumElements();
7192 int EltBits = VT.getScalarSizeInBits();
7193 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7194 "Only 8, 16, and 32 bit elements can be extended.");
7195 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7197 // Found a valid zext mask! Try various lowering strategies based on the
7198 // input type and available ISA extensions.
7199 if (Subtarget->hasSSE41()) {
7200 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7201 NumElements / Scale);
7202 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7205 // For any extends we can cheat for larger element sizes and use shuffle
7206 // instructions that can fold with a load and/or copy.
7207 if (AnyExt && EltBits == 32) {
7208 int PSHUFDMask[4] = {0, -1, 1, -1};
7209 return DAG.getBitcast(
7210 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7211 DAG.getBitcast(MVT::v4i32, InputV),
7212 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7214 if (AnyExt && EltBits == 16 && Scale > 2) {
7215 int PSHUFDMask[4] = {0, -1, 0, -1};
7216 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7217 DAG.getBitcast(MVT::v4i32, InputV),
7218 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7219 int PSHUFHWMask[4] = {1, -1, -1, -1};
7220 return DAG.getBitcast(
7221 VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7222 DAG.getBitcast(MVT::v8i16, InputV),
7223 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7226 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7228 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7229 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7230 assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7232 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7233 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7234 DAG.getConstant(EltBits, DL, MVT::i8),
7235 DAG.getConstant(0, DL, MVT::i8)));
7236 if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7237 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7240 DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7241 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7242 DAG.getConstant(EltBits, DL, MVT::i8),
7243 DAG.getConstant(EltBits, DL, MVT::i8)));
7244 return DAG.getNode(ISD::BITCAST, DL, VT,
7245 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7248 // If this would require more than 2 unpack instructions to expand, use
7249 // pshufb when available. We can only use more than 2 unpack instructions
7250 // when zero extending i8 elements which also makes it easier to use pshufb.
7251 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7252 assert(NumElements == 16 && "Unexpected byte vector width!");
7253 SDValue PSHUFBMask[16];
7254 for (int i = 0; i < 16; ++i)
7256 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7257 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7258 return DAG.getBitcast(VT,
7259 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7260 DAG.getNode(ISD::BUILD_VECTOR, DL,
7261 MVT::v16i8, PSHUFBMask)));
7264 // Otherwise emit a sequence of unpacks.
7266 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7267 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7268 : getZeroVector(InputVT, Subtarget, DAG, DL);
7269 InputV = DAG.getBitcast(InputVT, InputV);
7270 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7274 } while (Scale > 1);
7275 return DAG.getBitcast(VT, InputV);
7278 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7280 /// This routine will try to do everything in its power to cleverly lower
7281 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7282 /// check for the profitability of this lowering, it tries to aggressively
7283 /// match this pattern. It will use all of the micro-architectural details it
7284 /// can to emit an efficient lowering. It handles both blends with all-zero
7285 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7286 /// masking out later).
7288 /// The reason we have dedicated lowering for zext-style shuffles is that they
7289 /// are both incredibly common and often quite performance sensitive.
7290 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7291 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7292 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7293 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7295 int Bits = VT.getSizeInBits();
7296 int NumElements = VT.getVectorNumElements();
7297 assert(VT.getScalarSizeInBits() <= 32 &&
7298 "Exceeds 32-bit integer zero extension limit");
7299 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7301 // Define a helper function to check a particular ext-scale and lower to it if
7303 auto Lower = [&](int Scale) -> SDValue {
7306 for (int i = 0; i < NumElements; ++i) {
7308 continue; // Valid anywhere but doesn't tell us anything.
7309 if (i % Scale != 0) {
7310 // Each of the extended elements need to be zeroable.
7314 // We no longer are in the anyext case.
7319 // Each of the base elements needs to be consecutive indices into the
7320 // same input vector.
7321 SDValue V = Mask[i] < NumElements ? V1 : V2;
7324 else if (InputV != V)
7325 return SDValue(); // Flip-flopping inputs.
7327 if (Mask[i] % NumElements != i / Scale)
7328 return SDValue(); // Non-consecutive strided elements.
7331 // If we fail to find an input, we have a zero-shuffle which should always
7332 // have already been handled.
7333 // FIXME: Maybe handle this here in case during blending we end up with one?
7337 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7338 DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7341 // The widest scale possible for extending is to a 64-bit integer.
7342 assert(Bits % 64 == 0 &&
7343 "The number of bits in a vector must be divisible by 64 on x86!");
7344 int NumExtElements = Bits / 64;
7346 // Each iteration, try extending the elements half as much, but into twice as
7348 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7349 assert(NumElements % NumExtElements == 0 &&
7350 "The input vector size must be divisible by the extended size.");
7351 if (SDValue V = Lower(NumElements / NumExtElements))
7355 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7359 // Returns one of the source operands if the shuffle can be reduced to a
7360 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7361 auto CanZExtLowHalf = [&]() {
7362 for (int i = NumElements / 2; i != NumElements; ++i)
7365 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7367 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7372 if (SDValue V = CanZExtLowHalf()) {
7373 V = DAG.getBitcast(MVT::v2i64, V);
7374 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7375 return DAG.getBitcast(VT, V);
7378 // No viable ext lowering found.
7382 /// \brief Try to get a scalar value for a specific element of a vector.
7384 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7385 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7386 SelectionDAG &DAG) {
7387 MVT VT = V.getSimpleValueType();
7388 MVT EltVT = VT.getVectorElementType();
7389 while (V.getOpcode() == ISD::BITCAST)
7390 V = V.getOperand(0);
7391 // If the bitcasts shift the element size, we can't extract an equivalent
7393 MVT NewVT = V.getSimpleValueType();
7394 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7397 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7398 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7399 // Ensure the scalar operand is the same size as the destination.
7400 // FIXME: Add support for scalar truncation where possible.
7401 SDValue S = V.getOperand(Idx);
7402 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7403 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7409 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7411 /// This is particularly important because the set of instructions varies
7412 /// significantly based on whether the operand is a load or not.
7413 static bool isShuffleFoldableLoad(SDValue V) {
7414 while (V.getOpcode() == ISD::BITCAST)
7415 V = V.getOperand(0);
7417 return ISD::isNON_EXTLoad(V.getNode());
7420 /// \brief Try to lower insertion of a single element into a zero vector.
7422 /// This is a common pattern that we have especially efficient patterns to lower
7423 /// across all subtarget feature sets.
7424 static SDValue lowerVectorShuffleAsElementInsertion(
7425 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7426 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7427 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7429 MVT EltVT = VT.getVectorElementType();
7431 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7432 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7434 bool IsV1Zeroable = true;
7435 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7436 if (i != V2Index && !Zeroable[i]) {
7437 IsV1Zeroable = false;
7441 // Check for a single input from a SCALAR_TO_VECTOR node.
7442 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7443 // all the smarts here sunk into that routine. However, the current
7444 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7445 // vector shuffle lowering is dead.
7446 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7448 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7449 // We need to zext the scalar if it is smaller than an i32.
7450 V2S = DAG.getBitcast(EltVT, V2S);
7451 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7452 // Using zext to expand a narrow element won't work for non-zero
7457 // Zero-extend directly to i32.
7459 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7461 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7462 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7463 EltVT == MVT::i16) {
7464 // Either not inserting from the low element of the input or the input
7465 // element size is too small to use VZEXT_MOVL to clear the high bits.
7469 if (!IsV1Zeroable) {
7470 // If V1 can't be treated as a zero vector we have fewer options to lower
7471 // this. We can't support integer vectors or non-zero targets cheaply, and
7472 // the V1 elements can't be permuted in any way.
7473 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7474 if (!VT.isFloatingPoint() || V2Index != 0)
7476 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7477 V1Mask[V2Index] = -1;
7478 if (!isNoopShuffleMask(V1Mask))
7480 // This is essentially a special case blend operation, but if we have
7481 // general purpose blend operations, they are always faster. Bail and let
7482 // the rest of the lowering handle these as blends.
7483 if (Subtarget->hasSSE41())
7486 // Otherwise, use MOVSD or MOVSS.
7487 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7488 "Only two types of floating point element types to handle!");
7489 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7493 // This lowering only works for the low element with floating point vectors.
7494 if (VT.isFloatingPoint() && V2Index != 0)
7497 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7499 V2 = DAG.getBitcast(VT, V2);
7502 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7503 // the desired position. Otherwise it is more efficient to do a vector
7504 // shift left. We know that we can do a vector shift left because all
7505 // the inputs are zero.
7506 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7507 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7508 V2Shuffle[V2Index] = 0;
7509 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7511 V2 = DAG.getBitcast(MVT::v2i64, V2);
7513 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7514 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7515 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7516 DAG.getDataLayout(), VT)));
7517 V2 = DAG.getBitcast(VT, V2);
7523 /// \brief Try to lower broadcast of a single element.
7525 /// For convenience, this code also bundles all of the subtarget feature set
7526 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7527 /// a convenient way to factor it out.
7528 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7530 const X86Subtarget *Subtarget,
7531 SelectionDAG &DAG) {
7532 if (!Subtarget->hasAVX())
7534 if (VT.isInteger() && !Subtarget->hasAVX2())
7537 // Check that the mask is a broadcast.
7538 int BroadcastIdx = -1;
7540 if (M >= 0 && BroadcastIdx == -1)
7542 else if (M >= 0 && M != BroadcastIdx)
7545 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7546 "a sorted mask where the broadcast "
7549 // Go up the chain of (vector) values to find a scalar load that we can
7550 // combine with the broadcast.
7552 switch (V.getOpcode()) {
7553 case ISD::CONCAT_VECTORS: {
7554 int OperandSize = Mask.size() / V.getNumOperands();
7555 V = V.getOperand(BroadcastIdx / OperandSize);
7556 BroadcastIdx %= OperandSize;
7560 case ISD::INSERT_SUBVECTOR: {
7561 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7562 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7566 int BeginIdx = (int)ConstantIdx->getZExtValue();
7568 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7569 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7570 BroadcastIdx -= BeginIdx;
7581 // Check if this is a broadcast of a scalar. We special case lowering
7582 // for scalars so that we can more effectively fold with loads.
7583 // First, look through bitcast: if the original value has a larger element
7584 // type than the shuffle, the broadcast element is in essence truncated.
7585 // Make that explicit to ease folding.
7586 if (V.getOpcode() == ISD::BITCAST && VT.isInteger()) {
7587 EVT EltVT = VT.getVectorElementType();
7588 SDValue V0 = V.getOperand(0);
7589 EVT V0VT = V0.getValueType();
7591 if (V0VT.isInteger() && V0VT.getVectorElementType().bitsGT(EltVT) &&
7592 ((V0.getOpcode() == ISD::BUILD_VECTOR ||
7593 (V0.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)))) {
7594 V = DAG.getNode(ISD::TRUNCATE, DL, EltVT, V0.getOperand(BroadcastIdx));
7599 // Also check the simpler case, where we can directly reuse the scalar.
7600 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7601 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7602 V = V.getOperand(BroadcastIdx);
7604 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7605 // Only AVX2 has register broadcasts.
7606 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7608 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7609 // We can't broadcast from a vector register without AVX2, and we can only
7610 // broadcast from the zero-element of a vector register.
7614 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7617 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7618 // INSERTPS when the V1 elements are already in the correct locations
7619 // because otherwise we can just always use two SHUFPS instructions which
7620 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7621 // perform INSERTPS if a single V1 element is out of place and all V2
7622 // elements are zeroable.
7623 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7625 SelectionDAG &DAG) {
7626 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7627 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7628 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7629 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7631 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7634 int V1DstIndex = -1;
7635 int V2DstIndex = -1;
7636 bool V1UsedInPlace = false;
7638 for (int i = 0; i < 4; ++i) {
7639 // Synthesize a zero mask from the zeroable elements (includes undefs).
7645 // Flag if we use any V1 inputs in place.
7647 V1UsedInPlace = true;
7651 // We can only insert a single non-zeroable element.
7652 if (V1DstIndex != -1 || V2DstIndex != -1)
7656 // V1 input out of place for insertion.
7659 // V2 input for insertion.
7664 // Don't bother if we have no (non-zeroable) element for insertion.
7665 if (V1DstIndex == -1 && V2DstIndex == -1)
7668 // Determine element insertion src/dst indices. The src index is from the
7669 // start of the inserted vector, not the start of the concatenated vector.
7670 unsigned V2SrcIndex = 0;
7671 if (V1DstIndex != -1) {
7672 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7673 // and don't use the original V2 at all.
7674 V2SrcIndex = Mask[V1DstIndex];
7675 V2DstIndex = V1DstIndex;
7678 V2SrcIndex = Mask[V2DstIndex] - 4;
7681 // If no V1 inputs are used in place, then the result is created only from
7682 // the zero mask and the V2 insertion - so remove V1 dependency.
7684 V1 = DAG.getUNDEF(MVT::v4f32);
7686 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7687 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7689 // Insert the V2 element into the desired position.
7691 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7692 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7695 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7696 /// UNPCK instruction.
7698 /// This specifically targets cases where we end up with alternating between
7699 /// the two inputs, and so can permute them into something that feeds a single
7700 /// UNPCK instruction. Note that this routine only targets integer vectors
7701 /// because for floating point vectors we have a generalized SHUFPS lowering
7702 /// strategy that handles everything that doesn't *exactly* match an unpack,
7703 /// making this clever lowering unnecessary.
7704 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7705 SDValue V2, ArrayRef<int> Mask,
7706 SelectionDAG &DAG) {
7707 assert(!VT.isFloatingPoint() &&
7708 "This routine only supports integer vectors.");
7709 assert(!isSingleInputShuffleMask(Mask) &&
7710 "This routine should only be used when blending two inputs.");
7711 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7713 int Size = Mask.size();
7715 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7716 return M >= 0 && M % Size < Size / 2;
7718 int NumHiInputs = std::count_if(
7719 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7721 bool UnpackLo = NumLoInputs >= NumHiInputs;
7723 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7724 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7725 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7727 for (int i = 0; i < Size; ++i) {
7731 // Each element of the unpack contains Scale elements from this mask.
7732 int UnpackIdx = i / Scale;
7734 // We only handle the case where V1 feeds the first slots of the unpack.
7735 // We rely on canonicalization to ensure this is the case.
7736 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7739 // Setup the mask for this input. The indexing is tricky as we have to
7740 // handle the unpack stride.
7741 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7742 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7746 // If we will have to shuffle both inputs to use the unpack, check whether
7747 // we can just unpack first and shuffle the result. If so, skip this unpack.
7748 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7749 !isNoopShuffleMask(V2Mask))
7752 // Shuffle the inputs into place.
7753 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7754 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7756 // Cast the inputs to the type we will use to unpack them.
7757 V1 = DAG.getBitcast(UnpackVT, V1);
7758 V2 = DAG.getBitcast(UnpackVT, V2);
7760 // Unpack the inputs and cast the result back to the desired type.
7761 return DAG.getBitcast(
7762 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7766 // We try each unpack from the largest to the smallest to try and find one
7767 // that fits this mask.
7768 int OrigNumElements = VT.getVectorNumElements();
7769 int OrigScalarSize = VT.getScalarSizeInBits();
7770 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7771 int Scale = ScalarSize / OrigScalarSize;
7772 int NumElements = OrigNumElements / Scale;
7773 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7774 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7778 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7780 if (NumLoInputs == 0 || NumHiInputs == 0) {
7781 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7782 "We have to have *some* inputs!");
7783 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7785 // FIXME: We could consider the total complexity of the permute of each
7786 // possible unpacking. Or at the least we should consider how many
7787 // half-crossings are created.
7788 // FIXME: We could consider commuting the unpacks.
7790 SmallVector<int, 32> PermMask;
7791 PermMask.assign(Size, -1);
7792 for (int i = 0; i < Size; ++i) {
7796 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7799 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7801 return DAG.getVectorShuffle(
7802 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7804 DAG.getUNDEF(VT), PermMask);
7810 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7812 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7813 /// support for floating point shuffles but not integer shuffles. These
7814 /// instructions will incur a domain crossing penalty on some chips though so
7815 /// it is better to avoid lowering through this for integer vectors where
7817 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7818 const X86Subtarget *Subtarget,
7819 SelectionDAG &DAG) {
7821 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7822 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7823 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7824 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7825 ArrayRef<int> Mask = SVOp->getMask();
7826 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7828 if (isSingleInputShuffleMask(Mask)) {
7829 // Use low duplicate instructions for masks that match their pattern.
7830 if (Subtarget->hasSSE3())
7831 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7832 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7834 // Straight shuffle of a single input vector. Simulate this by using the
7835 // single input as both of the "inputs" to this instruction..
7836 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7838 if (Subtarget->hasAVX()) {
7839 // If we have AVX, we can use VPERMILPS which will allow folding a load
7840 // into the shuffle.
7841 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7842 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7845 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7846 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7848 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7849 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7851 // If we have a single input, insert that into V1 if we can do so cheaply.
7852 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7853 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7854 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7856 // Try inverting the insertion since for v2 masks it is easy to do and we
7857 // can't reliably sort the mask one way or the other.
7858 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7859 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7860 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7861 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7865 // Try to use one of the special instruction patterns to handle two common
7866 // blend patterns if a zero-blend above didn't work.
7867 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7868 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7869 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7870 // We can either use a special instruction to load over the low double or
7871 // to move just the low double.
7873 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7875 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7877 if (Subtarget->hasSSE41())
7878 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7882 // Use dedicated unpack instructions for masks that match their pattern.
7883 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7884 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7885 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7886 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7888 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7889 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7890 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7893 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7895 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7896 /// the integer unit to minimize domain crossing penalties. However, for blends
7897 /// it falls back to the floating point shuffle operation with appropriate bit
7899 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7900 const X86Subtarget *Subtarget,
7901 SelectionDAG &DAG) {
7903 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7904 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7905 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7906 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7907 ArrayRef<int> Mask = SVOp->getMask();
7908 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7910 if (isSingleInputShuffleMask(Mask)) {
7911 // Check for being able to broadcast a single element.
7912 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7913 Mask, Subtarget, DAG))
7916 // Straight shuffle of a single input vector. For everything from SSE2
7917 // onward this has a single fast instruction with no scary immediates.
7918 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7919 V1 = DAG.getBitcast(MVT::v4i32, V1);
7920 int WidenedMask[4] = {
7921 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7922 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7923 return DAG.getBitcast(
7925 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7926 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7928 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7929 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7930 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7931 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7933 // If we have a blend of two PACKUS operations an the blend aligns with the
7934 // low and half halves, we can just merge the PACKUS operations. This is
7935 // particularly important as it lets us merge shuffles that this routine itself
7937 auto GetPackNode = [](SDValue V) {
7938 while (V.getOpcode() == ISD::BITCAST)
7939 V = V.getOperand(0);
7941 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7943 if (SDValue V1Pack = GetPackNode(V1))
7944 if (SDValue V2Pack = GetPackNode(V2))
7945 return DAG.getBitcast(MVT::v2i64,
7946 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7947 Mask[0] == 0 ? V1Pack.getOperand(0)
7948 : V1Pack.getOperand(1),
7949 Mask[1] == 2 ? V2Pack.getOperand(0)
7950 : V2Pack.getOperand(1)));
7952 // Try to use shift instructions.
7954 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7957 // When loading a scalar and then shuffling it into a vector we can often do
7958 // the insertion cheaply.
7959 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7960 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7962 // Try inverting the insertion since for v2 masks it is easy to do and we
7963 // can't reliably sort the mask one way or the other.
7964 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7965 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7966 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7969 // We have different paths for blend lowering, but they all must use the
7970 // *exact* same predicate.
7971 bool IsBlendSupported = Subtarget->hasSSE41();
7972 if (IsBlendSupported)
7973 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7977 // Use dedicated unpack instructions for masks that match their pattern.
7978 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7979 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7980 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7981 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7983 // Try to use byte rotation instructions.
7984 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7985 if (Subtarget->hasSSSE3())
7986 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7987 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7990 // If we have direct support for blends, we should lower by decomposing into
7991 // a permute. That will be faster than the domain cross.
7992 if (IsBlendSupported)
7993 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7996 // We implement this with SHUFPD which is pretty lame because it will likely
7997 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7998 // However, all the alternatives are still more cycles and newer chips don't
7999 // have this problem. It would be really nice if x86 had better shuffles here.
8000 V1 = DAG.getBitcast(MVT::v2f64, V1);
8001 V2 = DAG.getBitcast(MVT::v2f64, V2);
8002 return DAG.getBitcast(MVT::v2i64,
8003 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8006 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8008 /// This is used to disable more specialized lowerings when the shufps lowering
8009 /// will happen to be efficient.
8010 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8011 // This routine only handles 128-bit shufps.
8012 assert(Mask.size() == 4 && "Unsupported mask size!");
8014 // To lower with a single SHUFPS we need to have the low half and high half
8015 // each requiring a single input.
8016 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8018 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8024 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8026 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8027 /// It makes no assumptions about whether this is the *best* lowering, it simply
8029 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8030 ArrayRef<int> Mask, SDValue V1,
8031 SDValue V2, SelectionDAG &DAG) {
8032 SDValue LowV = V1, HighV = V2;
8033 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8036 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8038 if (NumV2Elements == 1) {
8040 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8043 // Compute the index adjacent to V2Index and in the same half by toggling
8045 int V2AdjIndex = V2Index ^ 1;
8047 if (Mask[V2AdjIndex] == -1) {
8048 // Handles all the cases where we have a single V2 element and an undef.
8049 // This will only ever happen in the high lanes because we commute the
8050 // vector otherwise.
8052 std::swap(LowV, HighV);
8053 NewMask[V2Index] -= 4;
8055 // Handle the case where the V2 element ends up adjacent to a V1 element.
8056 // To make this work, blend them together as the first step.
8057 int V1Index = V2AdjIndex;
8058 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8059 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8060 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8062 // Now proceed to reconstruct the final blend as we have the necessary
8063 // high or low half formed.
8070 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8071 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8073 } else if (NumV2Elements == 2) {
8074 if (Mask[0] < 4 && Mask[1] < 4) {
8075 // Handle the easy case where we have V1 in the low lanes and V2 in the
8079 } else if (Mask[2] < 4 && Mask[3] < 4) {
8080 // We also handle the reversed case because this utility may get called
8081 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8082 // arrange things in the right direction.
8088 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8089 // trying to place elements directly, just blend them and set up the final
8090 // shuffle to place them.
8092 // The first two blend mask elements are for V1, the second two are for
8094 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8095 Mask[2] < 4 ? Mask[2] : Mask[3],
8096 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8097 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8098 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8099 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8101 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8104 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8105 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8106 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8107 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8110 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8111 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8114 /// \brief Lower 4-lane 32-bit floating point shuffles.
8116 /// Uses instructions exclusively from the floating point unit to minimize
8117 /// domain crossing penalties, as these are sufficient to implement all v4f32
8119 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8120 const X86Subtarget *Subtarget,
8121 SelectionDAG &DAG) {
8123 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8124 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8125 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8126 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8127 ArrayRef<int> Mask = SVOp->getMask();
8128 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8131 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8133 if (NumV2Elements == 0) {
8134 // Check for being able to broadcast a single element.
8135 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8136 Mask, Subtarget, DAG))
8139 // Use even/odd duplicate instructions for masks that match their pattern.
8140 if (Subtarget->hasSSE3()) {
8141 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8142 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8143 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8144 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8147 if (Subtarget->hasAVX()) {
8148 // If we have AVX, we can use VPERMILPS which will allow folding a load
8149 // into the shuffle.
8150 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8151 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8154 // Otherwise, use a straight shuffle of a single input vector. We pass the
8155 // input vector to both operands to simulate this with a SHUFPS.
8156 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8157 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8160 // There are special ways we can lower some single-element blends. However, we
8161 // have custom ways we can lower more complex single-element blends below that
8162 // we defer to if both this and BLENDPS fail to match, so restrict this to
8163 // when the V2 input is targeting element 0 of the mask -- that is the fast
8165 if (NumV2Elements == 1 && Mask[0] >= 4)
8166 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8167 Mask, Subtarget, DAG))
8170 if (Subtarget->hasSSE41()) {
8171 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8175 // Use INSERTPS if we can complete the shuffle efficiently.
8176 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8179 if (!isSingleSHUFPSMask(Mask))
8180 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8181 DL, MVT::v4f32, V1, V2, Mask, DAG))
8185 // Use dedicated unpack instructions for masks that match their pattern.
8186 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8187 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8188 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8189 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8190 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8191 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8192 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8193 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8195 // Otherwise fall back to a SHUFPS lowering strategy.
8196 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8199 /// \brief Lower 4-lane i32 vector shuffles.
8201 /// We try to handle these with integer-domain shuffles where we can, but for
8202 /// blends we use the floating point domain blend instructions.
8203 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8204 const X86Subtarget *Subtarget,
8205 SelectionDAG &DAG) {
8207 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8208 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8209 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8210 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8211 ArrayRef<int> Mask = SVOp->getMask();
8212 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8214 // Whenever we can lower this as a zext, that instruction is strictly faster
8215 // than any alternative. It also allows us to fold memory operands into the
8216 // shuffle in many cases.
8217 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8218 Mask, Subtarget, DAG))
8222 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8224 if (NumV2Elements == 0) {
8225 // Check for being able to broadcast a single element.
8226 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8227 Mask, Subtarget, DAG))
8230 // Straight shuffle of a single input vector. For everything from SSE2
8231 // onward this has a single fast instruction with no scary immediates.
8232 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8233 // but we aren't actually going to use the UNPCK instruction because doing
8234 // so prevents folding a load into this instruction or making a copy.
8235 const int UnpackLoMask[] = {0, 0, 1, 1};
8236 const int UnpackHiMask[] = {2, 2, 3, 3};
8237 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8238 Mask = UnpackLoMask;
8239 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8240 Mask = UnpackHiMask;
8242 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8243 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8246 // Try to use shift instructions.
8248 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8251 // There are special ways we can lower some single-element blends.
8252 if (NumV2Elements == 1)
8253 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8254 Mask, Subtarget, DAG))
8257 // We have different paths for blend lowering, but they all must use the
8258 // *exact* same predicate.
8259 bool IsBlendSupported = Subtarget->hasSSE41();
8260 if (IsBlendSupported)
8261 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8265 if (SDValue Masked =
8266 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8269 // Use dedicated unpack instructions for masks that match their pattern.
8270 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8271 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8272 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8273 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8274 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8275 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8276 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8277 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8279 // Try to use byte rotation instructions.
8280 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8281 if (Subtarget->hasSSSE3())
8282 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8283 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8286 // If we have direct support for blends, we should lower by decomposing into
8287 // a permute. That will be faster than the domain cross.
8288 if (IsBlendSupported)
8289 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8292 // Try to lower by permuting the inputs into an unpack instruction.
8293 if (SDValue Unpack =
8294 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8297 // We implement this with SHUFPS because it can blend from two vectors.
8298 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8299 // up the inputs, bypassing domain shift penalties that we would encur if we
8300 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8302 return DAG.getBitcast(
8304 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8305 DAG.getBitcast(MVT::v4f32, V2), Mask));
8308 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8309 /// shuffle lowering, and the most complex part.
8311 /// The lowering strategy is to try to form pairs of input lanes which are
8312 /// targeted at the same half of the final vector, and then use a dword shuffle
8313 /// to place them onto the right half, and finally unpack the paired lanes into
8314 /// their final position.
8316 /// The exact breakdown of how to form these dword pairs and align them on the
8317 /// correct sides is really tricky. See the comments within the function for
8318 /// more of the details.
8320 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8321 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8322 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8323 /// vector, form the analogous 128-bit 8-element Mask.
8324 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8325 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8326 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8327 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8328 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8330 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8331 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8332 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8334 SmallVector<int, 4> LoInputs;
8335 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8336 [](int M) { return M >= 0; });
8337 std::sort(LoInputs.begin(), LoInputs.end());
8338 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8339 SmallVector<int, 4> HiInputs;
8340 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8341 [](int M) { return M >= 0; });
8342 std::sort(HiInputs.begin(), HiInputs.end());
8343 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8345 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8346 int NumHToL = LoInputs.size() - NumLToL;
8348 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8349 int NumHToH = HiInputs.size() - NumLToH;
8350 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8351 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8352 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8353 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8355 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8356 // such inputs we can swap two of the dwords across the half mark and end up
8357 // with <=2 inputs to each half in each half. Once there, we can fall through
8358 // to the generic code below. For example:
8360 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8361 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8363 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8364 // and an existing 2-into-2 on the other half. In this case we may have to
8365 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8366 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8367 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8368 // because any other situation (including a 3-into-1 or 1-into-3 in the other
8369 // half than the one we target for fixing) will be fixed when we re-enter this
8370 // path. We will also combine away any sequence of PSHUFD instructions that
8371 // result into a single instruction. Here is an example of the tricky case:
8373 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8374 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8376 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8378 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8379 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8381 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8382 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8384 // The result is fine to be handled by the generic logic.
8385 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8386 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8387 int AOffset, int BOffset) {
8388 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8389 "Must call this with A having 3 or 1 inputs from the A half.");
8390 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8391 "Must call this with B having 1 or 3 inputs from the B half.");
8392 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8393 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8395 bool ThreeAInputs = AToAInputs.size() == 3;
8397 // Compute the index of dword with only one word among the three inputs in
8398 // a half by taking the sum of the half with three inputs and subtracting
8399 // the sum of the actual three inputs. The difference is the remaining
8402 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8403 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8404 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8405 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8406 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8407 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8408 int TripleNonInputIdx =
8409 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8410 TripleDWord = TripleNonInputIdx / 2;
8412 // We use xor with one to compute the adjacent DWord to whichever one the
8414 OneInputDWord = (OneInput / 2) ^ 1;
8416 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8417 // and BToA inputs. If there is also such a problem with the BToB and AToB
8418 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8419 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8420 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8421 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8422 // Compute how many inputs will be flipped by swapping these DWords. We
8424 // to balance this to ensure we don't form a 3-1 shuffle in the other
8426 int NumFlippedAToBInputs =
8427 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8428 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8429 int NumFlippedBToBInputs =
8430 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8431 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8432 if ((NumFlippedAToBInputs == 1 &&
8433 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8434 (NumFlippedBToBInputs == 1 &&
8435 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8436 // We choose whether to fix the A half or B half based on whether that
8437 // half has zero flipped inputs. At zero, we may not be able to fix it
8438 // with that half. We also bias towards fixing the B half because that
8439 // will more commonly be the high half, and we have to bias one way.
8440 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8441 ArrayRef<int> Inputs) {
8442 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8443 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8444 PinnedIdx ^ 1) != Inputs.end();
8445 // Determine whether the free index is in the flipped dword or the
8446 // unflipped dword based on where the pinned index is. We use this bit
8447 // in an xor to conditionally select the adjacent dword.
8448 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8449 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8450 FixFreeIdx) != Inputs.end();
8451 if (IsFixIdxInput == IsFixFreeIdxInput)
8453 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8454 FixFreeIdx) != Inputs.end();
8455 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8456 "We need to be changing the number of flipped inputs!");
8457 int PSHUFHalfMask[] = {0, 1, 2, 3};
8458 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8459 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8461 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8464 if (M != -1 && M == FixIdx)
8466 else if (M != -1 && M == FixFreeIdx)
8469 if (NumFlippedBToBInputs != 0) {
8471 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8472 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8474 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8475 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8476 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8481 int PSHUFDMask[] = {0, 1, 2, 3};
8482 PSHUFDMask[ADWord] = BDWord;
8483 PSHUFDMask[BDWord] = ADWord;
8486 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8487 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8489 // Adjust the mask to match the new locations of A and B.
8491 if (M != -1 && M/2 == ADWord)
8492 M = 2 * BDWord + M % 2;
8493 else if (M != -1 && M/2 == BDWord)
8494 M = 2 * ADWord + M % 2;
8496 // Recurse back into this routine to re-compute state now that this isn't
8497 // a 3 and 1 problem.
8498 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8501 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8502 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8503 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8504 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8506 // At this point there are at most two inputs to the low and high halves from
8507 // each half. That means the inputs can always be grouped into dwords and
8508 // those dwords can then be moved to the correct half with a dword shuffle.
8509 // We use at most one low and one high word shuffle to collect these paired
8510 // inputs into dwords, and finally a dword shuffle to place them.
8511 int PSHUFLMask[4] = {-1, -1, -1, -1};
8512 int PSHUFHMask[4] = {-1, -1, -1, -1};
8513 int PSHUFDMask[4] = {-1, -1, -1, -1};
8515 // First fix the masks for all the inputs that are staying in their
8516 // original halves. This will then dictate the targets of the cross-half
8518 auto fixInPlaceInputs =
8519 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8520 MutableArrayRef<int> SourceHalfMask,
8521 MutableArrayRef<int> HalfMask, int HalfOffset) {
8522 if (InPlaceInputs.empty())
8524 if (InPlaceInputs.size() == 1) {
8525 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8526 InPlaceInputs[0] - HalfOffset;
8527 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8530 if (IncomingInputs.empty()) {
8531 // Just fix all of the in place inputs.
8532 for (int Input : InPlaceInputs) {
8533 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8534 PSHUFDMask[Input / 2] = Input / 2;
8539 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8540 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8541 InPlaceInputs[0] - HalfOffset;
8542 // Put the second input next to the first so that they are packed into
8543 // a dword. We find the adjacent index by toggling the low bit.
8544 int AdjIndex = InPlaceInputs[0] ^ 1;
8545 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8546 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8547 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8549 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8550 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8552 // Now gather the cross-half inputs and place them into a free dword of
8553 // their target half.
8554 // FIXME: This operation could almost certainly be simplified dramatically to
8555 // look more like the 3-1 fixing operation.
8556 auto moveInputsToRightHalf = [&PSHUFDMask](
8557 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8558 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8559 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8561 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8562 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8564 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8566 int LowWord = Word & ~1;
8567 int HighWord = Word | 1;
8568 return isWordClobbered(SourceHalfMask, LowWord) ||
8569 isWordClobbered(SourceHalfMask, HighWord);
8572 if (IncomingInputs.empty())
8575 if (ExistingInputs.empty()) {
8576 // Map any dwords with inputs from them into the right half.
8577 for (int Input : IncomingInputs) {
8578 // If the source half mask maps over the inputs, turn those into
8579 // swaps and use the swapped lane.
8580 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8581 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8582 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8583 Input - SourceOffset;
8584 // We have to swap the uses in our half mask in one sweep.
8585 for (int &M : HalfMask)
8586 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8588 else if (M == Input)
8589 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8591 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8592 Input - SourceOffset &&
8593 "Previous placement doesn't match!");
8595 // Note that this correctly re-maps both when we do a swap and when
8596 // we observe the other side of the swap above. We rely on that to
8597 // avoid swapping the members of the input list directly.
8598 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8601 // Map the input's dword into the correct half.
8602 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8603 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8605 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8607 "Previous placement doesn't match!");
8610 // And just directly shift any other-half mask elements to be same-half
8611 // as we will have mirrored the dword containing the element into the
8612 // same position within that half.
8613 for (int &M : HalfMask)
8614 if (M >= SourceOffset && M < SourceOffset + 4) {
8615 M = M - SourceOffset + DestOffset;
8616 assert(M >= 0 && "This should never wrap below zero!");
8621 // Ensure we have the input in a viable dword of its current half. This
8622 // is particularly tricky because the original position may be clobbered
8623 // by inputs being moved and *staying* in that half.
8624 if (IncomingInputs.size() == 1) {
8625 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8626 int InputFixed = std::find(std::begin(SourceHalfMask),
8627 std::end(SourceHalfMask), -1) -
8628 std::begin(SourceHalfMask) + SourceOffset;
8629 SourceHalfMask[InputFixed - SourceOffset] =
8630 IncomingInputs[0] - SourceOffset;
8631 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8633 IncomingInputs[0] = InputFixed;
8635 } else if (IncomingInputs.size() == 2) {
8636 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8637 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8638 // We have two non-adjacent or clobbered inputs we need to extract from
8639 // the source half. To do this, we need to map them into some adjacent
8640 // dword slot in the source mask.
8641 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8642 IncomingInputs[1] - SourceOffset};
8644 // If there is a free slot in the source half mask adjacent to one of
8645 // the inputs, place the other input in it. We use (Index XOR 1) to
8646 // compute an adjacent index.
8647 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8648 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8649 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8650 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8651 InputsFixed[1] = InputsFixed[0] ^ 1;
8652 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8653 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8654 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8655 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8656 InputsFixed[0] = InputsFixed[1] ^ 1;
8657 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8658 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8659 // The two inputs are in the same DWord but it is clobbered and the
8660 // adjacent DWord isn't used at all. Move both inputs to the free
8662 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8663 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8664 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8665 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8667 // The only way we hit this point is if there is no clobbering
8668 // (because there are no off-half inputs to this half) and there is no
8669 // free slot adjacent to one of the inputs. In this case, we have to
8670 // swap an input with a non-input.
8671 for (int i = 0; i < 4; ++i)
8672 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8673 "We can't handle any clobbers here!");
8674 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8675 "Cannot have adjacent inputs here!");
8677 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8678 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8680 // We also have to update the final source mask in this case because
8681 // it may need to undo the above swap.
8682 for (int &M : FinalSourceHalfMask)
8683 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8684 M = InputsFixed[1] + SourceOffset;
8685 else if (M == InputsFixed[1] + SourceOffset)
8686 M = (InputsFixed[0] ^ 1) + SourceOffset;
8688 InputsFixed[1] = InputsFixed[0] ^ 1;
8691 // Point everything at the fixed inputs.
8692 for (int &M : HalfMask)
8693 if (M == IncomingInputs[0])
8694 M = InputsFixed[0] + SourceOffset;
8695 else if (M == IncomingInputs[1])
8696 M = InputsFixed[1] + SourceOffset;
8698 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8699 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8702 llvm_unreachable("Unhandled input size!");
8705 // Now hoist the DWord down to the right half.
8706 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8707 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8708 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8709 for (int &M : HalfMask)
8710 for (int Input : IncomingInputs)
8712 M = FreeDWord * 2 + Input % 2;
8714 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8715 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8716 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8717 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8719 // Now enact all the shuffles we've computed to move the inputs into their
8721 if (!isNoopShuffleMask(PSHUFLMask))
8722 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8723 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8724 if (!isNoopShuffleMask(PSHUFHMask))
8725 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8726 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8727 if (!isNoopShuffleMask(PSHUFDMask))
8730 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8731 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8733 // At this point, each half should contain all its inputs, and we can then
8734 // just shuffle them into their final position.
8735 assert(std::count_if(LoMask.begin(), LoMask.end(),
8736 [](int M) { return M >= 4; }) == 0 &&
8737 "Failed to lift all the high half inputs to the low mask!");
8738 assert(std::count_if(HiMask.begin(), HiMask.end(),
8739 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8740 "Failed to lift all the low half inputs to the high mask!");
8742 // Do a half shuffle for the low mask.
8743 if (!isNoopShuffleMask(LoMask))
8744 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8745 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8747 // Do a half shuffle with the high mask after shifting its values down.
8748 for (int &M : HiMask)
8751 if (!isNoopShuffleMask(HiMask))
8752 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8753 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8758 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8759 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8760 SDValue V2, ArrayRef<int> Mask,
8761 SelectionDAG &DAG, bool &V1InUse,
8763 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8769 int Size = Mask.size();
8770 int Scale = 16 / Size;
8771 for (int i = 0; i < 16; ++i) {
8772 if (Mask[i / Scale] == -1) {
8773 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8775 const int ZeroMask = 0x80;
8776 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8778 int V2Idx = Mask[i / Scale] < Size
8780 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8781 if (Zeroable[i / Scale])
8782 V1Idx = V2Idx = ZeroMask;
8783 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8784 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8785 V1InUse |= (ZeroMask != V1Idx);
8786 V2InUse |= (ZeroMask != V2Idx);
8791 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8792 DAG.getBitcast(MVT::v16i8, V1),
8793 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8795 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8796 DAG.getBitcast(MVT::v16i8, V2),
8797 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8799 // If we need shuffled inputs from both, blend the two.
8801 if (V1InUse && V2InUse)
8802 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8804 V = V1InUse ? V1 : V2;
8806 // Cast the result back to the correct type.
8807 return DAG.getBitcast(VT, V);
8810 /// \brief Generic lowering of 8-lane i16 shuffles.
8812 /// This handles both single-input shuffles and combined shuffle/blends with
8813 /// two inputs. The single input shuffles are immediately delegated to
8814 /// a dedicated lowering routine.
8816 /// The blends are lowered in one of three fundamental ways. If there are few
8817 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8818 /// of the input is significantly cheaper when lowered as an interleaving of
8819 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8820 /// halves of the inputs separately (making them have relatively few inputs)
8821 /// and then concatenate them.
8822 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8823 const X86Subtarget *Subtarget,
8824 SelectionDAG &DAG) {
8826 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8827 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8828 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8829 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8830 ArrayRef<int> OrigMask = SVOp->getMask();
8831 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8832 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8833 MutableArrayRef<int> Mask(MaskStorage);
8835 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8837 // Whenever we can lower this as a zext, that instruction is strictly faster
8838 // than any alternative.
8839 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8840 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8843 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8845 auto isV2 = [](int M) { return M >= 8; };
8847 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8849 if (NumV2Inputs == 0) {
8850 // Check for being able to broadcast a single element.
8851 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8852 Mask, Subtarget, DAG))
8855 // Try to use shift instructions.
8857 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8860 // Use dedicated unpack instructions for masks that match their pattern.
8861 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8862 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8863 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8864 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8866 // Try to use byte rotation instructions.
8867 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8868 Mask, Subtarget, DAG))
8871 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8875 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8876 "All single-input shuffles should be canonicalized to be V1-input "
8879 // Try to use shift instructions.
8881 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8884 // See if we can use SSE4A Extraction / Insertion.
8885 if (Subtarget->hasSSE4A())
8886 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8889 // There are special ways we can lower some single-element blends.
8890 if (NumV2Inputs == 1)
8891 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8892 Mask, Subtarget, DAG))
8895 // We have different paths for blend lowering, but they all must use the
8896 // *exact* same predicate.
8897 bool IsBlendSupported = Subtarget->hasSSE41();
8898 if (IsBlendSupported)
8899 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8903 if (SDValue Masked =
8904 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8907 // Use dedicated unpack instructions for masks that match their pattern.
8908 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8909 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8910 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8911 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8913 // Try to use byte rotation instructions.
8914 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8915 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8918 if (SDValue BitBlend =
8919 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8922 if (SDValue Unpack =
8923 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8926 // If we can't directly blend but can use PSHUFB, that will be better as it
8927 // can both shuffle and set up the inefficient blend.
8928 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8929 bool V1InUse, V2InUse;
8930 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8934 // We can always bit-blend if we have to so the fallback strategy is to
8935 // decompose into single-input permutes and blends.
8936 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8940 /// \brief Check whether a compaction lowering can be done by dropping even
8941 /// elements and compute how many times even elements must be dropped.
8943 /// This handles shuffles which take every Nth element where N is a power of
8944 /// two. Example shuffle masks:
8946 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8947 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8948 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8949 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8950 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8951 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8953 /// Any of these lanes can of course be undef.
8955 /// This routine only supports N <= 3.
8956 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8959 /// \returns N above, or the number of times even elements must be dropped if
8960 /// there is such a number. Otherwise returns zero.
8961 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8962 // Figure out whether we're looping over two inputs or just one.
8963 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8965 // The modulus for the shuffle vector entries is based on whether this is
8966 // a single input or not.
8967 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8968 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8969 "We should only be called with masks with a power-of-2 size!");
8971 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8973 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8974 // and 2^3 simultaneously. This is because we may have ambiguity with
8975 // partially undef inputs.
8976 bool ViableForN[3] = {true, true, true};
8978 for (int i = 0, e = Mask.size(); i < e; ++i) {
8979 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8984 bool IsAnyViable = false;
8985 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8986 if (ViableForN[j]) {
8989 // The shuffle mask must be equal to (i * 2^N) % M.
8990 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8993 ViableForN[j] = false;
8995 // Early exit if we exhaust the possible powers of two.
9000 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9004 // Return 0 as there is no viable power of two.
9008 /// \brief Generic lowering of v16i8 shuffles.
9010 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9011 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9012 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9013 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9015 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9016 const X86Subtarget *Subtarget,
9017 SelectionDAG &DAG) {
9019 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9020 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9021 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9022 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9023 ArrayRef<int> Mask = SVOp->getMask();
9024 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9026 // Try to use shift instructions.
9028 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9031 // Try to use byte rotation instructions.
9032 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9033 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9036 // Try to use a zext lowering.
9037 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9038 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9041 // See if we can use SSE4A Extraction / Insertion.
9042 if (Subtarget->hasSSE4A())
9043 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9047 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9049 // For single-input shuffles, there are some nicer lowering tricks we can use.
9050 if (NumV2Elements == 0) {
9051 // Check for being able to broadcast a single element.
9052 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9053 Mask, Subtarget, DAG))
9056 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9057 // Notably, this handles splat and partial-splat shuffles more efficiently.
9058 // However, it only makes sense if the pre-duplication shuffle simplifies
9059 // things significantly. Currently, this means we need to be able to
9060 // express the pre-duplication shuffle as an i16 shuffle.
9062 // FIXME: We should check for other patterns which can be widened into an
9063 // i16 shuffle as well.
9064 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9065 for (int i = 0; i < 16; i += 2)
9066 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9071 auto tryToWidenViaDuplication = [&]() -> SDValue {
9072 if (!canWidenViaDuplication(Mask))
9074 SmallVector<int, 4> LoInputs;
9075 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9076 [](int M) { return M >= 0 && M < 8; });
9077 std::sort(LoInputs.begin(), LoInputs.end());
9078 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9080 SmallVector<int, 4> HiInputs;
9081 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9082 [](int M) { return M >= 8; });
9083 std::sort(HiInputs.begin(), HiInputs.end());
9084 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9087 bool TargetLo = LoInputs.size() >= HiInputs.size();
9088 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9089 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9091 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9092 SmallDenseMap<int, int, 8> LaneMap;
9093 for (int I : InPlaceInputs) {
9094 PreDupI16Shuffle[I/2] = I/2;
9097 int j = TargetLo ? 0 : 4, je = j + 4;
9098 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9099 // Check if j is already a shuffle of this input. This happens when
9100 // there are two adjacent bytes after we move the low one.
9101 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9102 // If we haven't yet mapped the input, search for a slot into which
9104 while (j < je && PreDupI16Shuffle[j] != -1)
9108 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9111 // Map this input with the i16 shuffle.
9112 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9115 // Update the lane map based on the mapping we ended up with.
9116 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9118 V1 = DAG.getBitcast(
9120 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9121 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9123 // Unpack the bytes to form the i16s that will be shuffled into place.
9124 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9125 MVT::v16i8, V1, V1);
9127 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9128 for (int i = 0; i < 16; ++i)
9129 if (Mask[i] != -1) {
9130 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9131 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9132 if (PostDupI16Shuffle[i / 2] == -1)
9133 PostDupI16Shuffle[i / 2] = MappedMask;
9135 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9136 "Conflicting entrties in the original shuffle!");
9138 return DAG.getBitcast(
9140 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9141 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9143 if (SDValue V = tryToWidenViaDuplication())
9147 if (SDValue Masked =
9148 lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9151 // Use dedicated unpack instructions for masks that match their pattern.
9152 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9153 0, 16, 1, 17, 2, 18, 3, 19,
9155 4, 20, 5, 21, 6, 22, 7, 23}))
9156 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9157 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9158 8, 24, 9, 25, 10, 26, 11, 27,
9160 12, 28, 13, 29, 14, 30, 15, 31}))
9161 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9163 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9164 // with PSHUFB. It is important to do this before we attempt to generate any
9165 // blends but after all of the single-input lowerings. If the single input
9166 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9167 // want to preserve that and we can DAG combine any longer sequences into
9168 // a PSHUFB in the end. But once we start blending from multiple inputs,
9169 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9170 // and there are *very* few patterns that would actually be faster than the
9171 // PSHUFB approach because of its ability to zero lanes.
9173 // FIXME: The only exceptions to the above are blends which are exact
9174 // interleavings with direct instructions supporting them. We currently don't
9175 // handle those well here.
9176 if (Subtarget->hasSSSE3()) {
9177 bool V1InUse = false;
9178 bool V2InUse = false;
9180 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9181 DAG, V1InUse, V2InUse);
9183 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9184 // do so. This avoids using them to handle blends-with-zero which is
9185 // important as a single pshufb is significantly faster for that.
9186 if (V1InUse && V2InUse) {
9187 if (Subtarget->hasSSE41())
9188 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9189 Mask, Subtarget, DAG))
9192 // We can use an unpack to do the blending rather than an or in some
9193 // cases. Even though the or may be (very minorly) more efficient, we
9194 // preference this lowering because there are common cases where part of
9195 // the complexity of the shuffles goes away when we do the final blend as
9197 // FIXME: It might be worth trying to detect if the unpack-feeding
9198 // shuffles will both be pshufb, in which case we shouldn't bother with
9200 if (SDValue Unpack =
9201 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9208 // There are special ways we can lower some single-element blends.
9209 if (NumV2Elements == 1)
9210 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9211 Mask, Subtarget, DAG))
9214 if (SDValue BitBlend =
9215 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9218 // Check whether a compaction lowering can be done. This handles shuffles
9219 // which take every Nth element for some even N. See the helper function for
9222 // We special case these as they can be particularly efficiently handled with
9223 // the PACKUSB instruction on x86 and they show up in common patterns of
9224 // rearranging bytes to truncate wide elements.
9225 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9226 // NumEvenDrops is the power of two stride of the elements. Another way of
9227 // thinking about it is that we need to drop the even elements this many
9228 // times to get the original input.
9229 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9231 // First we need to zero all the dropped bytes.
9232 assert(NumEvenDrops <= 3 &&
9233 "No support for dropping even elements more than 3 times.");
9234 // We use the mask type to pick which bytes are preserved based on how many
9235 // elements are dropped.
9236 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9237 SDValue ByteClearMask = DAG.getBitcast(
9238 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9239 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9241 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9243 // Now pack things back together.
9244 V1 = DAG.getBitcast(MVT::v8i16, V1);
9245 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9246 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9247 for (int i = 1; i < NumEvenDrops; ++i) {
9248 Result = DAG.getBitcast(MVT::v8i16, Result);
9249 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9255 // Handle multi-input cases by blending single-input shuffles.
9256 if (NumV2Elements > 0)
9257 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9260 // The fallback path for single-input shuffles widens this into two v8i16
9261 // vectors with unpacks, shuffles those, and then pulls them back together
9265 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9266 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9267 for (int i = 0; i < 16; ++i)
9269 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9271 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9273 SDValue VLoHalf, VHiHalf;
9274 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9275 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9277 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9278 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9279 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9280 [](int M) { return M >= 0 && M % 2 == 1; })) {
9281 // Use a mask to drop the high bytes.
9282 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9283 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9284 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9286 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9287 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9289 // Squash the masks to point directly into VLoHalf.
9290 for (int &M : LoBlendMask)
9293 for (int &M : HiBlendMask)
9297 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9298 // VHiHalf so that we can blend them as i16s.
9299 VLoHalf = DAG.getBitcast(
9300 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9301 VHiHalf = DAG.getBitcast(
9302 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9305 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9306 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9308 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9311 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9313 /// This routine breaks down the specific type of 128-bit shuffle and
9314 /// dispatches to the lowering routines accordingly.
9315 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9316 MVT VT, const X86Subtarget *Subtarget,
9317 SelectionDAG &DAG) {
9318 switch (VT.SimpleTy) {
9320 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9322 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9324 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9326 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9328 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9330 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9333 llvm_unreachable("Unimplemented!");
9337 /// \brief Helper function to test whether a shuffle mask could be
9338 /// simplified by widening the elements being shuffled.
9340 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9341 /// leaves it in an unspecified state.
9343 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9344 /// shuffle masks. The latter have the special property of a '-2' representing
9345 /// a zero-ed lane of a vector.
9346 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9347 SmallVectorImpl<int> &WidenedMask) {
9348 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9349 // If both elements are undef, its trivial.
9350 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9351 WidenedMask.push_back(SM_SentinelUndef);
9355 // Check for an undef mask and a mask value properly aligned to fit with
9356 // a pair of values. If we find such a case, use the non-undef mask's value.
9357 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9358 WidenedMask.push_back(Mask[i + 1] / 2);
9361 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9362 WidenedMask.push_back(Mask[i] / 2);
9366 // When zeroing, we need to spread the zeroing across both lanes to widen.
9367 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9368 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9369 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9370 WidenedMask.push_back(SM_SentinelZero);
9376 // Finally check if the two mask values are adjacent and aligned with
9378 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9379 WidenedMask.push_back(Mask[i] / 2);
9383 // Otherwise we can't safely widen the elements used in this shuffle.
9386 assert(WidenedMask.size() == Mask.size() / 2 &&
9387 "Incorrect size of mask after widening the elements!");
9392 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9394 /// This routine just extracts two subvectors, shuffles them independently, and
9395 /// then concatenates them back together. This should work effectively with all
9396 /// AVX vector shuffle types.
9397 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9398 SDValue V2, ArrayRef<int> Mask,
9399 SelectionDAG &DAG) {
9400 assert(VT.getSizeInBits() >= 256 &&
9401 "Only for 256-bit or wider vector shuffles!");
9402 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9403 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9405 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9406 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9408 int NumElements = VT.getVectorNumElements();
9409 int SplitNumElements = NumElements / 2;
9410 MVT ScalarVT = VT.getScalarType();
9411 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9413 // Rather than splitting build-vectors, just build two narrower build
9414 // vectors. This helps shuffling with splats and zeros.
9415 auto SplitVector = [&](SDValue V) {
9416 while (V.getOpcode() == ISD::BITCAST)
9417 V = V->getOperand(0);
9419 MVT OrigVT = V.getSimpleValueType();
9420 int OrigNumElements = OrigVT.getVectorNumElements();
9421 int OrigSplitNumElements = OrigNumElements / 2;
9422 MVT OrigScalarVT = OrigVT.getScalarType();
9423 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9427 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9429 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9430 DAG.getIntPtrConstant(0, DL));
9431 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9432 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9435 SmallVector<SDValue, 16> LoOps, HiOps;
9436 for (int i = 0; i < OrigSplitNumElements; ++i) {
9437 LoOps.push_back(BV->getOperand(i));
9438 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9440 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9441 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9443 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9444 DAG.getBitcast(SplitVT, HiV));
9447 SDValue LoV1, HiV1, LoV2, HiV2;
9448 std::tie(LoV1, HiV1) = SplitVector(V1);
9449 std::tie(LoV2, HiV2) = SplitVector(V2);
9451 // Now create two 4-way blends of these half-width vectors.
9452 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9453 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9454 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9455 for (int i = 0; i < SplitNumElements; ++i) {
9456 int M = HalfMask[i];
9457 if (M >= NumElements) {
9458 if (M >= NumElements + SplitNumElements)
9462 V2BlendMask.push_back(M - NumElements);
9463 V1BlendMask.push_back(-1);
9464 BlendMask.push_back(SplitNumElements + i);
9465 } else if (M >= 0) {
9466 if (M >= SplitNumElements)
9470 V2BlendMask.push_back(-1);
9471 V1BlendMask.push_back(M);
9472 BlendMask.push_back(i);
9474 V2BlendMask.push_back(-1);
9475 V1BlendMask.push_back(-1);
9476 BlendMask.push_back(-1);
9480 // Because the lowering happens after all combining takes place, we need to
9481 // manually combine these blend masks as much as possible so that we create
9482 // a minimal number of high-level vector shuffle nodes.
9484 // First try just blending the halves of V1 or V2.
9485 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9486 return DAG.getUNDEF(SplitVT);
9487 if (!UseLoV2 && !UseHiV2)
9488 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9489 if (!UseLoV1 && !UseHiV1)
9490 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9492 SDValue V1Blend, V2Blend;
9493 if (UseLoV1 && UseHiV1) {
9495 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9497 // We only use half of V1 so map the usage down into the final blend mask.
9498 V1Blend = UseLoV1 ? LoV1 : HiV1;
9499 for (int i = 0; i < SplitNumElements; ++i)
9500 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9501 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9503 if (UseLoV2 && UseHiV2) {
9505 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9507 // We only use half of V2 so map the usage down into the final blend mask.
9508 V2Blend = UseLoV2 ? LoV2 : HiV2;
9509 for (int i = 0; i < SplitNumElements; ++i)
9510 if (BlendMask[i] >= SplitNumElements)
9511 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9513 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9515 SDValue Lo = HalfBlend(LoMask);
9516 SDValue Hi = HalfBlend(HiMask);
9517 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9520 /// \brief Either split a vector in halves or decompose the shuffles and the
9523 /// This is provided as a good fallback for many lowerings of non-single-input
9524 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9525 /// between splitting the shuffle into 128-bit components and stitching those
9526 /// back together vs. extracting the single-input shuffles and blending those
9528 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9529 SDValue V2, ArrayRef<int> Mask,
9530 SelectionDAG &DAG) {
9531 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9532 "lower single-input shuffles as it "
9533 "could then recurse on itself.");
9534 int Size = Mask.size();
9536 // If this can be modeled as a broadcast of two elements followed by a blend,
9537 // prefer that lowering. This is especially important because broadcasts can
9538 // often fold with memory operands.
9539 auto DoBothBroadcast = [&] {
9540 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9543 if (V2BroadcastIdx == -1)
9544 V2BroadcastIdx = M - Size;
9545 else if (M - Size != V2BroadcastIdx)
9547 } else if (M >= 0) {
9548 if (V1BroadcastIdx == -1)
9550 else if (M != V1BroadcastIdx)
9555 if (DoBothBroadcast())
9556 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9559 // If the inputs all stem from a single 128-bit lane of each input, then we
9560 // split them rather than blending because the split will decompose to
9561 // unusually few instructions.
9562 int LaneCount = VT.getSizeInBits() / 128;
9563 int LaneSize = Size / LaneCount;
9564 SmallBitVector LaneInputs[2];
9565 LaneInputs[0].resize(LaneCount, false);
9566 LaneInputs[1].resize(LaneCount, false);
9567 for (int i = 0; i < Size; ++i)
9569 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9570 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9571 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9573 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9574 // that the decomposed single-input shuffles don't end up here.
9575 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9578 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9579 /// a permutation and blend of those lanes.
9581 /// This essentially blends the out-of-lane inputs to each lane into the lane
9582 /// from a permuted copy of the vector. This lowering strategy results in four
9583 /// instructions in the worst case for a single-input cross lane shuffle which
9584 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9585 /// of. Special cases for each particular shuffle pattern should be handled
9586 /// prior to trying this lowering.
9587 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9588 SDValue V1, SDValue V2,
9590 SelectionDAG &DAG) {
9591 // FIXME: This should probably be generalized for 512-bit vectors as well.
9592 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9593 int LaneSize = Mask.size() / 2;
9595 // If there are only inputs from one 128-bit lane, splitting will in fact be
9596 // less expensive. The flags track whether the given lane contains an element
9597 // that crosses to another lane.
9598 bool LaneCrossing[2] = {false, false};
9599 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9600 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9601 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9602 if (!LaneCrossing[0] || !LaneCrossing[1])
9603 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9605 if (isSingleInputShuffleMask(Mask)) {
9606 SmallVector<int, 32> FlippedBlendMask;
9607 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9608 FlippedBlendMask.push_back(
9609 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9611 : Mask[i] % LaneSize +
9612 (i / LaneSize) * LaneSize + Size));
9614 // Flip the vector, and blend the results which should now be in-lane. The
9615 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9616 // 5 for the high source. The value 3 selects the high half of source 2 and
9617 // the value 2 selects the low half of source 2. We only use source 2 to
9618 // allow folding it into a memory operand.
9619 unsigned PERMMask = 3 | 2 << 4;
9620 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9621 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9622 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9625 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9626 // will be handled by the above logic and a blend of the results, much like
9627 // other patterns in AVX.
9628 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9631 /// \brief Handle lowering 2-lane 128-bit shuffles.
9632 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9633 SDValue V2, ArrayRef<int> Mask,
9634 const X86Subtarget *Subtarget,
9635 SelectionDAG &DAG) {
9636 // TODO: If minimizing size and one of the inputs is a zero vector and the
9637 // the zero vector has only one use, we could use a VPERM2X128 to save the
9638 // instruction bytes needed to explicitly generate the zero vector.
9640 // Blends are faster and handle all the non-lane-crossing cases.
9641 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9645 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9646 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9648 // If either input operand is a zero vector, use VPERM2X128 because its mask
9649 // allows us to replace the zero input with an implicit zero.
9650 if (!IsV1Zero && !IsV2Zero) {
9651 // Check for patterns which can be matched with a single insert of a 128-bit
9653 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9654 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9655 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9656 VT.getVectorNumElements() / 2);
9657 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9658 DAG.getIntPtrConstant(0, DL));
9659 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9660 OnlyUsesV1 ? V1 : V2,
9661 DAG.getIntPtrConstant(0, DL));
9662 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9666 // Otherwise form a 128-bit permutation. After accounting for undefs,
9667 // convert the 64-bit shuffle mask selection values into 128-bit
9668 // selection bits by dividing the indexes by 2 and shifting into positions
9669 // defined by a vperm2*128 instruction's immediate control byte.
9671 // The immediate permute control byte looks like this:
9672 // [1:0] - select 128 bits from sources for low half of destination
9674 // [3] - zero low half of destination
9675 // [5:4] - select 128 bits from sources for high half of destination
9677 // [7] - zero high half of destination
9679 int MaskLO = Mask[0];
9680 if (MaskLO == SM_SentinelUndef)
9681 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9683 int MaskHI = Mask[2];
9684 if (MaskHI == SM_SentinelUndef)
9685 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9687 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9689 // If either input is a zero vector, replace it with an undef input.
9690 // Shuffle mask values < 4 are selecting elements of V1.
9691 // Shuffle mask values >= 4 are selecting elements of V2.
9692 // Adjust each half of the permute mask by clearing the half that was
9693 // selecting the zero vector and setting the zero mask bit.
9695 V1 = DAG.getUNDEF(VT);
9697 PermMask = (PermMask & 0xf0) | 0x08;
9699 PermMask = (PermMask & 0x0f) | 0x80;
9702 V2 = DAG.getUNDEF(VT);
9704 PermMask = (PermMask & 0xf0) | 0x08;
9706 PermMask = (PermMask & 0x0f) | 0x80;
9709 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9710 DAG.getConstant(PermMask, DL, MVT::i8));
9713 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9714 /// shuffling each lane.
9716 /// This will only succeed when the result of fixing the 128-bit lanes results
9717 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9718 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9719 /// the lane crosses early and then use simpler shuffles within each lane.
9721 /// FIXME: It might be worthwhile at some point to support this without
9722 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9723 /// in x86 only floating point has interesting non-repeating shuffles, and even
9724 /// those are still *marginally* more expensive.
9725 static SDValue lowerVectorShuffleByMerging128BitLanes(
9726 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9727 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9728 assert(!isSingleInputShuffleMask(Mask) &&
9729 "This is only useful with multiple inputs.");
9731 int Size = Mask.size();
9732 int LaneSize = 128 / VT.getScalarSizeInBits();
9733 int NumLanes = Size / LaneSize;
9734 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9736 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9737 // check whether the in-128-bit lane shuffles share a repeating pattern.
9738 SmallVector<int, 4> Lanes;
9739 Lanes.resize(NumLanes, -1);
9740 SmallVector<int, 4> InLaneMask;
9741 InLaneMask.resize(LaneSize, -1);
9742 for (int i = 0; i < Size; ++i) {
9746 int j = i / LaneSize;
9749 // First entry we've seen for this lane.
9750 Lanes[j] = Mask[i] / LaneSize;
9751 } else if (Lanes[j] != Mask[i] / LaneSize) {
9752 // This doesn't match the lane selected previously!
9756 // Check that within each lane we have a consistent shuffle mask.
9757 int k = i % LaneSize;
9758 if (InLaneMask[k] < 0) {
9759 InLaneMask[k] = Mask[i] % LaneSize;
9760 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9761 // This doesn't fit a repeating in-lane mask.
9766 // First shuffle the lanes into place.
9767 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9768 VT.getSizeInBits() / 64);
9769 SmallVector<int, 8> LaneMask;
9770 LaneMask.resize(NumLanes * 2, -1);
9771 for (int i = 0; i < NumLanes; ++i)
9772 if (Lanes[i] >= 0) {
9773 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9774 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9777 V1 = DAG.getBitcast(LaneVT, V1);
9778 V2 = DAG.getBitcast(LaneVT, V2);
9779 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9781 // Cast it back to the type we actually want.
9782 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9784 // Now do a simple shuffle that isn't lane crossing.
9785 SmallVector<int, 8> NewMask;
9786 NewMask.resize(Size, -1);
9787 for (int i = 0; i < Size; ++i)
9789 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9790 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9791 "Must not introduce lane crosses at this point!");
9793 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9796 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9799 /// This returns true if the elements from a particular input are already in the
9800 /// slot required by the given mask and require no permutation.
9801 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9802 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9803 int Size = Mask.size();
9804 for (int i = 0; i < Size; ++i)
9805 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9811 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9812 ArrayRef<int> Mask, SDValue V1,
9813 SDValue V2, SelectionDAG &DAG) {
9815 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
9816 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
9817 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9818 int NumElts = VT.getVectorNumElements();
9819 bool ShufpdMask = true;
9820 bool CommutableMask = true;
9821 unsigned Immediate = 0;
9822 for (int i = 0; i < NumElts; ++i) {
9825 int Val = (i & 6) + NumElts * (i & 1);
9826 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9827 if (Mask[i] < Val || Mask[i] > Val + 1)
9829 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
9830 CommutableMask = false;
9831 Immediate |= (Mask[i] % 2) << i;
9834 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9835 DAG.getConstant(Immediate, DL, MVT::i8));
9837 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9838 DAG.getConstant(Immediate, DL, MVT::i8));
9842 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9844 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9845 /// isn't available.
9846 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9847 const X86Subtarget *Subtarget,
9848 SelectionDAG &DAG) {
9850 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9851 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9852 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9853 ArrayRef<int> Mask = SVOp->getMask();
9854 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9856 SmallVector<int, 4> WidenedMask;
9857 if (canWidenShuffleElements(Mask, WidenedMask))
9858 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9861 if (isSingleInputShuffleMask(Mask)) {
9862 // Check for being able to broadcast a single element.
9863 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9864 Mask, Subtarget, DAG))
9867 // Use low duplicate instructions for masks that match their pattern.
9868 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9869 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9871 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9872 // Non-half-crossing single input shuffles can be lowerid with an
9873 // interleaved permutation.
9874 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9875 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9876 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9877 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9880 // With AVX2 we have direct support for this permutation.
9881 if (Subtarget->hasAVX2())
9882 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9883 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9885 // Otherwise, fall back.
9886 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9890 // X86 has dedicated unpack instructions that can handle specific blend
9891 // operations: UNPCKH and UNPCKL.
9892 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9893 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9894 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9895 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9896 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9897 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9898 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9899 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9901 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9905 // Check if the blend happens to exactly fit that of SHUFPD.
9907 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9910 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9911 // shuffle. However, if we have AVX2 and either inputs are already in place,
9912 // we will be able to shuffle even across lanes the other input in a single
9913 // instruction so skip this pattern.
9914 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9915 isShuffleMaskInputInPlace(1, Mask))))
9916 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9917 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9920 // If we have AVX2 then we always want to lower with a blend because an v4 we
9921 // can fully permute the elements.
9922 if (Subtarget->hasAVX2())
9923 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9926 // Otherwise fall back on generic lowering.
9927 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9930 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9932 /// This routine is only called when we have AVX2 and thus a reasonable
9933 /// instruction set for v4i64 shuffling..
9934 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9935 const X86Subtarget *Subtarget,
9936 SelectionDAG &DAG) {
9938 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9939 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9940 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9941 ArrayRef<int> Mask = SVOp->getMask();
9942 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9943 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9945 SmallVector<int, 4> WidenedMask;
9946 if (canWidenShuffleElements(Mask, WidenedMask))
9947 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9950 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9954 // Check for being able to broadcast a single element.
9955 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9956 Mask, Subtarget, DAG))
9959 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9960 // use lower latency instructions that will operate on both 128-bit lanes.
9961 SmallVector<int, 2> RepeatedMask;
9962 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9963 if (isSingleInputShuffleMask(Mask)) {
9964 int PSHUFDMask[] = {-1, -1, -1, -1};
9965 for (int i = 0; i < 2; ++i)
9966 if (RepeatedMask[i] >= 0) {
9967 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9968 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9970 return DAG.getBitcast(
9972 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9973 DAG.getBitcast(MVT::v8i32, V1),
9974 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9978 // AVX2 provides a direct instruction for permuting a single input across
9980 if (isSingleInputShuffleMask(Mask))
9981 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9982 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9984 // Try to use shift instructions.
9986 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9989 // Use dedicated unpack instructions for masks that match their pattern.
9990 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9991 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9992 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9993 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9994 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9995 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9996 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9997 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9999 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10000 // shuffle. However, if we have AVX2 and either inputs are already in place,
10001 // we will be able to shuffle even across lanes the other input in a single
10002 // instruction so skip this pattern.
10003 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10004 isShuffleMaskInputInPlace(1, Mask))))
10005 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10006 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10009 // Otherwise fall back on generic blend lowering.
10010 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10014 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10016 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10017 /// isn't available.
10018 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10019 const X86Subtarget *Subtarget,
10020 SelectionDAG &DAG) {
10022 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10023 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10024 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10025 ArrayRef<int> Mask = SVOp->getMask();
10026 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10028 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10032 // Check for being able to broadcast a single element.
10033 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10034 Mask, Subtarget, DAG))
10037 // If the shuffle mask is repeated in each 128-bit lane, we have many more
10038 // options to efficiently lower the shuffle.
10039 SmallVector<int, 4> RepeatedMask;
10040 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10041 assert(RepeatedMask.size() == 4 &&
10042 "Repeated masks must be half the mask width!");
10044 // Use even/odd duplicate instructions for masks that match their pattern.
10045 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10046 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10047 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10048 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10050 if (isSingleInputShuffleMask(Mask))
10051 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10052 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10054 // Use dedicated unpack instructions for masks that match their pattern.
10055 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10056 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
10057 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10058 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
10059 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10060 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10061 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10062 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10064 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10065 // have already handled any direct blends. We also need to squash the
10066 // repeated mask into a simulated v4f32 mask.
10067 for (int i = 0; i < 4; ++i)
10068 if (RepeatedMask[i] >= 8)
10069 RepeatedMask[i] -= 4;
10070 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10073 // If we have a single input shuffle with different shuffle patterns in the
10074 // two 128-bit lanes use the variable mask to VPERMILPS.
10075 if (isSingleInputShuffleMask(Mask)) {
10076 SDValue VPermMask[8];
10077 for (int i = 0; i < 8; ++i)
10078 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10079 : DAG.getConstant(Mask[i], DL, MVT::i32);
10080 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10081 return DAG.getNode(
10082 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10083 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10085 if (Subtarget->hasAVX2())
10086 return DAG.getNode(
10087 X86ISD::VPERMV, DL, MVT::v8f32,
10088 DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10089 MVT::v8i32, VPermMask)),
10092 // Otherwise, fall back.
10093 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10097 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10099 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10100 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10103 // If we have AVX2 then we always want to lower with a blend because at v8 we
10104 // can fully permute the elements.
10105 if (Subtarget->hasAVX2())
10106 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10109 // Otherwise fall back on generic lowering.
10110 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10113 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10115 /// This routine is only called when we have AVX2 and thus a reasonable
10116 /// instruction set for v8i32 shuffling..
10117 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10118 const X86Subtarget *Subtarget,
10119 SelectionDAG &DAG) {
10121 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10122 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10123 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10124 ArrayRef<int> Mask = SVOp->getMask();
10125 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10126 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10128 // Whenever we can lower this as a zext, that instruction is strictly faster
10129 // than any alternative. It also allows us to fold memory operands into the
10130 // shuffle in many cases.
10131 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10132 Mask, Subtarget, DAG))
10135 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10139 // Check for being able to broadcast a single element.
10140 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10141 Mask, Subtarget, DAG))
10144 // If the shuffle mask is repeated in each 128-bit lane we can use more
10145 // efficient instructions that mirror the shuffles across the two 128-bit
10147 SmallVector<int, 4> RepeatedMask;
10148 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10149 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10150 if (isSingleInputShuffleMask(Mask))
10151 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10152 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10154 // Use dedicated unpack instructions for masks that match their pattern.
10155 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10156 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10157 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10158 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10159 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10160 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10161 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10162 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10165 // Try to use shift instructions.
10166 if (SDValue Shift =
10167 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10170 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10171 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10174 // If the shuffle patterns aren't repeated but it is a single input, directly
10175 // generate a cross-lane VPERMD instruction.
10176 if (isSingleInputShuffleMask(Mask)) {
10177 SDValue VPermMask[8];
10178 for (int i = 0; i < 8; ++i)
10179 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10180 : DAG.getConstant(Mask[i], DL, MVT::i32);
10181 return DAG.getNode(
10182 X86ISD::VPERMV, DL, MVT::v8i32,
10183 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10186 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10188 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10189 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10192 // Otherwise fall back on generic blend lowering.
10193 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10197 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10199 /// This routine is only called when we have AVX2 and thus a reasonable
10200 /// instruction set for v16i16 shuffling..
10201 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10202 const X86Subtarget *Subtarget,
10203 SelectionDAG &DAG) {
10205 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10206 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10207 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10208 ArrayRef<int> Mask = SVOp->getMask();
10209 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10210 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10212 // Whenever we can lower this as a zext, that instruction is strictly faster
10213 // than any alternative. It also allows us to fold memory operands into the
10214 // shuffle in many cases.
10215 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10216 Mask, Subtarget, DAG))
10219 // Check for being able to broadcast a single element.
10220 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10221 Mask, Subtarget, DAG))
10224 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10228 // Use dedicated unpack instructions for masks that match their pattern.
10229 if (isShuffleEquivalent(V1, V2, Mask,
10230 {// First 128-bit lane:
10231 0, 16, 1, 17, 2, 18, 3, 19,
10232 // Second 128-bit lane:
10233 8, 24, 9, 25, 10, 26, 11, 27}))
10234 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10235 if (isShuffleEquivalent(V1, V2, Mask,
10236 {// First 128-bit lane:
10237 4, 20, 5, 21, 6, 22, 7, 23,
10238 // Second 128-bit lane:
10239 12, 28, 13, 29, 14, 30, 15, 31}))
10240 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10242 // Try to use shift instructions.
10243 if (SDValue Shift =
10244 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10247 // Try to use byte rotation instructions.
10248 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10249 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10252 if (isSingleInputShuffleMask(Mask)) {
10253 // There are no generalized cross-lane shuffle operations available on i16
10255 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10256 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10259 SmallVector<int, 8> RepeatedMask;
10260 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10261 // As this is a single-input shuffle, the repeated mask should be
10262 // a strictly valid v8i16 mask that we can pass through to the v8i16
10263 // lowering to handle even the v16 case.
10264 return lowerV8I16GeneralSingleInputVectorShuffle(
10265 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10268 SDValue PSHUFBMask[32];
10269 for (int i = 0; i < 16; ++i) {
10270 if (Mask[i] == -1) {
10271 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10275 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10276 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10277 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10278 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10280 return DAG.getBitcast(MVT::v16i16,
10281 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10282 DAG.getBitcast(MVT::v32i8, V1),
10283 DAG.getNode(ISD::BUILD_VECTOR, DL,
10284 MVT::v32i8, PSHUFBMask)));
10287 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10289 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10290 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10293 // Otherwise fall back on generic lowering.
10294 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10297 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10299 /// This routine is only called when we have AVX2 and thus a reasonable
10300 /// instruction set for v32i8 shuffling..
10301 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10302 const X86Subtarget *Subtarget,
10303 SelectionDAG &DAG) {
10305 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10306 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10307 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10308 ArrayRef<int> Mask = SVOp->getMask();
10309 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10310 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10312 // Whenever we can lower this as a zext, that instruction is strictly faster
10313 // than any alternative. It also allows us to fold memory operands into the
10314 // shuffle in many cases.
10315 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10316 Mask, Subtarget, DAG))
10319 // Check for being able to broadcast a single element.
10320 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10321 Mask, Subtarget, DAG))
10324 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10328 // Use dedicated unpack instructions for masks that match their pattern.
10329 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10331 if (isShuffleEquivalent(
10333 {// First 128-bit lane:
10334 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10335 // Second 128-bit lane:
10336 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10337 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10338 if (isShuffleEquivalent(
10340 {// First 128-bit lane:
10341 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10342 // Second 128-bit lane:
10343 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10344 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10346 // Try to use shift instructions.
10347 if (SDValue Shift =
10348 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10351 // Try to use byte rotation instructions.
10352 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10353 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10356 if (isSingleInputShuffleMask(Mask)) {
10357 // There are no generalized cross-lane shuffle operations available on i8
10359 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10360 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10363 SDValue PSHUFBMask[32];
10364 for (int i = 0; i < 32; ++i)
10367 ? DAG.getUNDEF(MVT::i8)
10368 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10371 return DAG.getNode(
10372 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10373 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10376 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10378 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10379 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10382 // Otherwise fall back on generic lowering.
10383 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10386 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10388 /// This routine either breaks down the specific type of a 256-bit x86 vector
10389 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10390 /// together based on the available instructions.
10391 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10392 MVT VT, const X86Subtarget *Subtarget,
10393 SelectionDAG &DAG) {
10395 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10396 ArrayRef<int> Mask = SVOp->getMask();
10398 // If we have a single input to the zero element, insert that into V1 if we
10399 // can do so cheaply.
10400 int NumElts = VT.getVectorNumElements();
10401 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10402 return M >= NumElts;
10405 if (NumV2Elements == 1 && Mask[0] >= NumElts)
10406 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10407 DL, VT, V1, V2, Mask, Subtarget, DAG))
10410 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10411 // check for those subtargets here and avoid much of the subtarget querying in
10412 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10413 // ability to manipulate a 256-bit vector with integer types. Since we'll use
10414 // floating point types there eventually, just immediately cast everything to
10415 // a float and operate entirely in that domain.
10416 if (VT.isInteger() && !Subtarget->hasAVX2()) {
10417 int ElementBits = VT.getScalarSizeInBits();
10418 if (ElementBits < 32)
10419 // No floating point type available, decompose into 128-bit vectors.
10420 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10422 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10423 VT.getVectorNumElements());
10424 V1 = DAG.getBitcast(FpVT, V1);
10425 V2 = DAG.getBitcast(FpVT, V2);
10426 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10429 switch (VT.SimpleTy) {
10431 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10433 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10435 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10437 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10439 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10441 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10444 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10448 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10449 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10450 const X86Subtarget *Subtarget,
10451 SelectionDAG &DAG) {
10453 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10454 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10455 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10456 ArrayRef<int> Mask = SVOp->getMask();
10457 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10459 // X86 has dedicated unpack instructions that can handle specific blend
10460 // operations: UNPCKH and UNPCKL.
10461 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10462 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10463 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10464 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10466 // FIXME: Implement direct support for this type!
10467 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10470 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10471 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10472 const X86Subtarget *Subtarget,
10473 SelectionDAG &DAG) {
10475 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10476 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10477 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10478 ArrayRef<int> Mask = SVOp->getMask();
10479 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10481 // Use dedicated unpack instructions for masks that match their pattern.
10482 if (isShuffleEquivalent(V1, V2, Mask,
10483 {// First 128-bit lane.
10484 0, 16, 1, 17, 4, 20, 5, 21,
10485 // Second 128-bit lane.
10486 8, 24, 9, 25, 12, 28, 13, 29}))
10487 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10488 if (isShuffleEquivalent(V1, V2, Mask,
10489 {// First 128-bit lane.
10490 2, 18, 3, 19, 6, 22, 7, 23,
10491 // Second 128-bit lane.
10492 10, 26, 11, 27, 14, 30, 15, 31}))
10493 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10495 // FIXME: Implement direct support for this type!
10496 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10499 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10500 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10501 const X86Subtarget *Subtarget,
10502 SelectionDAG &DAG) {
10504 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10505 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10506 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10507 ArrayRef<int> Mask = SVOp->getMask();
10508 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10510 // X86 has dedicated unpack instructions that can handle specific blend
10511 // operations: UNPCKH and UNPCKL.
10512 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10513 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10514 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10515 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10517 // FIXME: Implement direct support for this type!
10518 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10521 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10522 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10523 const X86Subtarget *Subtarget,
10524 SelectionDAG &DAG) {
10526 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10527 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10528 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10529 ArrayRef<int> Mask = SVOp->getMask();
10530 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10532 // Use dedicated unpack instructions for masks that match their pattern.
10533 if (isShuffleEquivalent(V1, V2, Mask,
10534 {// First 128-bit lane.
10535 0, 16, 1, 17, 4, 20, 5, 21,
10536 // Second 128-bit lane.
10537 8, 24, 9, 25, 12, 28, 13, 29}))
10538 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10539 if (isShuffleEquivalent(V1, V2, Mask,
10540 {// First 128-bit lane.
10541 2, 18, 3, 19, 6, 22, 7, 23,
10542 // Second 128-bit lane.
10543 10, 26, 11, 27, 14, 30, 15, 31}))
10544 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10546 // FIXME: Implement direct support for this type!
10547 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10550 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10551 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10552 const X86Subtarget *Subtarget,
10553 SelectionDAG &DAG) {
10555 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10556 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10557 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10558 ArrayRef<int> Mask = SVOp->getMask();
10559 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10560 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10562 // FIXME: Implement direct support for this type!
10563 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10566 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10567 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10568 const X86Subtarget *Subtarget,
10569 SelectionDAG &DAG) {
10571 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10572 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10573 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10574 ArrayRef<int> Mask = SVOp->getMask();
10575 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10576 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10578 // FIXME: Implement direct support for this type!
10579 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10582 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10584 /// This routine either breaks down the specific type of a 512-bit x86 vector
10585 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10586 /// together based on the available instructions.
10587 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10588 MVT VT, const X86Subtarget *Subtarget,
10589 SelectionDAG &DAG) {
10591 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10592 ArrayRef<int> Mask = SVOp->getMask();
10593 assert(Subtarget->hasAVX512() &&
10594 "Cannot lower 512-bit vectors w/ basic ISA!");
10596 // Check for being able to broadcast a single element.
10597 if (SDValue Broadcast =
10598 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10601 // Dispatch to each element type for lowering. If we don't have supprot for
10602 // specific element type shuffles at 512 bits, immediately split them and
10603 // lower them. Each lowering routine of a given type is allowed to assume that
10604 // the requisite ISA extensions for that element type are available.
10605 switch (VT.SimpleTy) {
10607 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10609 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10611 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10613 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10615 if (Subtarget->hasBWI())
10616 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10619 if (Subtarget->hasBWI())
10620 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10624 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10627 // Otherwise fall back on splitting.
10628 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10631 /// \brief Top-level lowering for x86 vector shuffles.
10633 /// This handles decomposition, canonicalization, and lowering of all x86
10634 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10635 /// above in helper routines. The canonicalization attempts to widen shuffles
10636 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10637 /// s.t. only one of the two inputs needs to be tested, etc.
10638 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10639 SelectionDAG &DAG) {
10640 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10641 ArrayRef<int> Mask = SVOp->getMask();
10642 SDValue V1 = Op.getOperand(0);
10643 SDValue V2 = Op.getOperand(1);
10644 MVT VT = Op.getSimpleValueType();
10645 int NumElements = VT.getVectorNumElements();
10648 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10650 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10651 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10652 if (V1IsUndef && V2IsUndef)
10653 return DAG.getUNDEF(VT);
10655 // When we create a shuffle node we put the UNDEF node to second operand,
10656 // but in some cases the first operand may be transformed to UNDEF.
10657 // In this case we should just commute the node.
10659 return DAG.getCommutedVectorShuffle(*SVOp);
10661 // Check for non-undef masks pointing at an undef vector and make the masks
10662 // undef as well. This makes it easier to match the shuffle based solely on
10666 if (M >= NumElements) {
10667 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10668 for (int &M : NewMask)
10669 if (M >= NumElements)
10671 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10674 // We actually see shuffles that are entirely re-arrangements of a set of
10675 // zero inputs. This mostly happens while decomposing complex shuffles into
10676 // simple ones. Directly lower these as a buildvector of zeros.
10677 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10678 if (Zeroable.all())
10679 return getZeroVector(VT, Subtarget, DAG, dl);
10681 // Try to collapse shuffles into using a vector type with fewer elements but
10682 // wider element types. We cap this to not form integers or floating point
10683 // elements wider than 64 bits, but it might be interesting to form i128
10684 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10685 SmallVector<int, 16> WidenedMask;
10686 if (VT.getScalarSizeInBits() < 64 &&
10687 canWidenShuffleElements(Mask, WidenedMask)) {
10688 MVT NewEltVT = VT.isFloatingPoint()
10689 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10690 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10691 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10692 // Make sure that the new vector type is legal. For example, v2f64 isn't
10694 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10695 V1 = DAG.getBitcast(NewVT, V1);
10696 V2 = DAG.getBitcast(NewVT, V2);
10697 return DAG.getBitcast(
10698 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10702 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10703 for (int M : SVOp->getMask())
10705 ++NumUndefElements;
10706 else if (M < NumElements)
10711 // Commute the shuffle as needed such that more elements come from V1 than
10712 // V2. This allows us to match the shuffle pattern strictly on how many
10713 // elements come from V1 without handling the symmetric cases.
10714 if (NumV2Elements > NumV1Elements)
10715 return DAG.getCommutedVectorShuffle(*SVOp);
10717 // When the number of V1 and V2 elements are the same, try to minimize the
10718 // number of uses of V2 in the low half of the vector. When that is tied,
10719 // ensure that the sum of indices for V1 is equal to or lower than the sum
10720 // indices for V2. When those are equal, try to ensure that the number of odd
10721 // indices for V1 is lower than the number of odd indices for V2.
10722 if (NumV1Elements == NumV2Elements) {
10723 int LowV1Elements = 0, LowV2Elements = 0;
10724 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10725 if (M >= NumElements)
10729 if (LowV2Elements > LowV1Elements) {
10730 return DAG.getCommutedVectorShuffle(*SVOp);
10731 } else if (LowV2Elements == LowV1Elements) {
10732 int SumV1Indices = 0, SumV2Indices = 0;
10733 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10734 if (SVOp->getMask()[i] >= NumElements)
10736 else if (SVOp->getMask()[i] >= 0)
10738 if (SumV2Indices < SumV1Indices) {
10739 return DAG.getCommutedVectorShuffle(*SVOp);
10740 } else if (SumV2Indices == SumV1Indices) {
10741 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10742 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10743 if (SVOp->getMask()[i] >= NumElements)
10744 NumV2OddIndices += i % 2;
10745 else if (SVOp->getMask()[i] >= 0)
10746 NumV1OddIndices += i % 2;
10747 if (NumV2OddIndices < NumV1OddIndices)
10748 return DAG.getCommutedVectorShuffle(*SVOp);
10753 // For each vector width, delegate to a specialized lowering routine.
10754 if (VT.getSizeInBits() == 128)
10755 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10757 if (VT.getSizeInBits() == 256)
10758 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10760 // Force AVX-512 vectors to be scalarized for now.
10761 // FIXME: Implement AVX-512 support!
10762 if (VT.getSizeInBits() == 512)
10763 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10765 llvm_unreachable("Unimplemented!");
10768 // This function assumes its argument is a BUILD_VECTOR of constants or
10769 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10771 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10772 unsigned &MaskValue) {
10774 unsigned NumElems = BuildVector->getNumOperands();
10775 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10776 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10777 unsigned NumElemsInLane = NumElems / NumLanes;
10779 // Blend for v16i16 should be symmetric for the both lanes.
10780 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10781 SDValue EltCond = BuildVector->getOperand(i);
10782 SDValue SndLaneEltCond =
10783 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10785 int Lane1Cond = -1, Lane2Cond = -1;
10786 if (isa<ConstantSDNode>(EltCond))
10787 Lane1Cond = !isZero(EltCond);
10788 if (isa<ConstantSDNode>(SndLaneEltCond))
10789 Lane2Cond = !isZero(SndLaneEltCond);
10791 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10792 // Lane1Cond != 0, means we want the first argument.
10793 // Lane1Cond == 0, means we want the second argument.
10794 // The encoding of this argument is 0 for the first argument, 1
10795 // for the second. Therefore, invert the condition.
10796 MaskValue |= !Lane1Cond << i;
10797 else if (Lane1Cond < 0)
10798 MaskValue |= !Lane2Cond << i;
10805 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10806 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10807 const X86Subtarget *Subtarget,
10808 SelectionDAG &DAG) {
10809 SDValue Cond = Op.getOperand(0);
10810 SDValue LHS = Op.getOperand(1);
10811 SDValue RHS = Op.getOperand(2);
10813 MVT VT = Op.getSimpleValueType();
10815 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10817 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10819 // Only non-legal VSELECTs reach this lowering, convert those into generic
10820 // shuffles and re-use the shuffle lowering path for blends.
10821 SmallVector<int, 32> Mask;
10822 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10823 SDValue CondElt = CondBV->getOperand(i);
10825 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10827 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10830 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10831 // A vselect where all conditions and data are constants can be optimized into
10832 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10833 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10834 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10835 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10838 // Try to lower this to a blend-style vector shuffle. This can handle all
10839 // constant condition cases.
10840 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10843 // Variable blends are only legal from SSE4.1 onward.
10844 if (!Subtarget->hasSSE41())
10847 // Only some types will be legal on some subtargets. If we can emit a legal
10848 // VSELECT-matching blend, return Op, and but if we need to expand, return
10850 switch (Op.getSimpleValueType().SimpleTy) {
10852 // Most of the vector types have blends past SSE4.1.
10856 // The byte blends for AVX vectors were introduced only in AVX2.
10857 if (Subtarget->hasAVX2())
10864 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10865 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10868 // FIXME: We should custom lower this by fixing the condition and using i8
10874 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10875 MVT VT = Op.getSimpleValueType();
10878 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10881 if (VT.getSizeInBits() == 8) {
10882 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10883 Op.getOperand(0), Op.getOperand(1));
10884 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10885 DAG.getValueType(VT));
10886 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10889 if (VT.getSizeInBits() == 16) {
10890 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10891 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10893 return DAG.getNode(
10894 ISD::TRUNCATE, dl, MVT::i16,
10895 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10896 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10897 Op.getOperand(1)));
10898 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10899 Op.getOperand(0), Op.getOperand(1));
10900 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10901 DAG.getValueType(VT));
10902 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10905 if (VT == MVT::f32) {
10906 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10907 // the result back to FR32 register. It's only worth matching if the
10908 // result has a single use which is a store or a bitcast to i32. And in
10909 // the case of a store, it's not worth it if the index is a constant 0,
10910 // because a MOVSSmr can be used instead, which is smaller and faster.
10911 if (!Op.hasOneUse())
10913 SDNode *User = *Op.getNode()->use_begin();
10914 if ((User->getOpcode() != ISD::STORE ||
10915 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10916 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10917 (User->getOpcode() != ISD::BITCAST ||
10918 User->getValueType(0) != MVT::i32))
10920 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10921 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10923 return DAG.getBitcast(MVT::f32, Extract);
10926 if (VT == MVT::i32 || VT == MVT::i64) {
10927 // ExtractPS/pextrq works with constant index.
10928 if (isa<ConstantSDNode>(Op.getOperand(1)))
10934 /// Extract one bit from mask vector, like v16i1 or v8i1.
10935 /// AVX-512 feature.
10937 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10938 SDValue Vec = Op.getOperand(0);
10940 MVT VecVT = Vec.getSimpleValueType();
10941 SDValue Idx = Op.getOperand(1);
10942 MVT EltVT = Op.getSimpleValueType();
10944 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10945 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10946 "Unexpected vector type in ExtractBitFromMaskVector");
10948 // variable index can't be handled in mask registers,
10949 // extend vector to VR512
10950 if (!isa<ConstantSDNode>(Idx)) {
10951 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10952 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10953 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10954 ExtVT.getVectorElementType(), Ext, Idx);
10955 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10958 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10959 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10960 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10961 rc = getRegClassFor(MVT::v16i1);
10962 unsigned MaxSift = rc->getSize()*8 - 1;
10963 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10964 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10965 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10966 DAG.getConstant(MaxSift, dl, MVT::i8));
10967 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10968 DAG.getIntPtrConstant(0, dl));
10972 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10973 SelectionDAG &DAG) const {
10975 SDValue Vec = Op.getOperand(0);
10976 MVT VecVT = Vec.getSimpleValueType();
10977 SDValue Idx = Op.getOperand(1);
10979 if (Op.getSimpleValueType() == MVT::i1)
10980 return ExtractBitFromMaskVector(Op, DAG);
10982 if (!isa<ConstantSDNode>(Idx)) {
10983 if (VecVT.is512BitVector() ||
10984 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10985 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10988 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10989 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10990 MaskEltVT.getSizeInBits());
10992 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10993 auto PtrVT = getPointerTy(DAG.getDataLayout());
10994 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10995 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10996 DAG.getConstant(0, dl, PtrVT));
10997 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10998 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10999 DAG.getConstant(0, dl, PtrVT));
11004 // If this is a 256-bit vector result, first extract the 128-bit vector and
11005 // then extract the element from the 128-bit vector.
11006 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11008 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11009 // Get the 128-bit vector.
11010 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11011 MVT EltVT = VecVT.getVectorElementType();
11013 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11015 //if (IdxVal >= NumElems/2)
11016 // IdxVal -= NumElems/2;
11017 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11018 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11019 DAG.getConstant(IdxVal, dl, MVT::i32));
11022 assert(VecVT.is128BitVector() && "Unexpected vector length");
11024 if (Subtarget->hasSSE41())
11025 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11028 MVT VT = Op.getSimpleValueType();
11029 // TODO: handle v16i8.
11030 if (VT.getSizeInBits() == 16) {
11031 SDValue Vec = Op.getOperand(0);
11032 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11034 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11035 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11036 DAG.getBitcast(MVT::v4i32, Vec),
11037 Op.getOperand(1)));
11038 // Transform it so it match pextrw which produces a 32-bit result.
11039 MVT EltVT = MVT::i32;
11040 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11041 Op.getOperand(0), Op.getOperand(1));
11042 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11043 DAG.getValueType(VT));
11044 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11047 if (VT.getSizeInBits() == 32) {
11048 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11052 // SHUFPS the element to the lowest double word, then movss.
11053 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11054 MVT VVT = Op.getOperand(0).getSimpleValueType();
11055 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11056 DAG.getUNDEF(VVT), Mask);
11057 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11058 DAG.getIntPtrConstant(0, dl));
11061 if (VT.getSizeInBits() == 64) {
11062 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11063 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11064 // to match extract_elt for f64.
11065 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11069 // UNPCKHPD the element to the lowest double word, then movsd.
11070 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11071 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11072 int Mask[2] = { 1, -1 };
11073 MVT VVT = Op.getOperand(0).getSimpleValueType();
11074 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11075 DAG.getUNDEF(VVT), Mask);
11076 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11077 DAG.getIntPtrConstant(0, dl));
11083 /// Insert one bit to mask vector, like v16i1 or v8i1.
11084 /// AVX-512 feature.
11086 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11088 SDValue Vec = Op.getOperand(0);
11089 SDValue Elt = Op.getOperand(1);
11090 SDValue Idx = Op.getOperand(2);
11091 MVT VecVT = Vec.getSimpleValueType();
11093 if (!isa<ConstantSDNode>(Idx)) {
11094 // Non constant index. Extend source and destination,
11095 // insert element and then truncate the result.
11096 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11097 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
11098 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11099 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11100 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11101 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11104 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11105 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11107 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11108 DAG.getConstant(IdxVal, dl, MVT::i8));
11109 if (Vec.getOpcode() == ISD::UNDEF)
11111 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11114 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11115 SelectionDAG &DAG) const {
11116 MVT VT = Op.getSimpleValueType();
11117 MVT EltVT = VT.getVectorElementType();
11119 if (EltVT == MVT::i1)
11120 return InsertBitToMaskVector(Op, DAG);
11123 SDValue N0 = Op.getOperand(0);
11124 SDValue N1 = Op.getOperand(1);
11125 SDValue N2 = Op.getOperand(2);
11126 if (!isa<ConstantSDNode>(N2))
11128 auto *N2C = cast<ConstantSDNode>(N2);
11129 unsigned IdxVal = N2C->getZExtValue();
11131 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11132 // into that, and then insert the subvector back into the result.
11133 if (VT.is256BitVector() || VT.is512BitVector()) {
11134 // With a 256-bit vector, we can insert into the zero element efficiently
11135 // using a blend if we have AVX or AVX2 and the right data type.
11136 if (VT.is256BitVector() && IdxVal == 0) {
11137 // TODO: It is worthwhile to cast integer to floating point and back
11138 // and incur a domain crossing penalty if that's what we'll end up
11139 // doing anyway after extracting to a 128-bit vector.
11140 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11141 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11142 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11143 N2 = DAG.getIntPtrConstant(1, dl);
11144 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11148 // Get the desired 128-bit vector chunk.
11149 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11151 // Insert the element into the desired chunk.
11152 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11153 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11155 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11156 DAG.getConstant(IdxIn128, dl, MVT::i32));
11158 // Insert the changed part back into the bigger vector
11159 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11161 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11163 if (Subtarget->hasSSE41()) {
11164 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11166 if (VT == MVT::v8i16) {
11167 Opc = X86ISD::PINSRW;
11169 assert(VT == MVT::v16i8);
11170 Opc = X86ISD::PINSRB;
11173 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11175 if (N1.getValueType() != MVT::i32)
11176 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11177 if (N2.getValueType() != MVT::i32)
11178 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11179 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11182 if (EltVT == MVT::f32) {
11183 // Bits [7:6] of the constant are the source select. This will always be
11184 // zero here. The DAG Combiner may combine an extract_elt index into
11185 // these bits. For example (insert (extract, 3), 2) could be matched by
11186 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11187 // Bits [5:4] of the constant are the destination select. This is the
11188 // value of the incoming immediate.
11189 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11190 // combine either bitwise AND or insert of float 0.0 to set these bits.
11192 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11193 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11194 // If this is an insertion of 32-bits into the low 32-bits of
11195 // a vector, we prefer to generate a blend with immediate rather
11196 // than an insertps. Blends are simpler operations in hardware and so
11197 // will always have equal or better performance than insertps.
11198 // But if optimizing for size and there's a load folding opportunity,
11199 // generate insertps because blendps does not have a 32-bit memory
11201 N2 = DAG.getIntPtrConstant(1, dl);
11202 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11203 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11205 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11206 // Create this as a scalar to vector..
11207 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11208 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11211 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11212 // PINSR* works with constant index.
11217 if (EltVT == MVT::i8)
11220 if (EltVT.getSizeInBits() == 16) {
11221 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11222 // as its second argument.
11223 if (N1.getValueType() != MVT::i32)
11224 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11225 if (N2.getValueType() != MVT::i32)
11226 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11227 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11232 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11234 MVT OpVT = Op.getSimpleValueType();
11236 // If this is a 256-bit vector result, first insert into a 128-bit
11237 // vector and then insert into the 256-bit vector.
11238 if (!OpVT.is128BitVector()) {
11239 // Insert into a 128-bit vector.
11240 unsigned SizeFactor = OpVT.getSizeInBits()/128;
11241 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11242 OpVT.getVectorNumElements() / SizeFactor);
11244 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11246 // Insert the 128-bit vector.
11247 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11250 if (OpVT == MVT::v1i64 &&
11251 Op.getOperand(0).getValueType() == MVT::i64)
11252 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11254 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11255 assert(OpVT.is128BitVector() && "Expected an SSE type!");
11256 return DAG.getBitcast(
11257 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11260 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
11261 // a simple subregister reference or explicit instructions to grab
11262 // upper bits of a vector.
11263 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11264 SelectionDAG &DAG) {
11266 SDValue In = Op.getOperand(0);
11267 SDValue Idx = Op.getOperand(1);
11268 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11269 MVT ResVT = Op.getSimpleValueType();
11270 MVT InVT = In.getSimpleValueType();
11272 if (Subtarget->hasFp256()) {
11273 if (ResVT.is128BitVector() &&
11274 (InVT.is256BitVector() || InVT.is512BitVector()) &&
11275 isa<ConstantSDNode>(Idx)) {
11276 return Extract128BitVector(In, IdxVal, DAG, dl);
11278 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11279 isa<ConstantSDNode>(Idx)) {
11280 return Extract256BitVector(In, IdxVal, DAG, dl);
11286 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
11287 // simple superregister reference or explicit instructions to insert
11288 // the upper bits of a vector.
11289 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11290 SelectionDAG &DAG) {
11291 if (!Subtarget->hasAVX())
11295 SDValue Vec = Op.getOperand(0);
11296 SDValue SubVec = Op.getOperand(1);
11297 SDValue Idx = Op.getOperand(2);
11299 if (!isa<ConstantSDNode>(Idx))
11302 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11303 MVT OpVT = Op.getSimpleValueType();
11304 MVT SubVecVT = SubVec.getSimpleValueType();
11306 // Fold two 16-byte subvector loads into one 32-byte load:
11307 // (insert_subvector (insert_subvector undef, (load addr), 0),
11308 // (load addr + 16), Elts/2)
11310 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11311 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11312 OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11313 auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11314 if (Idx2 && Idx2->getZExtValue() == 0) {
11315 SDValue SubVec2 = Vec.getOperand(1);
11316 // If needed, look through a bitcast to get to the load.
11317 if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11318 SubVec2 = SubVec2.getOperand(0);
11320 if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11322 unsigned Alignment = FirstLd->getAlignment();
11323 unsigned AS = FirstLd->getAddressSpace();
11324 const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11325 if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11326 OpVT, AS, Alignment, &Fast) && Fast) {
11327 SDValue Ops[] = { SubVec2, SubVec };
11328 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11335 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11336 SubVecVT.is128BitVector())
11337 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11339 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11340 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11342 if (OpVT.getVectorElementType() == MVT::i1) {
11343 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11345 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11346 SDValue Undef = DAG.getUNDEF(OpVT);
11347 unsigned NumElems = OpVT.getVectorNumElements();
11348 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11350 if (IdxVal == OpVT.getVectorNumElements() / 2) {
11351 // Zero upper bits of the Vec
11352 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11353 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11355 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11357 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11358 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11361 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11363 // Zero upper bits of the Vec2
11364 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11365 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11366 // Zero lower bits of the Vec
11367 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11368 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11369 // Merge them together
11370 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11376 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11377 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11378 // one of the above mentioned nodes. It has to be wrapped because otherwise
11379 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11380 // be used to form addressing mode. These wrapped nodes will be selected
11383 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11384 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11386 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11387 // global base reg.
11388 unsigned char OpFlag = 0;
11389 unsigned WrapperKind = X86ISD::Wrapper;
11390 CodeModel::Model M = DAG.getTarget().getCodeModel();
11392 if (Subtarget->isPICStyleRIPRel() &&
11393 (M == CodeModel::Small || M == CodeModel::Kernel))
11394 WrapperKind = X86ISD::WrapperRIP;
11395 else if (Subtarget->isPICStyleGOT())
11396 OpFlag = X86II::MO_GOTOFF;
11397 else if (Subtarget->isPICStyleStubPIC())
11398 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11400 auto PtrVT = getPointerTy(DAG.getDataLayout());
11401 SDValue Result = DAG.getTargetConstantPool(
11402 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11404 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11405 // With PIC, the address is actually $g + Offset.
11408 DAG.getNode(ISD::ADD, DL, PtrVT,
11409 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11415 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11416 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11418 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11419 // global base reg.
11420 unsigned char OpFlag = 0;
11421 unsigned WrapperKind = X86ISD::Wrapper;
11422 CodeModel::Model M = DAG.getTarget().getCodeModel();
11424 if (Subtarget->isPICStyleRIPRel() &&
11425 (M == CodeModel::Small || M == CodeModel::Kernel))
11426 WrapperKind = X86ISD::WrapperRIP;
11427 else if (Subtarget->isPICStyleGOT())
11428 OpFlag = X86II::MO_GOTOFF;
11429 else if (Subtarget->isPICStyleStubPIC())
11430 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11432 auto PtrVT = getPointerTy(DAG.getDataLayout());
11433 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11435 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11437 // With PIC, the address is actually $g + Offset.
11440 DAG.getNode(ISD::ADD, DL, PtrVT,
11441 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11447 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11448 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11450 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11451 // global base reg.
11452 unsigned char OpFlag = 0;
11453 unsigned WrapperKind = X86ISD::Wrapper;
11454 CodeModel::Model M = DAG.getTarget().getCodeModel();
11456 if (Subtarget->isPICStyleRIPRel() &&
11457 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11458 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11459 OpFlag = X86II::MO_GOTPCREL;
11460 WrapperKind = X86ISD::WrapperRIP;
11461 } else if (Subtarget->isPICStyleGOT()) {
11462 OpFlag = X86II::MO_GOT;
11463 } else if (Subtarget->isPICStyleStubPIC()) {
11464 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11465 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11466 OpFlag = X86II::MO_DARWIN_NONLAZY;
11469 auto PtrVT = getPointerTy(DAG.getDataLayout());
11470 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11473 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11475 // With PIC, the address is actually $g + Offset.
11476 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11477 !Subtarget->is64Bit()) {
11479 DAG.getNode(ISD::ADD, DL, PtrVT,
11480 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11483 // For symbols that require a load from a stub to get the address, emit the
11485 if (isGlobalStubReference(OpFlag))
11486 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11487 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11488 false, false, false, 0);
11494 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11495 // Create the TargetBlockAddressAddress node.
11496 unsigned char OpFlags =
11497 Subtarget->ClassifyBlockAddressReference();
11498 CodeModel::Model M = DAG.getTarget().getCodeModel();
11499 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11500 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11502 auto PtrVT = getPointerTy(DAG.getDataLayout());
11503 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11505 if (Subtarget->isPICStyleRIPRel() &&
11506 (M == CodeModel::Small || M == CodeModel::Kernel))
11507 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11509 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11511 // With PIC, the address is actually $g + Offset.
11512 if (isGlobalRelativeToPICBase(OpFlags)) {
11513 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11514 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11521 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11522 int64_t Offset, SelectionDAG &DAG) const {
11523 // Create the TargetGlobalAddress node, folding in the constant
11524 // offset if it is legal.
11525 unsigned char OpFlags =
11526 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11527 CodeModel::Model M = DAG.getTarget().getCodeModel();
11528 auto PtrVT = getPointerTy(DAG.getDataLayout());
11530 if (OpFlags == X86II::MO_NO_FLAG &&
11531 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11532 // A direct static reference to a global.
11533 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11536 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11539 if (Subtarget->isPICStyleRIPRel() &&
11540 (M == CodeModel::Small || M == CodeModel::Kernel))
11541 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11543 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11545 // With PIC, the address is actually $g + Offset.
11546 if (isGlobalRelativeToPICBase(OpFlags)) {
11547 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11548 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11551 // For globals that require a load from a stub to get the address, emit the
11553 if (isGlobalStubReference(OpFlags))
11554 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11555 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11556 false, false, false, 0);
11558 // If there was a non-zero offset that we didn't fold, create an explicit
11559 // addition for it.
11561 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11562 DAG.getConstant(Offset, dl, PtrVT));
11568 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11569 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11570 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11571 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11575 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11576 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11577 unsigned char OperandFlags, bool LocalDynamic = false) {
11578 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11579 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11581 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11582 GA->getValueType(0),
11586 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11590 SDValue Ops[] = { Chain, TGA, *InFlag };
11591 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11593 SDValue Ops[] = { Chain, TGA };
11594 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11597 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11598 MFI->setAdjustsStack(true);
11599 MFI->setHasCalls(true);
11601 SDValue Flag = Chain.getValue(1);
11602 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11605 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11607 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11610 SDLoc dl(GA); // ? function entry point might be better
11611 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11612 DAG.getNode(X86ISD::GlobalBaseReg,
11613 SDLoc(), PtrVT), InFlag);
11614 InFlag = Chain.getValue(1);
11616 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11619 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11621 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11623 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11624 X86::RAX, X86II::MO_TLSGD);
11627 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11633 // Get the start address of the TLS block for this module.
11634 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11635 .getInfo<X86MachineFunctionInfo>();
11636 MFI->incNumLocalDynamicTLSAccesses();
11640 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11641 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11644 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11645 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11646 InFlag = Chain.getValue(1);
11647 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11648 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11651 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11655 unsigned char OperandFlags = X86II::MO_DTPOFF;
11656 unsigned WrapperKind = X86ISD::Wrapper;
11657 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11658 GA->getValueType(0),
11659 GA->getOffset(), OperandFlags);
11660 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11662 // Add x@dtpoff with the base.
11663 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11666 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11667 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11668 const EVT PtrVT, TLSModel::Model model,
11669 bool is64Bit, bool isPIC) {
11672 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11673 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11674 is64Bit ? 257 : 256));
11676 SDValue ThreadPointer =
11677 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11678 MachinePointerInfo(Ptr), false, false, false, 0);
11680 unsigned char OperandFlags = 0;
11681 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11683 unsigned WrapperKind = X86ISD::Wrapper;
11684 if (model == TLSModel::LocalExec) {
11685 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11686 } else if (model == TLSModel::InitialExec) {
11688 OperandFlags = X86II::MO_GOTTPOFF;
11689 WrapperKind = X86ISD::WrapperRIP;
11691 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11694 llvm_unreachable("Unexpected model");
11697 // emit "addl x@ntpoff,%eax" (local exec)
11698 // or "addl x@indntpoff,%eax" (initial exec)
11699 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11701 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11702 GA->getOffset(), OperandFlags);
11703 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11705 if (model == TLSModel::InitialExec) {
11706 if (isPIC && !is64Bit) {
11707 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11708 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11712 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11713 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
11714 false, false, false, 0);
11717 // The address of the thread local variable is the add of the thread
11718 // pointer with the offset of the variable.
11719 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11723 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11725 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11726 const GlobalValue *GV = GA->getGlobal();
11727 auto PtrVT = getPointerTy(DAG.getDataLayout());
11729 if (Subtarget->isTargetELF()) {
11730 if (DAG.getTarget().Options.EmulatedTLS)
11731 return LowerToTLSEmulatedModel(GA, DAG);
11732 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11734 case TLSModel::GeneralDynamic:
11735 if (Subtarget->is64Bit())
11736 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11737 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11738 case TLSModel::LocalDynamic:
11739 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11740 Subtarget->is64Bit());
11741 case TLSModel::InitialExec:
11742 case TLSModel::LocalExec:
11743 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11744 DAG.getTarget().getRelocationModel() ==
11747 llvm_unreachable("Unknown TLS model.");
11750 if (Subtarget->isTargetDarwin()) {
11751 // Darwin only has one model of TLS. Lower to that.
11752 unsigned char OpFlag = 0;
11753 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11754 X86ISD::WrapperRIP : X86ISD::Wrapper;
11756 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11757 // global base reg.
11758 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11759 !Subtarget->is64Bit();
11761 OpFlag = X86II::MO_TLVP_PIC_BASE;
11763 OpFlag = X86II::MO_TLVP;
11765 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11766 GA->getValueType(0),
11767 GA->getOffset(), OpFlag);
11768 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11770 // With PIC32, the address is actually $g + Offset.
11772 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11773 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11776 // Lowering the machine isd will make sure everything is in the right
11778 SDValue Chain = DAG.getEntryNode();
11779 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11780 SDValue Args[] = { Chain, Offset };
11781 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11783 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11784 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11785 MFI->setAdjustsStack(true);
11787 // And our return value (tls address) is in the standard call return value
11789 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11790 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11793 if (Subtarget->isTargetKnownWindowsMSVC() ||
11794 Subtarget->isTargetWindowsGNU()) {
11795 // Just use the implicit TLS architecture
11796 // Need to generate someting similar to:
11797 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11799 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11800 // mov rcx, qword [rdx+rcx*8]
11801 // mov eax, .tls$:tlsvar
11802 // [rax+rcx] contains the address
11803 // Windows 64bit: gs:0x58
11804 // Windows 32bit: fs:__tls_array
11807 SDValue Chain = DAG.getEntryNode();
11809 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11810 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11811 // use its literal value of 0x2C.
11812 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11813 ? Type::getInt8PtrTy(*DAG.getContext(),
11815 : Type::getInt32PtrTy(*DAG.getContext(),
11818 SDValue TlsArray = Subtarget->is64Bit()
11819 ? DAG.getIntPtrConstant(0x58, dl)
11820 : (Subtarget->isTargetWindowsGNU()
11821 ? DAG.getIntPtrConstant(0x2C, dl)
11822 : DAG.getExternalSymbol("_tls_array", PtrVT));
11824 SDValue ThreadPointer =
11825 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11829 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11830 res = ThreadPointer;
11832 // Load the _tls_index variable
11833 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11834 if (Subtarget->is64Bit())
11835 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11836 MachinePointerInfo(), MVT::i32, false, false,
11839 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11842 auto &DL = DAG.getDataLayout();
11844 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11845 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11847 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11850 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11853 // Get the offset of start of .tls section
11854 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11855 GA->getValueType(0),
11856 GA->getOffset(), X86II::MO_SECREL);
11857 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11859 // The address of the thread local variable is the add of the thread
11860 // pointer with the offset of the variable.
11861 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11864 llvm_unreachable("TLS not implemented for this target.");
11867 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11868 /// and take a 2 x i32 value to shift plus a shift amount.
11869 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11870 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11871 MVT VT = Op.getSimpleValueType();
11872 unsigned VTBits = VT.getSizeInBits();
11874 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11875 SDValue ShOpLo = Op.getOperand(0);
11876 SDValue ShOpHi = Op.getOperand(1);
11877 SDValue ShAmt = Op.getOperand(2);
11878 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11879 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11881 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11882 DAG.getConstant(VTBits - 1, dl, MVT::i8));
11883 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11884 DAG.getConstant(VTBits - 1, dl, MVT::i8))
11885 : DAG.getConstant(0, dl, VT);
11887 SDValue Tmp2, Tmp3;
11888 if (Op.getOpcode() == ISD::SHL_PARTS) {
11889 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11890 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11892 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11893 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11896 // If the shift amount is larger or equal than the width of a part we can't
11897 // rely on the results of shld/shrd. Insert a test and select the appropriate
11898 // values for large shift amounts.
11899 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11900 DAG.getConstant(VTBits, dl, MVT::i8));
11901 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11902 AndNode, DAG.getConstant(0, dl, MVT::i8));
11905 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11906 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11907 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11909 if (Op.getOpcode() == ISD::SHL_PARTS) {
11910 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11911 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11913 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11914 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11917 SDValue Ops[2] = { Lo, Hi };
11918 return DAG.getMergeValues(Ops, dl);
11921 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11922 SelectionDAG &DAG) const {
11923 SDValue Src = Op.getOperand(0);
11924 MVT SrcVT = Src.getSimpleValueType();
11925 MVT VT = Op.getSimpleValueType();
11928 if (SrcVT.isVector()) {
11929 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11930 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11931 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11932 DAG.getUNDEF(SrcVT)));
11934 if (SrcVT.getVectorElementType() == MVT::i1) {
11935 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11936 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11937 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11942 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11943 "Unknown SINT_TO_FP to lower!");
11945 // These are really Legal; return the operand so the caller accepts it as
11947 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11949 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11950 Subtarget->is64Bit()) {
11954 unsigned Size = SrcVT.getSizeInBits()/8;
11955 MachineFunction &MF = DAG.getMachineFunction();
11956 auto PtrVT = getPointerTy(MF.getDataLayout());
11957 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11958 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11959 SDValue Chain = DAG.getStore(
11960 DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
11961 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
11963 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11966 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11968 SelectionDAG &DAG) const {
11972 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11974 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11976 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11978 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11980 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11981 MachineMemOperand *MMO;
11983 int SSFI = FI->getIndex();
11984 MMO = DAG.getMachineFunction().getMachineMemOperand(
11985 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
11986 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11988 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11989 StackSlot = StackSlot.getOperand(1);
11991 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11992 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11994 Tys, Ops, SrcVT, MMO);
11997 Chain = Result.getValue(1);
11998 SDValue InFlag = Result.getValue(2);
12000 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12001 // shouldn't be necessary except that RFP cannot be live across
12002 // multiple blocks. When stackifier is fixed, they can be uncoupled.
12003 MachineFunction &MF = DAG.getMachineFunction();
12004 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12005 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12006 auto PtrVT = getPointerTy(MF.getDataLayout());
12007 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12008 Tys = DAG.getVTList(MVT::Other);
12010 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12012 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12013 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12014 MachineMemOperand::MOStore, SSFISize, SSFISize);
12016 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12017 Ops, Op.getValueType(), MMO);
12018 Result = DAG.getLoad(
12019 Op.getValueType(), DL, Chain, StackSlot,
12020 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12021 false, false, false, 0);
12027 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12028 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12029 SelectionDAG &DAG) const {
12030 // This algorithm is not obvious. Here it is what we're trying to output:
12033 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12034 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12036 haddpd %xmm0, %xmm0
12038 pshufd $0x4e, %xmm0, %xmm1
12044 LLVMContext *Context = DAG.getContext();
12046 // Build some magic constants.
12047 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12048 Constant *C0 = ConstantDataVector::get(*Context, CV0);
12049 auto PtrVT = getPointerTy(DAG.getDataLayout());
12050 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12052 SmallVector<Constant*,2> CV1;
12054 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12055 APInt(64, 0x4330000000000000ULL))));
12057 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12058 APInt(64, 0x4530000000000000ULL))));
12059 Constant *C1 = ConstantVector::get(CV1);
12060 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12062 // Load the 64-bit value into an XMM register.
12063 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12066 DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12067 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12068 false, false, false, 16);
12070 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12073 DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12074 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12075 false, false, false, 16);
12076 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12077 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12080 if (Subtarget->hasSSE3()) {
12081 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12082 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12084 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12085 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12087 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12088 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12091 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12092 DAG.getIntPtrConstant(0, dl));
12095 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12096 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12097 SelectionDAG &DAG) const {
12099 // FP constant to bias correct the final result.
12100 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12103 // Load the 32-bit value into an XMM register.
12104 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12107 // Zero out the upper parts of the register.
12108 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12110 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12111 DAG.getBitcast(MVT::v2f64, Load),
12112 DAG.getIntPtrConstant(0, dl));
12114 // Or the load with the bias.
12115 SDValue Or = DAG.getNode(
12116 ISD::OR, dl, MVT::v2i64,
12117 DAG.getBitcast(MVT::v2i64,
12118 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12119 DAG.getBitcast(MVT::v2i64,
12120 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12122 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12123 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12125 // Subtract the bias.
12126 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12128 // Handle final rounding.
12129 EVT DestVT = Op.getValueType();
12131 if (DestVT.bitsLT(MVT::f64))
12132 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12133 DAG.getIntPtrConstant(0, dl));
12134 if (DestVT.bitsGT(MVT::f64))
12135 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12137 // Handle final rounding.
12141 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12142 const X86Subtarget &Subtarget) {
12143 // The algorithm is the following:
12144 // #ifdef __SSE4_1__
12145 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12146 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12147 // (uint4) 0x53000000, 0xaa);
12149 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12150 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12152 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12153 // return (float4) lo + fhi;
12156 SDValue V = Op->getOperand(0);
12157 EVT VecIntVT = V.getValueType();
12158 bool Is128 = VecIntVT == MVT::v4i32;
12159 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12160 // If we convert to something else than the supported type, e.g., to v4f64,
12162 if (VecFloatVT != Op->getValueType(0))
12165 unsigned NumElts = VecIntVT.getVectorNumElements();
12166 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12167 "Unsupported custom type");
12168 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12170 // In the #idef/#else code, we have in common:
12171 // - The vector of constants:
12177 // Create the splat vector for 0x4b000000.
12178 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12179 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12180 CstLow, CstLow, CstLow, CstLow};
12181 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12182 makeArrayRef(&CstLowArray[0], NumElts));
12183 // Create the splat vector for 0x53000000.
12184 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12185 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12186 CstHigh, CstHigh, CstHigh, CstHigh};
12187 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12188 makeArrayRef(&CstHighArray[0], NumElts));
12190 // Create the right shift.
12191 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12192 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12193 CstShift, CstShift, CstShift, CstShift};
12194 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12195 makeArrayRef(&CstShiftArray[0], NumElts));
12196 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12199 if (Subtarget.hasSSE41()) {
12200 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12201 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12202 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12203 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12204 // Low will be bitcasted right away, so do not bother bitcasting back to its
12206 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12207 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12208 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12209 // (uint4) 0x53000000, 0xaa);
12210 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12211 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12212 // High will be bitcasted right away, so do not bother bitcasting back to
12213 // its original type.
12214 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12215 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12217 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12218 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12219 CstMask, CstMask, CstMask);
12220 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12221 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12222 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12224 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12225 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12228 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12229 SDValue CstFAdd = DAG.getConstantFP(
12230 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12231 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12232 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12233 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12234 makeArrayRef(&CstFAddArray[0], NumElts));
12236 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12237 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12239 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12240 // return (float4) lo + fhi;
12241 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12242 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12245 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12246 SelectionDAG &DAG) const {
12247 SDValue N0 = Op.getOperand(0);
12248 MVT SVT = N0.getSimpleValueType();
12251 switch (SVT.SimpleTy) {
12253 llvm_unreachable("Custom UINT_TO_FP is not supported!");
12258 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12259 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12260 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12264 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12267 if (Subtarget->hasAVX512())
12268 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12269 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12271 llvm_unreachable(nullptr);
12274 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12275 SelectionDAG &DAG) const {
12276 SDValue N0 = Op.getOperand(0);
12278 auto PtrVT = getPointerTy(DAG.getDataLayout());
12280 if (Op.getValueType().isVector())
12281 return lowerUINT_TO_FP_vec(Op, DAG);
12283 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12284 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12285 // the optimization here.
12286 if (DAG.SignBitIsZero(N0))
12287 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12289 MVT SrcVT = N0.getSimpleValueType();
12290 MVT DstVT = Op.getSimpleValueType();
12291 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12292 return LowerUINT_TO_FP_i64(Op, DAG);
12293 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12294 return LowerUINT_TO_FP_i32(Op, DAG);
12295 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12298 // Make a 64-bit buffer, and use it to build an FILD.
12299 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12300 if (SrcVT == MVT::i32) {
12301 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12302 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12303 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12304 StackSlot, MachinePointerInfo(),
12306 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12307 OffsetSlot, MachinePointerInfo(),
12309 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12313 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12314 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12315 StackSlot, MachinePointerInfo(),
12317 // For i64 source, we need to add the appropriate power of 2 if the input
12318 // was negative. This is the same as the optimization in
12319 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12320 // we must be careful to do the computation in x87 extended precision, not
12321 // in SSE. (The generic code can't know it's OK to do this, or how to.)
12322 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12323 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12324 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12325 MachineMemOperand::MOLoad, 8, 8);
12327 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12328 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12329 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12332 APInt FF(32, 0x5F800000ULL);
12334 // Check whether the sign bit is set.
12335 SDValue SignSet = DAG.getSetCC(
12336 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12337 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12339 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12340 SDValue FudgePtr = DAG.getConstantPool(
12341 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12343 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12344 SDValue Zero = DAG.getIntPtrConstant(0, dl);
12345 SDValue Four = DAG.getIntPtrConstant(4, dl);
12346 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12348 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12350 // Load the value out, extending it from f32 to f80.
12351 // FIXME: Avoid the extend by constructing the right constant pool?
12352 SDValue Fudge = DAG.getExtLoad(
12353 ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12354 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12355 false, false, false, 4);
12356 // Extend everything to 80 bits to force it to be done on x87.
12357 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12358 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12359 DAG.getIntPtrConstant(0, dl));
12362 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12363 // is legal, or has an f16 source (which needs to be promoted to f32),
12364 // just return an <SDValue(), SDValue()> pair.
12365 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12366 // to i16, i32 or i64, and we lower it to a legal sequence.
12367 // If lowered to the final integer result we return a <result, SDValue()> pair.
12368 // Otherwise we lower it to a sequence ending with a FIST, return a
12369 // <FIST, StackSlot> pair, and the caller is responsible for loading
12370 // the final integer result from StackSlot.
12371 std::pair<SDValue,SDValue>
12372 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12373 bool IsSigned, bool IsReplace) const {
12376 EVT DstTy = Op.getValueType();
12377 EVT TheVT = Op.getOperand(0).getValueType();
12378 auto PtrVT = getPointerTy(DAG.getDataLayout());
12380 if (TheVT == MVT::f16)
12381 // We need to promote the f16 to f32 before using the lowering
12382 // in this routine.
12383 return std::make_pair(SDValue(), SDValue());
12385 assert((TheVT == MVT::f32 ||
12386 TheVT == MVT::f64 ||
12387 TheVT == MVT::f80) &&
12388 "Unexpected FP operand type in FP_TO_INTHelper");
12390 // If using FIST to compute an unsigned i64, we'll need some fixup
12391 // to handle values above the maximum signed i64. A FIST is always
12392 // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12393 bool UnsignedFixup = !IsSigned &&
12394 DstTy == MVT::i64 &&
12395 (!Subtarget->is64Bit() ||
12396 !isScalarFPTypeInSSEReg(TheVT));
12398 if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12399 // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12400 // The low 32 bits of the fist result will have the correct uint32 result.
12401 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12405 assert(DstTy.getSimpleVT() <= MVT::i64 &&
12406 DstTy.getSimpleVT() >= MVT::i16 &&
12407 "Unknown FP_TO_INT to lower!");
12409 // These are really Legal.
12410 if (DstTy == MVT::i32 &&
12411 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12412 return std::make_pair(SDValue(), SDValue());
12413 if (Subtarget->is64Bit() &&
12414 DstTy == MVT::i64 &&
12415 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12416 return std::make_pair(SDValue(), SDValue());
12418 // We lower FP->int64 into FISTP64 followed by a load from a temporary
12420 MachineFunction &MF = DAG.getMachineFunction();
12421 unsigned MemSize = DstTy.getSizeInBits()/8;
12422 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12423 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12426 switch (DstTy.getSimpleVT().SimpleTy) {
12427 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12428 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12429 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12430 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12433 SDValue Chain = DAG.getEntryNode();
12434 SDValue Value = Op.getOperand(0);
12435 SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12437 if (UnsignedFixup) {
12439 // Conversion to unsigned i64 is implemented with a select,
12440 // depending on whether the source value fits in the range
12441 // of a signed i64. Let Thresh be the FP equivalent of
12442 // 0x8000000000000000ULL.
12444 // Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12445 // FistSrc = (Value < Thresh) ? Value : (Value - Thresh);
12446 // Fist-to-mem64 FistSrc
12447 // Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12448 // to XOR'ing the high 32 bits with Adjust.
12450 // Being a power of 2, Thresh is exactly representable in all FP formats.
12451 // For X87 we'd like to use the smallest FP type for this constant, but
12452 // for DAG type consistency we have to match the FP operand type.
12454 APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
12455 APFloat::opStatus Status = APFloat::opOK;
12456 bool LosesInfo = false;
12457 if (TheVT == MVT::f64)
12458 // The rounding mode is irrelevant as the conversion should be exact.
12459 Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
12461 else if (TheVT == MVT::f80)
12462 Status = Thresh.convert(APFloat::x87DoubleExtended,
12463 APFloat::rmNearestTiesToEven, &LosesInfo);
12465 assert(Status == APFloat::opOK && !LosesInfo &&
12466 "FP conversion should have been exact");
12468 SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
12470 SDValue Cmp = DAG.getSetCC(DL,
12471 getSetCCResultType(DAG.getDataLayout(),
12472 *DAG.getContext(), TheVT),
12473 Value, ThreshVal, ISD::SETLT);
12474 Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
12475 DAG.getConstant(0, DL, MVT::i32),
12476 DAG.getConstant(0x80000000, DL, MVT::i32));
12477 SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
12478 Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
12479 *DAG.getContext(), TheVT),
12480 Value, ThreshVal, ISD::SETLT);
12481 Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
12484 // FIXME This causes a redundant load/store if the SSE-class value is already
12485 // in memory, such as if it is on the callstack.
12486 if (isScalarFPTypeInSSEReg(TheVT)) {
12487 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12488 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12489 MachinePointerInfo::getFixedStack(MF, SSFI), false,
12491 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12493 Chain, StackSlot, DAG.getValueType(TheVT)
12496 MachineMemOperand *MMO =
12497 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12498 MachineMemOperand::MOLoad, MemSize, MemSize);
12499 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12500 Chain = Value.getValue(1);
12501 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12502 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12505 MachineMemOperand *MMO =
12506 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
12507 MachineMemOperand::MOStore, MemSize, MemSize);
12509 if (UnsignedFixup) {
12511 // Insert the FIST, load its result as two i32's,
12512 // and XOR the high i32 with Adjust.
12514 SDValue FistOps[] = { Chain, Value, StackSlot };
12515 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12516 FistOps, DstTy, MMO);
12518 SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
12519 MachinePointerInfo(),
12520 false, false, false, 0);
12521 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
12522 DAG.getConstant(4, DL, PtrVT));
12524 SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
12525 MachinePointerInfo(),
12526 false, false, false, 0);
12527 High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
12529 if (Subtarget->is64Bit()) {
12530 // Join High32 and Low32 into a 64-bit result.
12531 // (High32 << 32) | Low32
12532 Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
12533 High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
12534 High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
12535 DAG.getConstant(32, DL, MVT::i8));
12536 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
12537 return std::make_pair(Result, SDValue());
12540 SDValue ResultOps[] = { Low32, High32 };
12542 SDValue pair = IsReplace
12543 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
12544 : DAG.getMergeValues(ResultOps, DL);
12545 return std::make_pair(pair, SDValue());
12547 // Build the FP_TO_INT*_IN_MEM
12548 SDValue Ops[] = { Chain, Value, StackSlot };
12549 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12551 return std::make_pair(FIST, StackSlot);
12555 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12556 const X86Subtarget *Subtarget) {
12557 MVT VT = Op->getSimpleValueType(0);
12558 SDValue In = Op->getOperand(0);
12559 MVT InVT = In.getSimpleValueType();
12562 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12563 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12565 // Optimize vectors in AVX mode:
12568 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12569 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12570 // Concat upper and lower parts.
12573 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12574 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12575 // Concat upper and lower parts.
12578 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12579 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12580 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12583 if (Subtarget->hasInt256())
12584 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12586 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12587 SDValue Undef = DAG.getUNDEF(InVT);
12588 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12589 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12590 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12592 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12593 VT.getVectorNumElements()/2);
12595 OpLo = DAG.getBitcast(HVT, OpLo);
12596 OpHi = DAG.getBitcast(HVT, OpHi);
12598 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12601 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12602 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12603 MVT VT = Op->getSimpleValueType(0);
12604 SDValue In = Op->getOperand(0);
12605 MVT InVT = In.getSimpleValueType();
12607 unsigned int NumElts = VT.getVectorNumElements();
12608 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12611 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12612 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12614 assert(InVT.getVectorElementType() == MVT::i1);
12615 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12617 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12619 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12621 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12622 if (VT.is512BitVector())
12624 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12627 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12628 SelectionDAG &DAG) {
12629 if (Subtarget->hasFp256())
12630 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12636 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12637 SelectionDAG &DAG) {
12639 MVT VT = Op.getSimpleValueType();
12640 SDValue In = Op.getOperand(0);
12641 MVT SVT = In.getSimpleValueType();
12643 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12644 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12646 if (Subtarget->hasFp256())
12647 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12650 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12651 VT.getVectorNumElements() != SVT.getVectorNumElements());
12655 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12657 MVT VT = Op.getSimpleValueType();
12658 SDValue In = Op.getOperand(0);
12659 MVT InVT = In.getSimpleValueType();
12661 if (VT == MVT::i1) {
12662 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12663 "Invalid scalar TRUNCATE operation");
12664 if (InVT.getSizeInBits() >= 32)
12666 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12667 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12669 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12670 "Invalid TRUNCATE operation");
12672 // move vector to mask - truncate solution for SKX
12673 if (VT.getVectorElementType() == MVT::i1) {
12674 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12675 Subtarget->hasBWI())
12676 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12677 if ((InVT.is256BitVector() || InVT.is128BitVector())
12678 && InVT.getScalarSizeInBits() <= 16 &&
12679 Subtarget->hasBWI() && Subtarget->hasVLX())
12680 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12681 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12682 Subtarget->hasDQI())
12683 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12684 if ((InVT.is256BitVector() || InVT.is128BitVector())
12685 && InVT.getScalarSizeInBits() >= 32 &&
12686 Subtarget->hasDQI() && Subtarget->hasVLX())
12687 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12690 if (VT.getVectorElementType() == MVT::i1) {
12691 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12692 unsigned NumElts = InVT.getVectorNumElements();
12693 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12694 if (InVT.getSizeInBits() < 512) {
12695 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12696 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12701 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12702 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12703 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12706 // vpmovqb/w/d, vpmovdb/w, vpmovwb
12707 if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12708 (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12709 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12711 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12712 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12713 if (Subtarget->hasInt256()) {
12714 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12715 In = DAG.getBitcast(MVT::v8i32, In);
12716 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12718 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12719 DAG.getIntPtrConstant(0, DL));
12722 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12723 DAG.getIntPtrConstant(0, DL));
12724 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12725 DAG.getIntPtrConstant(2, DL));
12726 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12727 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12728 static const int ShufMask[] = {0, 2, 4, 6};
12729 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12732 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12733 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12734 if (Subtarget->hasInt256()) {
12735 In = DAG.getBitcast(MVT::v32i8, In);
12737 SmallVector<SDValue,32> pshufbMask;
12738 for (unsigned i = 0; i < 2; ++i) {
12739 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12740 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12741 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12742 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12743 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12744 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12745 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12746 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12747 for (unsigned j = 0; j < 8; ++j)
12748 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12750 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12751 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12752 In = DAG.getBitcast(MVT::v4i64, In);
12754 static const int ShufMask[] = {0, 2, -1, -1};
12755 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12757 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12758 DAG.getIntPtrConstant(0, DL));
12759 return DAG.getBitcast(VT, In);
12762 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12763 DAG.getIntPtrConstant(0, DL));
12765 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12766 DAG.getIntPtrConstant(4, DL));
12768 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12769 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12771 // The PSHUFB mask:
12772 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12773 -1, -1, -1, -1, -1, -1, -1, -1};
12775 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12776 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12777 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12779 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12780 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12782 // The MOVLHPS Mask:
12783 static const int ShufMask2[] = {0, 1, 4, 5};
12784 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12785 return DAG.getBitcast(MVT::v8i16, res);
12788 // Handle truncation of V256 to V128 using shuffles.
12789 if (!VT.is128BitVector() || !InVT.is256BitVector())
12792 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12794 unsigned NumElems = VT.getVectorNumElements();
12795 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12797 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12798 // Prepare truncation shuffle mask
12799 for (unsigned i = 0; i != NumElems; ++i)
12800 MaskVec[i] = i * 2;
12801 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12802 DAG.getUNDEF(NVT), &MaskVec[0]);
12803 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12804 DAG.getIntPtrConstant(0, DL));
12807 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12808 SelectionDAG &DAG) const {
12809 assert(!Op.getSimpleValueType().isVector());
12811 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12812 /*IsSigned=*/ true, /*IsReplace=*/ false);
12813 SDValue FIST = Vals.first, StackSlot = Vals.second;
12814 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12815 if (!FIST.getNode())
12818 if (StackSlot.getNode())
12819 // Load the result.
12820 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12821 FIST, StackSlot, MachinePointerInfo(),
12822 false, false, false, 0);
12824 // The node is the result.
12828 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12829 SelectionDAG &DAG) const {
12830 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12831 /*IsSigned=*/ false, /*IsReplace=*/ false);
12832 SDValue FIST = Vals.first, StackSlot = Vals.second;
12833 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12834 if (!FIST.getNode())
12837 if (StackSlot.getNode())
12838 // Load the result.
12839 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12840 FIST, StackSlot, MachinePointerInfo(),
12841 false, false, false, 0);
12843 // The node is the result.
12847 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12849 MVT VT = Op.getSimpleValueType();
12850 SDValue In = Op.getOperand(0);
12851 MVT SVT = In.getSimpleValueType();
12853 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12855 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12856 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12857 In, DAG.getUNDEF(SVT)));
12860 /// The only differences between FABS and FNEG are the mask and the logic op.
12861 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12862 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12863 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12864 "Wrong opcode for lowering FABS or FNEG.");
12866 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12868 // If this is a FABS and it has an FNEG user, bail out to fold the combination
12869 // into an FNABS. We'll lower the FABS after that if it is still in use.
12871 for (SDNode *User : Op->uses())
12872 if (User->getOpcode() == ISD::FNEG)
12876 MVT VT = Op.getSimpleValueType();
12878 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12879 // decide if we should generate a 16-byte constant mask when we only need 4 or
12880 // 8 bytes for the scalar case.
12886 if (VT.isVector()) {
12888 EltVT = VT.getVectorElementType();
12889 NumElts = VT.getVectorNumElements();
12891 // There are no scalar bitwise logical SSE/AVX instructions, so we
12892 // generate a 16-byte vector constant and logic op even for the scalar case.
12893 // Using a 16-byte mask allows folding the load of the mask with
12894 // the logic op, so it can save (~4 bytes) on code size.
12895 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12897 NumElts = (VT == MVT::f64) ? 2 : 4;
12900 unsigned EltBits = EltVT.getSizeInBits();
12901 LLVMContext *Context = DAG.getContext();
12902 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12904 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12905 Constant *C = ConstantInt::get(*Context, MaskElt);
12906 C = ConstantVector::getSplat(NumElts, C);
12907 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12908 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12909 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12911 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12912 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12913 false, false, false, Alignment);
12915 SDValue Op0 = Op.getOperand(0);
12916 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12918 IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12919 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12922 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12924 // For the scalar case extend to a 128-bit vector, perform the logic op,
12925 // and extract the scalar result back out.
12926 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
12927 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12928 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
12929 DAG.getIntPtrConstant(0, dl));
12932 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12933 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12934 LLVMContext *Context = DAG.getContext();
12935 SDValue Op0 = Op.getOperand(0);
12936 SDValue Op1 = Op.getOperand(1);
12938 MVT VT = Op.getSimpleValueType();
12939 MVT SrcVT = Op1.getSimpleValueType();
12941 // If second operand is smaller, extend it first.
12942 if (SrcVT.bitsLT(VT)) {
12943 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12946 // And if it is bigger, shrink it first.
12947 if (SrcVT.bitsGT(VT)) {
12948 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12952 // At this point the operands and the result should have the same
12953 // type, and that won't be f80 since that is not custom lowered.
12955 const fltSemantics &Sem =
12956 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12957 const unsigned SizeInBits = VT.getSizeInBits();
12959 SmallVector<Constant *, 4> CV(
12960 VT == MVT::f64 ? 2 : 4,
12961 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12963 // First, clear all bits but the sign bit from the second operand (sign).
12964 CV[0] = ConstantFP::get(*Context,
12965 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12966 Constant *C = ConstantVector::get(CV);
12967 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12968 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12970 // Perform all logic operations as 16-byte vectors because there are no
12971 // scalar FP logic instructions in SSE. This allows load folding of the
12972 // constants into the logic instructions.
12973 MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12975 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12976 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12977 false, false, false, 16);
12978 Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
12979 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
12981 // Next, clear the sign bit from the first operand (magnitude).
12982 // If it's a constant, we can clear it here.
12983 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12984 APFloat APF = Op0CN->getValueAPF();
12985 // If the magnitude is a positive zero, the sign bit alone is enough.
12986 if (APF.isPosZero())
12987 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
12988 DAG.getIntPtrConstant(0, dl));
12990 CV[0] = ConstantFP::get(*Context, APF);
12992 CV[0] = ConstantFP::get(
12994 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12996 C = ConstantVector::get(CV);
12997 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12999 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13000 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13001 false, false, false, 16);
13002 // If the magnitude operand wasn't a constant, we need to AND out the sign.
13003 if (!isa<ConstantFPSDNode>(Op0)) {
13004 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13005 Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13007 // OR the magnitude value with the sign bit.
13008 Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13009 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13010 DAG.getIntPtrConstant(0, dl));
13013 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13014 SDValue N0 = Op.getOperand(0);
13016 MVT VT = Op.getSimpleValueType();
13018 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13019 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13020 DAG.getConstant(1, dl, VT));
13021 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13024 // Check whether an OR'd tree is PTEST-able.
13025 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13026 SelectionDAG &DAG) {
13027 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13029 if (!Subtarget->hasSSE41())
13032 if (!Op->hasOneUse())
13035 SDNode *N = Op.getNode();
13038 SmallVector<SDValue, 8> Opnds;
13039 DenseMap<SDValue, unsigned> VecInMap;
13040 SmallVector<SDValue, 8> VecIns;
13041 EVT VT = MVT::Other;
13043 // Recognize a special case where a vector is casted into wide integer to
13045 Opnds.push_back(N->getOperand(0));
13046 Opnds.push_back(N->getOperand(1));
13048 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13049 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13050 // BFS traverse all OR'd operands.
13051 if (I->getOpcode() == ISD::OR) {
13052 Opnds.push_back(I->getOperand(0));
13053 Opnds.push_back(I->getOperand(1));
13054 // Re-evaluate the number of nodes to be traversed.
13055 e += 2; // 2 more nodes (LHS and RHS) are pushed.
13059 // Quit if a non-EXTRACT_VECTOR_ELT
13060 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13063 // Quit if without a constant index.
13064 SDValue Idx = I->getOperand(1);
13065 if (!isa<ConstantSDNode>(Idx))
13068 SDValue ExtractedFromVec = I->getOperand(0);
13069 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13070 if (M == VecInMap.end()) {
13071 VT = ExtractedFromVec.getValueType();
13072 // Quit if not 128/256-bit vector.
13073 if (!VT.is128BitVector() && !VT.is256BitVector())
13075 // Quit if not the same type.
13076 if (VecInMap.begin() != VecInMap.end() &&
13077 VT != VecInMap.begin()->first.getValueType())
13079 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13080 VecIns.push_back(ExtractedFromVec);
13082 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13085 assert((VT.is128BitVector() || VT.is256BitVector()) &&
13086 "Not extracted from 128-/256-bit vector.");
13088 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13090 for (DenseMap<SDValue, unsigned>::const_iterator
13091 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13092 // Quit if not all elements are used.
13093 if (I->second != FullMask)
13097 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13099 // Cast all vectors into TestVT for PTEST.
13100 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13101 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13103 // If more than one full vectors are evaluated, OR them first before PTEST.
13104 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13105 // Each iteration will OR 2 nodes and append the result until there is only
13106 // 1 node left, i.e. the final OR'd value of all vectors.
13107 SDValue LHS = VecIns[Slot];
13108 SDValue RHS = VecIns[Slot + 1];
13109 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13112 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13113 VecIns.back(), VecIns.back());
13116 /// \brief return true if \c Op has a use that doesn't just read flags.
13117 static bool hasNonFlagsUse(SDValue Op) {
13118 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13120 SDNode *User = *UI;
13121 unsigned UOpNo = UI.getOperandNo();
13122 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13123 // Look pass truncate.
13124 UOpNo = User->use_begin().getOperandNo();
13125 User = *User->use_begin();
13128 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13129 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13135 /// Emit nodes that will be selected as "test Op0,Op0", or something
13137 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13138 SelectionDAG &DAG) const {
13139 if (Op.getValueType() == MVT::i1) {
13140 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13141 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13142 DAG.getConstant(0, dl, MVT::i8));
13144 // CF and OF aren't always set the way we want. Determine which
13145 // of these we need.
13146 bool NeedCF = false;
13147 bool NeedOF = false;
13150 case X86::COND_A: case X86::COND_AE:
13151 case X86::COND_B: case X86::COND_BE:
13154 case X86::COND_G: case X86::COND_GE:
13155 case X86::COND_L: case X86::COND_LE:
13156 case X86::COND_O: case X86::COND_NO: {
13157 // Check if we really need to set the
13158 // Overflow flag. If NoSignedWrap is present
13159 // that is not actually needed.
13160 switch (Op->getOpcode()) {
13165 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13166 if (BinNode->Flags.hasNoSignedWrap())
13176 // See if we can use the EFLAGS value from the operand instead of
13177 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13178 // we prove that the arithmetic won't overflow, we can't use OF or CF.
13179 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13180 // Emit a CMP with 0, which is the TEST pattern.
13181 //if (Op.getValueType() == MVT::i1)
13182 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13183 // DAG.getConstant(0, MVT::i1));
13184 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13185 DAG.getConstant(0, dl, Op.getValueType()));
13187 unsigned Opcode = 0;
13188 unsigned NumOperands = 0;
13190 // Truncate operations may prevent the merge of the SETCC instruction
13191 // and the arithmetic instruction before it. Attempt to truncate the operands
13192 // of the arithmetic instruction and use a reduced bit-width instruction.
13193 bool NeedTruncation = false;
13194 SDValue ArithOp = Op;
13195 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13196 SDValue Arith = Op->getOperand(0);
13197 // Both the trunc and the arithmetic op need to have one user each.
13198 if (Arith->hasOneUse())
13199 switch (Arith.getOpcode()) {
13206 NeedTruncation = true;
13212 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13213 // which may be the result of a CAST. We use the variable 'Op', which is the
13214 // non-casted variable when we check for possible users.
13215 switch (ArithOp.getOpcode()) {
13217 // Due to an isel shortcoming, be conservative if this add is likely to be
13218 // selected as part of a load-modify-store instruction. When the root node
13219 // in a match is a store, isel doesn't know how to remap non-chain non-flag
13220 // uses of other nodes in the match, such as the ADD in this case. This
13221 // leads to the ADD being left around and reselected, with the result being
13222 // two adds in the output. Alas, even if none our users are stores, that
13223 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
13224 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
13225 // climbing the DAG back to the root, and it doesn't seem to be worth the
13227 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13228 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13229 if (UI->getOpcode() != ISD::CopyToReg &&
13230 UI->getOpcode() != ISD::SETCC &&
13231 UI->getOpcode() != ISD::STORE)
13234 if (ConstantSDNode *C =
13235 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13236 // An add of one will be selected as an INC.
13237 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13238 Opcode = X86ISD::INC;
13243 // An add of negative one (subtract of one) will be selected as a DEC.
13244 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13245 Opcode = X86ISD::DEC;
13251 // Otherwise use a regular EFLAGS-setting add.
13252 Opcode = X86ISD::ADD;
13257 // If we have a constant logical shift that's only used in a comparison
13258 // against zero turn it into an equivalent AND. This allows turning it into
13259 // a TEST instruction later.
13260 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13261 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13262 EVT VT = Op.getValueType();
13263 unsigned BitWidth = VT.getSizeInBits();
13264 unsigned ShAmt = Op->getConstantOperandVal(1);
13265 if (ShAmt >= BitWidth) // Avoid undefined shifts.
13267 APInt Mask = ArithOp.getOpcode() == ISD::SRL
13268 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13269 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13270 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13272 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13273 DAG.getConstant(Mask, dl, VT));
13274 DAG.ReplaceAllUsesWith(Op, New);
13280 // If the primary and result isn't used, don't bother using X86ISD::AND,
13281 // because a TEST instruction will be better.
13282 if (!hasNonFlagsUse(Op))
13288 // Due to the ISEL shortcoming noted above, be conservative if this op is
13289 // likely to be selected as part of a load-modify-store instruction.
13290 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13291 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13292 if (UI->getOpcode() == ISD::STORE)
13295 // Otherwise use a regular EFLAGS-setting instruction.
13296 switch (ArithOp.getOpcode()) {
13297 default: llvm_unreachable("unexpected operator!");
13298 case ISD::SUB: Opcode = X86ISD::SUB; break;
13299 case ISD::XOR: Opcode = X86ISD::XOR; break;
13300 case ISD::AND: Opcode = X86ISD::AND; break;
13302 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13303 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13304 if (EFLAGS.getNode())
13307 Opcode = X86ISD::OR;
13321 return SDValue(Op.getNode(), 1);
13327 // If we found that truncation is beneficial, perform the truncation and
13329 if (NeedTruncation) {
13330 EVT VT = Op.getValueType();
13331 SDValue WideVal = Op->getOperand(0);
13332 EVT WideVT = WideVal.getValueType();
13333 unsigned ConvertedOp = 0;
13334 // Use a target machine opcode to prevent further DAGCombine
13335 // optimizations that may separate the arithmetic operations
13336 // from the setcc node.
13337 switch (WideVal.getOpcode()) {
13339 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13340 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13341 case ISD::AND: ConvertedOp = X86ISD::AND; break;
13342 case ISD::OR: ConvertedOp = X86ISD::OR; break;
13343 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13347 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13348 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13349 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13350 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13351 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13357 // Emit a CMP with 0, which is the TEST pattern.
13358 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13359 DAG.getConstant(0, dl, Op.getValueType()));
13361 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13362 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13364 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13365 DAG.ReplaceAllUsesWith(Op, New);
13366 return SDValue(New.getNode(), 1);
13369 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13371 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13372 SDLoc dl, SelectionDAG &DAG) const {
13373 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13374 if (C->getAPIntValue() == 0)
13375 return EmitTest(Op0, X86CC, dl, DAG);
13377 if (Op0.getValueType() == MVT::i1)
13378 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13381 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13382 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13383 // Do the comparison at i32 if it's smaller, besides the Atom case.
13384 // This avoids subregister aliasing issues. Keep the smaller reference
13385 // if we're optimizing for size, however, as that'll allow better folding
13386 // of memory operations.
13387 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13388 !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13389 !Subtarget->isAtom()) {
13390 unsigned ExtendOp =
13391 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13392 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13393 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13395 // Use SUB instead of CMP to enable CSE between SUB and CMP.
13396 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13397 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13399 return SDValue(Sub.getNode(), 1);
13401 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13404 /// Convert a comparison if required by the subtarget.
13405 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13406 SelectionDAG &DAG) const {
13407 // If the subtarget does not support the FUCOMI instruction, floating-point
13408 // comparisons have to be converted.
13409 if (Subtarget->hasCMov() ||
13410 Cmp.getOpcode() != X86ISD::CMP ||
13411 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13412 !Cmp.getOperand(1).getValueType().isFloatingPoint())
13415 // The instruction selector will select an FUCOM instruction instead of
13416 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13417 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13418 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13420 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13421 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13422 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13423 DAG.getConstant(8, dl, MVT::i8));
13424 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13425 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13428 /// The minimum architected relative accuracy is 2^-12. We need one
13429 /// Newton-Raphson step to have a good float result (24 bits of precision).
13430 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13431 DAGCombinerInfo &DCI,
13432 unsigned &RefinementSteps,
13433 bool &UseOneConstNR) const {
13434 EVT VT = Op.getValueType();
13435 const char *RecipOp;
13437 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13438 // TODO: Add support for AVX512 (v16f32).
13439 // It is likely not profitable to do this for f64 because a double-precision
13440 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13441 // instructions: convert to single, rsqrtss, convert back to double, refine
13442 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13443 // along with FMA, this could be a throughput win.
13444 if (VT == MVT::f32 && Subtarget->hasSSE1())
13446 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13447 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13448 RecipOp = "vec-sqrtf";
13452 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13453 if (!Recips.isEnabled(RecipOp))
13456 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13457 UseOneConstNR = false;
13458 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13461 /// The minimum architected relative accuracy is 2^-12. We need one
13462 /// Newton-Raphson step to have a good float result (24 bits of precision).
13463 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13464 DAGCombinerInfo &DCI,
13465 unsigned &RefinementSteps) const {
13466 EVT VT = Op.getValueType();
13467 const char *RecipOp;
13469 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13470 // TODO: Add support for AVX512 (v16f32).
13471 // It is likely not profitable to do this for f64 because a double-precision
13472 // reciprocal estimate with refinement on x86 prior to FMA requires
13473 // 15 instructions: convert to single, rcpss, convert back to double, refine
13474 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13475 // along with FMA, this could be a throughput win.
13476 if (VT == MVT::f32 && Subtarget->hasSSE1())
13478 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13479 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13480 RecipOp = "vec-divf";
13484 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13485 if (!Recips.isEnabled(RecipOp))
13488 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13489 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13492 /// If we have at least two divisions that use the same divisor, convert to
13493 /// multplication by a reciprocal. This may need to be adjusted for a given
13494 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13495 /// This is because we still need one division to calculate the reciprocal and
13496 /// then we need two multiplies by that reciprocal as replacements for the
13497 /// original divisions.
13498 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13502 static bool isAllOnes(SDValue V) {
13503 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13504 return C && C->isAllOnesValue();
13507 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13508 /// if it's possible.
13509 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13510 SDLoc dl, SelectionDAG &DAG) const {
13511 SDValue Op0 = And.getOperand(0);
13512 SDValue Op1 = And.getOperand(1);
13513 if (Op0.getOpcode() == ISD::TRUNCATE)
13514 Op0 = Op0.getOperand(0);
13515 if (Op1.getOpcode() == ISD::TRUNCATE)
13516 Op1 = Op1.getOperand(0);
13519 if (Op1.getOpcode() == ISD::SHL)
13520 std::swap(Op0, Op1);
13521 if (Op0.getOpcode() == ISD::SHL) {
13522 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13523 if (And00C->getZExtValue() == 1) {
13524 // If we looked past a truncate, check that it's only truncating away
13526 unsigned BitWidth = Op0.getValueSizeInBits();
13527 unsigned AndBitWidth = And.getValueSizeInBits();
13528 if (BitWidth > AndBitWidth) {
13530 DAG.computeKnownBits(Op0, Zeros, Ones);
13531 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13535 RHS = Op0.getOperand(1);
13537 } else if (Op1.getOpcode() == ISD::Constant) {
13538 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13539 uint64_t AndRHSVal = AndRHS->getZExtValue();
13540 SDValue AndLHS = Op0;
13542 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13543 LHS = AndLHS.getOperand(0);
13544 RHS = AndLHS.getOperand(1);
13547 // Use BT if the immediate can't be encoded in a TEST instruction.
13548 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13550 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13554 if (LHS.getNode()) {
13555 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
13556 // instruction. Since the shift amount is in-range-or-undefined, we know
13557 // that doing a bittest on the i32 value is ok. We extend to i32 because
13558 // the encoding for the i16 version is larger than the i32 version.
13559 // Also promote i16 to i32 for performance / code size reason.
13560 if (LHS.getValueType() == MVT::i8 ||
13561 LHS.getValueType() == MVT::i16)
13562 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13564 // If the operand types disagree, extend the shift amount to match. Since
13565 // BT ignores high bits (like shifts) we can use anyextend.
13566 if (LHS.getValueType() != RHS.getValueType())
13567 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13569 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13570 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13571 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13572 DAG.getConstant(Cond, dl, MVT::i8), BT);
13578 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13580 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13585 // SSE Condition code mapping:
13594 switch (SetCCOpcode) {
13595 default: llvm_unreachable("Unexpected SETCC condition");
13597 case ISD::SETEQ: SSECC = 0; break;
13599 case ISD::SETGT: Swap = true; // Fallthrough
13601 case ISD::SETOLT: SSECC = 1; break;
13603 case ISD::SETGE: Swap = true; // Fallthrough
13605 case ISD::SETOLE: SSECC = 2; break;
13606 case ISD::SETUO: SSECC = 3; break;
13608 case ISD::SETNE: SSECC = 4; break;
13609 case ISD::SETULE: Swap = true; // Fallthrough
13610 case ISD::SETUGE: SSECC = 5; break;
13611 case ISD::SETULT: Swap = true; // Fallthrough
13612 case ISD::SETUGT: SSECC = 6; break;
13613 case ISD::SETO: SSECC = 7; break;
13615 case ISD::SETONE: SSECC = 8; break;
13618 std::swap(Op0, Op1);
13623 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13624 // ones, and then concatenate the result back.
13625 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13626 MVT VT = Op.getSimpleValueType();
13628 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13629 "Unsupported value type for operation");
13631 unsigned NumElems = VT.getVectorNumElements();
13633 SDValue CC = Op.getOperand(2);
13635 // Extract the LHS vectors
13636 SDValue LHS = Op.getOperand(0);
13637 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13638 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13640 // Extract the RHS vectors
13641 SDValue RHS = Op.getOperand(1);
13642 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13643 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13645 // Issue the operation on the smaller types and concatenate the result back
13646 MVT EltVT = VT.getVectorElementType();
13647 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13648 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13649 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13650 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13653 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13654 SDValue Op0 = Op.getOperand(0);
13655 SDValue Op1 = Op.getOperand(1);
13656 SDValue CC = Op.getOperand(2);
13657 MVT VT = Op.getSimpleValueType();
13660 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13661 "Unexpected type for boolean compare operation");
13662 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13663 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13664 DAG.getConstant(-1, dl, VT));
13665 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13666 DAG.getConstant(-1, dl, VT));
13667 switch (SetCCOpcode) {
13668 default: llvm_unreachable("Unexpected SETCC condition");
13670 // (x == y) -> ~(x ^ y)
13671 return DAG.getNode(ISD::XOR, dl, VT,
13672 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13673 DAG.getConstant(-1, dl, VT));
13675 // (x != y) -> (x ^ y)
13676 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13679 // (x > y) -> (x & ~y)
13680 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13683 // (x < y) -> (~x & y)
13684 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13687 // (x <= y) -> (~x | y)
13688 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13691 // (x >=y) -> (x | ~y)
13692 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13696 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13697 const X86Subtarget *Subtarget) {
13698 SDValue Op0 = Op.getOperand(0);
13699 SDValue Op1 = Op.getOperand(1);
13700 SDValue CC = Op.getOperand(2);
13701 MVT VT = Op.getSimpleValueType();
13704 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13705 Op.getValueType().getScalarType() == MVT::i1 &&
13706 "Cannot set masked compare for this operation");
13708 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13710 bool Unsigned = false;
13713 switch (SetCCOpcode) {
13714 default: llvm_unreachable("Unexpected SETCC condition");
13715 case ISD::SETNE: SSECC = 4; break;
13716 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
13717 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13718 case ISD::SETLT: Swap = true; //fall-through
13719 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
13720 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13721 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13722 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
13723 case ISD::SETULE: Unsigned = true; //fall-through
13724 case ISD::SETLE: SSECC = 2; break;
13728 std::swap(Op0, Op1);
13730 return DAG.getNode(Opc, dl, VT, Op0, Op1);
13731 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13732 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13733 DAG.getConstant(SSECC, dl, MVT::i8));
13736 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13737 /// operand \p Op1. If non-trivial (for example because it's not constant)
13738 /// return an empty value.
13739 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13741 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13745 MVT VT = Op1.getSimpleValueType();
13746 MVT EVT = VT.getVectorElementType();
13747 unsigned n = VT.getVectorNumElements();
13748 SmallVector<SDValue, 8> ULTOp1;
13750 for (unsigned i = 0; i < n; ++i) {
13751 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13752 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13755 // Avoid underflow.
13756 APInt Val = Elt->getAPIntValue();
13760 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13763 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13766 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13767 SelectionDAG &DAG) {
13768 SDValue Op0 = Op.getOperand(0);
13769 SDValue Op1 = Op.getOperand(1);
13770 SDValue CC = Op.getOperand(2);
13771 MVT VT = Op.getSimpleValueType();
13772 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13773 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13778 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13779 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13782 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13783 unsigned Opc = X86ISD::CMPP;
13784 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13785 assert(VT.getVectorNumElements() <= 16);
13786 Opc = X86ISD::CMPM;
13788 // In the two special cases we can't handle, emit two comparisons.
13791 unsigned CombineOpc;
13792 if (SetCCOpcode == ISD::SETUEQ) {
13793 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13795 assert(SetCCOpcode == ISD::SETONE);
13796 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13799 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13800 DAG.getConstant(CC0, dl, MVT::i8));
13801 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13802 DAG.getConstant(CC1, dl, MVT::i8));
13803 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13805 // Handle all other FP comparisons here.
13806 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13807 DAG.getConstant(SSECC, dl, MVT::i8));
13810 // Break 256-bit integer vector compare into smaller ones.
13811 if (VT.is256BitVector() && !Subtarget->hasInt256())
13812 return Lower256IntVSETCC(Op, DAG);
13814 EVT OpVT = Op1.getValueType();
13815 if (OpVT.getVectorElementType() == MVT::i1)
13816 return LowerBoolVSETCC_AVX512(Op, DAG);
13818 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13819 if (Subtarget->hasAVX512()) {
13820 if (Op1.getValueType().is512BitVector() ||
13821 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13822 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13823 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13825 // In AVX-512 architecture setcc returns mask with i1 elements,
13826 // But there is no compare instruction for i8 and i16 elements in KNL.
13827 // We are not talking about 512-bit operands in this case, these
13828 // types are illegal.
13830 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13831 OpVT.getVectorElementType().getSizeInBits() >= 8))
13832 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13833 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13836 // We are handling one of the integer comparisons here. Since SSE only has
13837 // GT and EQ comparisons for integer, swapping operands and multiple
13838 // operations may be required for some comparisons.
13840 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13841 bool Subus = false;
13843 switch (SetCCOpcode) {
13844 default: llvm_unreachable("Unexpected SETCC condition");
13845 case ISD::SETNE: Invert = true;
13846 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
13847 case ISD::SETLT: Swap = true;
13848 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
13849 case ISD::SETGE: Swap = true;
13850 case ISD::SETLE: Opc = X86ISD::PCMPGT;
13851 Invert = true; break;
13852 case ISD::SETULT: Swap = true;
13853 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13854 FlipSigns = true; break;
13855 case ISD::SETUGE: Swap = true;
13856 case ISD::SETULE: Opc = X86ISD::PCMPGT;
13857 FlipSigns = true; Invert = true; break;
13860 // Special case: Use min/max operations for SETULE/SETUGE
13861 MVT VET = VT.getVectorElementType();
13863 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13864 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13867 switch (SetCCOpcode) {
13869 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13870 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13873 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13876 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13877 if (!MinMax && hasSubus) {
13878 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13880 // t = psubus Op0, Op1
13881 // pcmpeq t, <0..0>
13882 switch (SetCCOpcode) {
13884 case ISD::SETULT: {
13885 // If the comparison is against a constant we can turn this into a
13886 // setule. With psubus, setule does not require a swap. This is
13887 // beneficial because the constant in the register is no longer
13888 // destructed as the destination so it can be hoisted out of a loop.
13889 // Only do this pre-AVX since vpcmp* is no longer destructive.
13890 if (Subtarget->hasAVX())
13892 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13893 if (ULEOp1.getNode()) {
13895 Subus = true; Invert = false; Swap = false;
13899 // Psubus is better than flip-sign because it requires no inversion.
13900 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13901 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13905 Opc = X86ISD::SUBUS;
13911 std::swap(Op0, Op1);
13913 // Check that the operation in question is available (most are plain SSE2,
13914 // but PCMPGTQ and PCMPEQQ have different requirements).
13915 if (VT == MVT::v2i64) {
13916 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13917 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13919 // First cast everything to the right type.
13920 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13921 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13923 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13924 // bits of the inputs before performing those operations. The lower
13925 // compare is always unsigned.
13928 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13930 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13931 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13932 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13933 Sign, Zero, Sign, Zero);
13935 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13936 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13938 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13939 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13940 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13942 // Create masks for only the low parts/high parts of the 64 bit integers.
13943 static const int MaskHi[] = { 1, 1, 3, 3 };
13944 static const int MaskLo[] = { 0, 0, 2, 2 };
13945 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13946 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13947 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13949 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13950 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13953 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13955 return DAG.getBitcast(VT, Result);
13958 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13959 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13960 // pcmpeqd + pshufd + pand.
13961 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13963 // First cast everything to the right type.
13964 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13965 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13968 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13970 // Make sure the lower and upper halves are both all-ones.
13971 static const int Mask[] = { 1, 0, 3, 2 };
13972 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13973 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13976 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13978 return DAG.getBitcast(VT, Result);
13982 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13983 // bits of the inputs before performing those operations.
13985 EVT EltVT = VT.getVectorElementType();
13986 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13988 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13989 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13992 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13994 // If the logical-not of the result is required, perform that now.
13996 Result = DAG.getNOT(dl, Result, VT);
13999 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14002 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14003 getZeroVector(VT, Subtarget, DAG, dl));
14008 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14010 MVT VT = Op.getSimpleValueType();
14012 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14014 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14015 && "SetCC type must be 8-bit or 1-bit integer");
14016 SDValue Op0 = Op.getOperand(0);
14017 SDValue Op1 = Op.getOperand(1);
14019 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14021 // Optimize to BT if possible.
14022 // Lower (X & (1 << N)) == 0 to BT(X, N).
14023 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14024 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14025 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14026 Op1.getOpcode() == ISD::Constant &&
14027 cast<ConstantSDNode>(Op1)->isNullValue() &&
14028 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14029 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14030 if (NewSetCC.getNode()) {
14032 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14037 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
14039 if (Op1.getOpcode() == ISD::Constant &&
14040 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14041 cast<ConstantSDNode>(Op1)->isNullValue()) &&
14042 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14044 // If the input is a setcc, then reuse the input setcc or use a new one with
14045 // the inverted condition.
14046 if (Op0.getOpcode() == X86ISD::SETCC) {
14047 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14048 bool Invert = (CC == ISD::SETNE) ^
14049 cast<ConstantSDNode>(Op1)->isNullValue();
14053 CCode = X86::GetOppositeBranchCondition(CCode);
14054 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14055 DAG.getConstant(CCode, dl, MVT::i8),
14056 Op0.getOperand(1));
14058 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14062 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14063 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14064 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14066 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14067 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14070 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14071 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14072 if (X86CC == X86::COND_INVALID)
14075 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14076 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14077 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14078 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14080 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14084 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14085 static bool isX86LogicalCmp(SDValue Op) {
14086 unsigned Opc = Op.getNode()->getOpcode();
14087 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14088 Opc == X86ISD::SAHF)
14090 if (Op.getResNo() == 1 &&
14091 (Opc == X86ISD::ADD ||
14092 Opc == X86ISD::SUB ||
14093 Opc == X86ISD::ADC ||
14094 Opc == X86ISD::SBB ||
14095 Opc == X86ISD::SMUL ||
14096 Opc == X86ISD::UMUL ||
14097 Opc == X86ISD::INC ||
14098 Opc == X86ISD::DEC ||
14099 Opc == X86ISD::OR ||
14100 Opc == X86ISD::XOR ||
14101 Opc == X86ISD::AND))
14104 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14110 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14111 if (V.getOpcode() != ISD::TRUNCATE)
14114 SDValue VOp0 = V.getOperand(0);
14115 unsigned InBits = VOp0.getValueSizeInBits();
14116 unsigned Bits = V.getValueSizeInBits();
14117 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14120 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14121 bool addTest = true;
14122 SDValue Cond = Op.getOperand(0);
14123 SDValue Op1 = Op.getOperand(1);
14124 SDValue Op2 = Op.getOperand(2);
14126 EVT VT = Op1.getValueType();
14129 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14130 // are available or VBLENDV if AVX is available.
14131 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14132 if (Cond.getOpcode() == ISD::SETCC &&
14133 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14134 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14135 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14136 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14137 int SSECC = translateX86FSETCC(
14138 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14141 if (Subtarget->hasAVX512()) {
14142 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14143 DAG.getConstant(SSECC, DL, MVT::i8));
14144 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14147 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14148 DAG.getConstant(SSECC, DL, MVT::i8));
14150 // If we have AVX, we can use a variable vector select (VBLENDV) instead
14151 // of 3 logic instructions for size savings and potentially speed.
14152 // Unfortunately, there is no scalar form of VBLENDV.
14154 // If either operand is a constant, don't try this. We can expect to
14155 // optimize away at least one of the logic instructions later in that
14156 // case, so that sequence would be faster than a variable blend.
14158 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14159 // uses XMM0 as the selection register. That may need just as many
14160 // instructions as the AND/ANDN/OR sequence due to register moves, so
14163 if (Subtarget->hasAVX() &&
14164 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14166 // Convert to vectors, do a VSELECT, and convert back to scalar.
14167 // All of the conversions should be optimized away.
14169 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14170 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14171 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14172 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14174 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14175 VCmp = DAG.getBitcast(VCmpVT, VCmp);
14177 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14179 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14180 VSel, DAG.getIntPtrConstant(0, DL));
14182 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14183 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14184 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14188 if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14190 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14191 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14192 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14193 Op1Scalar = Op1.getOperand(0);
14195 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14196 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14197 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14198 Op2Scalar = Op2.getOperand(0);
14199 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14200 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14201 Op1Scalar.getValueType(),
14202 Cond, Op1Scalar, Op2Scalar);
14203 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14204 return DAG.getBitcast(VT, newSelect);
14205 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14206 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14207 DAG.getIntPtrConstant(0, DL));
14211 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14212 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14213 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14214 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14215 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14216 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14217 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14219 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14222 if (Cond.getOpcode() == ISD::SETCC) {
14223 SDValue NewCond = LowerSETCC(Cond, DAG);
14224 if (NewCond.getNode())
14228 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14229 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14230 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14231 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14232 if (Cond.getOpcode() == X86ISD::SETCC &&
14233 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14234 isZero(Cond.getOperand(1).getOperand(1))) {
14235 SDValue Cmp = Cond.getOperand(1);
14237 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14239 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14240 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14241 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14243 SDValue CmpOp0 = Cmp.getOperand(0);
14244 // Apply further optimizations for special cases
14245 // (select (x != 0), -1, 0) -> neg & sbb
14246 // (select (x == 0), 0, -1) -> neg & sbb
14247 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14248 if (YC->isNullValue() &&
14249 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14250 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14251 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14252 DAG.getConstant(0, DL,
14253 CmpOp0.getValueType()),
14255 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14256 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14257 SDValue(Neg.getNode(), 1));
14261 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14262 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14263 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14265 SDValue Res = // Res = 0 or -1.
14266 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14267 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14269 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14270 Res = DAG.getNOT(DL, Res, Res.getValueType());
14272 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14273 if (!N2C || !N2C->isNullValue())
14274 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14279 // Look past (and (setcc_carry (cmp ...)), 1).
14280 if (Cond.getOpcode() == ISD::AND &&
14281 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14282 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14283 if (C && C->getAPIntValue() == 1)
14284 Cond = Cond.getOperand(0);
14287 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14288 // setting operand in place of the X86ISD::SETCC.
14289 unsigned CondOpcode = Cond.getOpcode();
14290 if (CondOpcode == X86ISD::SETCC ||
14291 CondOpcode == X86ISD::SETCC_CARRY) {
14292 CC = Cond.getOperand(0);
14294 SDValue Cmp = Cond.getOperand(1);
14295 unsigned Opc = Cmp.getOpcode();
14296 MVT VT = Op.getSimpleValueType();
14298 bool IllegalFPCMov = false;
14299 if (VT.isFloatingPoint() && !VT.isVector() &&
14300 !isScalarFPTypeInSSEReg(VT)) // FPStack?
14301 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14303 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14304 Opc == X86ISD::BT) { // FIXME
14308 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14309 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14310 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14311 Cond.getOperand(0).getValueType() != MVT::i8)) {
14312 SDValue LHS = Cond.getOperand(0);
14313 SDValue RHS = Cond.getOperand(1);
14314 unsigned X86Opcode;
14317 switch (CondOpcode) {
14318 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14319 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14320 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14321 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14322 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14323 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14324 default: llvm_unreachable("unexpected overflowing operator");
14326 if (CondOpcode == ISD::UMULO)
14327 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14330 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14332 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14334 if (CondOpcode == ISD::UMULO)
14335 Cond = X86Op.getValue(2);
14337 Cond = X86Op.getValue(1);
14339 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14344 // Look past the truncate if the high bits are known zero.
14345 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14346 Cond = Cond.getOperand(0);
14348 // We know the result of AND is compared against zero. Try to match
14350 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14351 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14352 if (NewSetCC.getNode()) {
14353 CC = NewSetCC.getOperand(0);
14354 Cond = NewSetCC.getOperand(1);
14361 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14362 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14365 // a < b ? -1 : 0 -> RES = ~setcc_carry
14366 // a < b ? 0 : -1 -> RES = setcc_carry
14367 // a >= b ? -1 : 0 -> RES = setcc_carry
14368 // a >= b ? 0 : -1 -> RES = ~setcc_carry
14369 if (Cond.getOpcode() == X86ISD::SUB) {
14370 Cond = ConvertCmpIfNecessary(Cond, DAG);
14371 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14373 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14374 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14375 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14376 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14378 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14379 return DAG.getNOT(DL, Res, Res.getValueType());
14384 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14385 // widen the cmov and push the truncate through. This avoids introducing a new
14386 // branch during isel and doesn't add any extensions.
14387 if (Op.getValueType() == MVT::i8 &&
14388 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14389 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14390 if (T1.getValueType() == T2.getValueType() &&
14391 // Blacklist CopyFromReg to avoid partial register stalls.
14392 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14393 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14394 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14395 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14399 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14400 // condition is true.
14401 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14402 SDValue Ops[] = { Op2, Op1, CC, Cond };
14403 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14406 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14407 const X86Subtarget *Subtarget,
14408 SelectionDAG &DAG) {
14409 MVT VT = Op->getSimpleValueType(0);
14410 SDValue In = Op->getOperand(0);
14411 MVT InVT = In.getSimpleValueType();
14412 MVT VTElt = VT.getVectorElementType();
14413 MVT InVTElt = InVT.getVectorElementType();
14417 if ((InVTElt == MVT::i1) &&
14418 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14419 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14421 ((Subtarget->hasBWI() && VT.is512BitVector() &&
14422 VTElt.getSizeInBits() <= 16)) ||
14424 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14425 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14427 ((Subtarget->hasDQI() && VT.is512BitVector() &&
14428 VTElt.getSizeInBits() >= 32))))
14429 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14431 unsigned int NumElts = VT.getVectorNumElements();
14433 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14436 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14437 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14438 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14439 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14442 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14443 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14445 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14448 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14450 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14451 if (VT.is512BitVector())
14453 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14456 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14457 const X86Subtarget *Subtarget,
14458 SelectionDAG &DAG) {
14459 SDValue In = Op->getOperand(0);
14460 MVT VT = Op->getSimpleValueType(0);
14461 MVT InVT = In.getSimpleValueType();
14462 assert(VT.getSizeInBits() == InVT.getSizeInBits());
14464 MVT InSVT = InVT.getScalarType();
14465 assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14467 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14469 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14474 // SSE41 targets can use the pmovsx* instructions directly.
14475 if (Subtarget->hasSSE41())
14476 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14478 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14482 // As SRAI is only available on i16/i32 types, we expand only up to i32
14483 // and handle i64 separately.
14484 while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14485 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14486 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14487 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14488 Curr = DAG.getBitcast(CurrVT, Curr);
14491 SDValue SignExt = Curr;
14492 if (CurrVT != InVT) {
14493 unsigned SignExtShift =
14494 CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14495 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14496 DAG.getConstant(SignExtShift, dl, MVT::i8));
14502 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14503 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14504 DAG.getConstant(31, dl, MVT::i8));
14505 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14506 return DAG.getBitcast(VT, Ext);
14512 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14513 SelectionDAG &DAG) {
14514 MVT VT = Op->getSimpleValueType(0);
14515 SDValue In = Op->getOperand(0);
14516 MVT InVT = In.getSimpleValueType();
14519 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14520 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14522 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14523 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14524 (VT != MVT::v16i16 || InVT != MVT::v16i8))
14527 if (Subtarget->hasInt256())
14528 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14530 // Optimize vectors in AVX mode
14531 // Sign extend v8i16 to v8i32 and
14534 // Divide input vector into two parts
14535 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14536 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14537 // concat the vectors to original VT
14539 unsigned NumElems = InVT.getVectorNumElements();
14540 SDValue Undef = DAG.getUNDEF(InVT);
14542 SmallVector<int,8> ShufMask1(NumElems, -1);
14543 for (unsigned i = 0; i != NumElems/2; ++i)
14546 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14548 SmallVector<int,8> ShufMask2(NumElems, -1);
14549 for (unsigned i = 0; i != NumElems/2; ++i)
14550 ShufMask2[i] = i + NumElems/2;
14552 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14554 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14555 VT.getVectorNumElements()/2);
14557 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14558 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14560 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14563 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14564 // may emit an illegal shuffle but the expansion is still better than scalar
14565 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14566 // we'll emit a shuffle and a arithmetic shift.
14567 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14568 // TODO: It is possible to support ZExt by zeroing the undef values during
14569 // the shuffle phase or after the shuffle.
14570 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14571 SelectionDAG &DAG) {
14572 MVT RegVT = Op.getSimpleValueType();
14573 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14574 assert(RegVT.isInteger() &&
14575 "We only custom lower integer vector sext loads.");
14577 // Nothing useful we can do without SSE2 shuffles.
14578 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14580 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14582 EVT MemVT = Ld->getMemoryVT();
14583 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14584 unsigned RegSz = RegVT.getSizeInBits();
14586 ISD::LoadExtType Ext = Ld->getExtensionType();
14588 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14589 && "Only anyext and sext are currently implemented.");
14590 assert(MemVT != RegVT && "Cannot extend to the same type");
14591 assert(MemVT.isVector() && "Must load a vector from memory");
14593 unsigned NumElems = RegVT.getVectorNumElements();
14594 unsigned MemSz = MemVT.getSizeInBits();
14595 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14597 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14598 // The only way in which we have a legal 256-bit vector result but not the
14599 // integer 256-bit operations needed to directly lower a sextload is if we
14600 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14601 // a 128-bit vector and a normal sign_extend to 256-bits that should get
14602 // correctly legalized. We do this late to allow the canonical form of
14603 // sextload to persist throughout the rest of the DAG combiner -- it wants
14604 // to fold together any extensions it can, and so will fuse a sign_extend
14605 // of an sextload into a sextload targeting a wider value.
14607 if (MemSz == 128) {
14608 // Just switch this to a normal load.
14609 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14610 "it must be a legal 128-bit vector "
14612 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14613 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14614 Ld->isInvariant(), Ld->getAlignment());
14616 assert(MemSz < 128 &&
14617 "Can't extend a type wider than 128 bits to a 256 bit vector!");
14618 // Do an sext load to a 128-bit vector type. We want to use the same
14619 // number of elements, but elements half as wide. This will end up being
14620 // recursively lowered by this routine, but will succeed as we definitely
14621 // have all the necessary features if we're using AVX1.
14623 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14624 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14626 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14627 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14628 Ld->isNonTemporal(), Ld->isInvariant(),
14629 Ld->getAlignment());
14632 // Replace chain users with the new chain.
14633 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14634 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14636 // Finally, do a normal sign-extend to the desired register.
14637 return DAG.getSExtOrTrunc(Load, dl, RegVT);
14640 // All sizes must be a power of two.
14641 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14642 "Non-power-of-two elements are not custom lowered!");
14644 // Attempt to load the original value using scalar loads.
14645 // Find the largest scalar type that divides the total loaded size.
14646 MVT SclrLoadTy = MVT::i8;
14647 for (MVT Tp : MVT::integer_valuetypes()) {
14648 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14653 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14654 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14656 SclrLoadTy = MVT::f64;
14658 // Calculate the number of scalar loads that we need to perform
14659 // in order to load our vector from memory.
14660 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14662 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14663 "Can only lower sext loads with a single scalar load!");
14665 unsigned loadRegZize = RegSz;
14666 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14669 // Represent our vector as a sequence of elements which are the
14670 // largest scalar that we can load.
14671 EVT LoadUnitVecVT = EVT::getVectorVT(
14672 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14674 // Represent the data using the same element type that is stored in
14675 // memory. In practice, we ''widen'' MemVT.
14677 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14678 loadRegZize / MemVT.getScalarType().getSizeInBits());
14680 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14681 "Invalid vector type");
14683 // We can't shuffle using an illegal type.
14684 assert(TLI.isTypeLegal(WideVecVT) &&
14685 "We only lower types that form legal widened vector types");
14687 SmallVector<SDValue, 8> Chains;
14688 SDValue Ptr = Ld->getBasePtr();
14689 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14690 TLI.getPointerTy(DAG.getDataLayout()));
14691 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14693 for (unsigned i = 0; i < NumLoads; ++i) {
14694 // Perform a single load.
14695 SDValue ScalarLoad =
14696 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14697 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14698 Ld->getAlignment());
14699 Chains.push_back(ScalarLoad.getValue(1));
14700 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14701 // another round of DAGCombining.
14703 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14705 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14706 ScalarLoad, DAG.getIntPtrConstant(i, dl));
14708 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14711 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14713 // Bitcast the loaded value to a vector of the original element type, in
14714 // the size of the target vector type.
14715 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14716 unsigned SizeRatio = RegSz / MemSz;
14718 if (Ext == ISD::SEXTLOAD) {
14719 // If we have SSE4.1, we can directly emit a VSEXT node.
14720 if (Subtarget->hasSSE41()) {
14721 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14722 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14726 // Otherwise we'll shuffle the small elements in the high bits of the
14727 // larger type and perform an arithmetic shift. If the shift is not legal
14728 // it's better to scalarize.
14729 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14730 "We can't implement a sext load without an arithmetic right shift!");
14732 // Redistribute the loaded elements into the different locations.
14733 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14734 for (unsigned i = 0; i != NumElems; ++i)
14735 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14737 SDValue Shuff = DAG.getVectorShuffle(
14738 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14740 Shuff = DAG.getBitcast(RegVT, Shuff);
14742 // Build the arithmetic shift.
14743 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14744 MemVT.getVectorElementType().getSizeInBits();
14746 DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14747 DAG.getConstant(Amt, dl, RegVT));
14749 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14753 // Redistribute the loaded elements into the different locations.
14754 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14755 for (unsigned i = 0; i != NumElems; ++i)
14756 ShuffleVec[i * SizeRatio] = i;
14758 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14759 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14761 // Bitcast to the requested type.
14762 Shuff = DAG.getBitcast(RegVT, Shuff);
14763 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14767 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14768 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14769 // from the AND / OR.
14770 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14771 Opc = Op.getOpcode();
14772 if (Opc != ISD::OR && Opc != ISD::AND)
14774 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14775 Op.getOperand(0).hasOneUse() &&
14776 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14777 Op.getOperand(1).hasOneUse());
14780 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14781 // 1 and that the SETCC node has a single use.
14782 static bool isXor1OfSetCC(SDValue Op) {
14783 if (Op.getOpcode() != ISD::XOR)
14785 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14786 if (N1C && N1C->getAPIntValue() == 1) {
14787 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14788 Op.getOperand(0).hasOneUse();
14793 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14794 bool addTest = true;
14795 SDValue Chain = Op.getOperand(0);
14796 SDValue Cond = Op.getOperand(1);
14797 SDValue Dest = Op.getOperand(2);
14800 bool Inverted = false;
14802 if (Cond.getOpcode() == ISD::SETCC) {
14803 // Check for setcc([su]{add,sub,mul}o == 0).
14804 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14805 isa<ConstantSDNode>(Cond.getOperand(1)) &&
14806 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14807 Cond.getOperand(0).getResNo() == 1 &&
14808 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14809 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14810 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14811 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14812 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14813 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14815 Cond = Cond.getOperand(0);
14817 SDValue NewCond = LowerSETCC(Cond, DAG);
14818 if (NewCond.getNode())
14823 // FIXME: LowerXALUO doesn't handle these!!
14824 else if (Cond.getOpcode() == X86ISD::ADD ||
14825 Cond.getOpcode() == X86ISD::SUB ||
14826 Cond.getOpcode() == X86ISD::SMUL ||
14827 Cond.getOpcode() == X86ISD::UMUL)
14828 Cond = LowerXALUO(Cond, DAG);
14831 // Look pass (and (setcc_carry (cmp ...)), 1).
14832 if (Cond.getOpcode() == ISD::AND &&
14833 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14834 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14835 if (C && C->getAPIntValue() == 1)
14836 Cond = Cond.getOperand(0);
14839 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14840 // setting operand in place of the X86ISD::SETCC.
14841 unsigned CondOpcode = Cond.getOpcode();
14842 if (CondOpcode == X86ISD::SETCC ||
14843 CondOpcode == X86ISD::SETCC_CARRY) {
14844 CC = Cond.getOperand(0);
14846 SDValue Cmp = Cond.getOperand(1);
14847 unsigned Opc = Cmp.getOpcode();
14848 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14849 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14853 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14857 // These can only come from an arithmetic instruction with overflow,
14858 // e.g. SADDO, UADDO.
14859 Cond = Cond.getNode()->getOperand(1);
14865 CondOpcode = Cond.getOpcode();
14866 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14867 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14868 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14869 Cond.getOperand(0).getValueType() != MVT::i8)) {
14870 SDValue LHS = Cond.getOperand(0);
14871 SDValue RHS = Cond.getOperand(1);
14872 unsigned X86Opcode;
14875 // Keep this in sync with LowerXALUO, otherwise we might create redundant
14876 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14878 switch (CondOpcode) {
14879 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14881 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14883 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14886 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14887 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14889 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14891 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14894 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14895 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14896 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14897 default: llvm_unreachable("unexpected overflowing operator");
14900 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14901 if (CondOpcode == ISD::UMULO)
14902 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14905 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14907 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14909 if (CondOpcode == ISD::UMULO)
14910 Cond = X86Op.getValue(2);
14912 Cond = X86Op.getValue(1);
14914 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14918 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14919 SDValue Cmp = Cond.getOperand(0).getOperand(1);
14920 if (CondOpc == ISD::OR) {
14921 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14922 // two branches instead of an explicit OR instruction with a
14924 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14925 isX86LogicalCmp(Cmp)) {
14926 CC = Cond.getOperand(0).getOperand(0);
14927 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14928 Chain, Dest, CC, Cmp);
14929 CC = Cond.getOperand(1).getOperand(0);
14933 } else { // ISD::AND
14934 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14935 // two branches instead of an explicit AND instruction with a
14936 // separate test. However, we only do this if this block doesn't
14937 // have a fall-through edge, because this requires an explicit
14938 // jmp when the condition is false.
14939 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14940 isX86LogicalCmp(Cmp) &&
14941 Op.getNode()->hasOneUse()) {
14942 X86::CondCode CCode =
14943 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14944 CCode = X86::GetOppositeBranchCondition(CCode);
14945 CC = DAG.getConstant(CCode, dl, MVT::i8);
14946 SDNode *User = *Op.getNode()->use_begin();
14947 // Look for an unconditional branch following this conditional branch.
14948 // We need this because we need to reverse the successors in order
14949 // to implement FCMP_OEQ.
14950 if (User->getOpcode() == ISD::BR) {
14951 SDValue FalseBB = User->getOperand(1);
14953 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14954 assert(NewBR == User);
14958 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14959 Chain, Dest, CC, Cmp);
14960 X86::CondCode CCode =
14961 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14962 CCode = X86::GetOppositeBranchCondition(CCode);
14963 CC = DAG.getConstant(CCode, dl, MVT::i8);
14969 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14970 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14971 // It should be transformed during dag combiner except when the condition
14972 // is set by a arithmetics with overflow node.
14973 X86::CondCode CCode =
14974 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14975 CCode = X86::GetOppositeBranchCondition(CCode);
14976 CC = DAG.getConstant(CCode, dl, MVT::i8);
14977 Cond = Cond.getOperand(0).getOperand(1);
14979 } else if (Cond.getOpcode() == ISD::SETCC &&
14980 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14981 // For FCMP_OEQ, we can emit
14982 // two branches instead of an explicit AND instruction with a
14983 // separate test. However, we only do this if this block doesn't
14984 // have a fall-through edge, because this requires an explicit
14985 // jmp when the condition is false.
14986 if (Op.getNode()->hasOneUse()) {
14987 SDNode *User = *Op.getNode()->use_begin();
14988 // Look for an unconditional branch following this conditional branch.
14989 // We need this because we need to reverse the successors in order
14990 // to implement FCMP_OEQ.
14991 if (User->getOpcode() == ISD::BR) {
14992 SDValue FalseBB = User->getOperand(1);
14994 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14995 assert(NewBR == User);
14999 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15000 Cond.getOperand(0), Cond.getOperand(1));
15001 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15002 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15003 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15004 Chain, Dest, CC, Cmp);
15005 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15010 } else if (Cond.getOpcode() == ISD::SETCC &&
15011 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15012 // For FCMP_UNE, we can emit
15013 // two branches instead of an explicit AND instruction with a
15014 // separate test. However, we only do this if this block doesn't
15015 // have a fall-through edge, because this requires an explicit
15016 // jmp when the condition is false.
15017 if (Op.getNode()->hasOneUse()) {
15018 SDNode *User = *Op.getNode()->use_begin();
15019 // Look for an unconditional branch following this conditional branch.
15020 // We need this because we need to reverse the successors in order
15021 // to implement FCMP_UNE.
15022 if (User->getOpcode() == ISD::BR) {
15023 SDValue FalseBB = User->getOperand(1);
15025 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15026 assert(NewBR == User);
15029 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15030 Cond.getOperand(0), Cond.getOperand(1));
15031 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15032 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15033 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15034 Chain, Dest, CC, Cmp);
15035 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15045 // Look pass the truncate if the high bits are known zero.
15046 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15047 Cond = Cond.getOperand(0);
15049 // We know the result of AND is compared against zero. Try to match
15051 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15052 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15053 if (NewSetCC.getNode()) {
15054 CC = NewSetCC.getOperand(0);
15055 Cond = NewSetCC.getOperand(1);
15062 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15063 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15064 Cond = EmitTest(Cond, X86Cond, dl, DAG);
15066 Cond = ConvertCmpIfNecessary(Cond, DAG);
15067 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15068 Chain, Dest, CC, Cond);
15071 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15072 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15073 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15074 // that the guard pages used by the OS virtual memory manager are allocated in
15075 // correct sequence.
15077 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15078 SelectionDAG &DAG) const {
15079 MachineFunction &MF = DAG.getMachineFunction();
15080 bool SplitStack = MF.shouldSplitStack();
15081 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15086 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15087 SDNode* Node = Op.getNode();
15089 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15090 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15091 " not tell us which reg is the stack pointer!");
15092 EVT VT = Node->getValueType(0);
15093 SDValue Tmp1 = SDValue(Node, 0);
15094 SDValue Tmp2 = SDValue(Node, 1);
15095 SDValue Tmp3 = Node->getOperand(2);
15096 SDValue Chain = Tmp1.getOperand(0);
15098 // Chain the dynamic stack allocation so that it doesn't modify the stack
15099 // pointer when other instructions are using the stack.
15100 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
15103 SDValue Size = Tmp2.getOperand(1);
15104 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15105 Chain = SP.getValue(1);
15106 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15107 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15108 unsigned StackAlign = TFI.getStackAlignment();
15109 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15110 if (Align > StackAlign)
15111 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15112 DAG.getConstant(-(uint64_t)Align, dl, VT));
15113 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15115 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15116 DAG.getIntPtrConstant(0, dl, true), SDValue(),
15119 SDValue Ops[2] = { Tmp1, Tmp2 };
15120 return DAG.getMergeValues(Ops, dl);
15124 SDValue Chain = Op.getOperand(0);
15125 SDValue Size = Op.getOperand(1);
15126 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15127 EVT VT = Op.getNode()->getValueType(0);
15129 bool Is64Bit = Subtarget->is64Bit();
15130 MVT SPTy = getPointerTy(DAG.getDataLayout());
15133 MachineRegisterInfo &MRI = MF.getRegInfo();
15136 // The 64 bit implementation of segmented stacks needs to clobber both r10
15137 // r11. This makes it impossible to use it along with nested parameters.
15138 const Function *F = MF.getFunction();
15140 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15142 if (I->hasNestAttr())
15143 report_fatal_error("Cannot use segmented stacks with functions that "
15144 "have nested arguments.");
15147 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15148 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15149 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15150 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15151 DAG.getRegister(Vreg, SPTy));
15152 SDValue Ops1[2] = { Value, Chain };
15153 return DAG.getMergeValues(Ops1, dl);
15156 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15158 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15159 Flag = Chain.getValue(1);
15160 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15162 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15164 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15165 unsigned SPReg = RegInfo->getStackRegister();
15166 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15167 Chain = SP.getValue(1);
15170 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15171 DAG.getConstant(-(uint64_t)Align, dl, VT));
15172 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15175 SDValue Ops1[2] = { SP, Chain };
15176 return DAG.getMergeValues(Ops1, dl);
15180 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15181 MachineFunction &MF = DAG.getMachineFunction();
15182 auto PtrVT = getPointerTy(MF.getDataLayout());
15183 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15185 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15188 if (!Subtarget->is64Bit() ||
15189 Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15190 // vastart just stores the address of the VarArgsFrameIndex slot into the
15191 // memory location argument.
15192 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15193 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15194 MachinePointerInfo(SV), false, false, 0);
15198 // gp_offset (0 - 6 * 8)
15199 // fp_offset (48 - 48 + 8 * 16)
15200 // overflow_arg_area (point to parameters coming in memory).
15202 SmallVector<SDValue, 8> MemOps;
15203 SDValue FIN = Op.getOperand(1);
15205 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15206 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15208 FIN, MachinePointerInfo(SV), false, false, 0);
15209 MemOps.push_back(Store);
15212 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15213 Store = DAG.getStore(Op.getOperand(0), DL,
15214 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15216 FIN, MachinePointerInfo(SV, 4), false, false, 0);
15217 MemOps.push_back(Store);
15219 // Store ptr to overflow_arg_area
15220 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15221 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15222 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15223 MachinePointerInfo(SV, 8),
15225 MemOps.push_back(Store);
15227 // Store ptr to reg_save_area.
15228 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15229 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15230 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15231 MachinePointerInfo(SV, 16), false, false, 0);
15232 MemOps.push_back(Store);
15233 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15236 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15237 assert(Subtarget->is64Bit() &&
15238 "LowerVAARG only handles 64-bit va_arg!");
15239 assert(Op.getNode()->getNumOperands() == 4);
15241 MachineFunction &MF = DAG.getMachineFunction();
15242 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15243 // The Win64 ABI uses char* instead of a structure.
15244 return DAG.expandVAArg(Op.getNode());
15246 SDValue Chain = Op.getOperand(0);
15247 SDValue SrcPtr = Op.getOperand(1);
15248 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15249 unsigned Align = Op.getConstantOperandVal(3);
15252 EVT ArgVT = Op.getNode()->getValueType(0);
15253 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15254 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15257 // Decide which area this value should be read from.
15258 // TODO: Implement the AMD64 ABI in its entirety. This simple
15259 // selection mechanism works only for the basic types.
15260 if (ArgVT == MVT::f80) {
15261 llvm_unreachable("va_arg for f80 not yet implemented");
15262 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15263 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
15264 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15265 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
15267 llvm_unreachable("Unhandled argument type in LowerVAARG");
15270 if (ArgMode == 2) {
15271 // Sanity Check: Make sure using fp_offset makes sense.
15272 assert(!Subtarget->useSoftFloat() &&
15273 !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15274 Subtarget->hasSSE1());
15277 // Insert VAARG_64 node into the DAG
15278 // VAARG_64 returns two values: Variable Argument Address, Chain
15279 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15280 DAG.getConstant(ArgMode, dl, MVT::i8),
15281 DAG.getConstant(Align, dl, MVT::i32)};
15282 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15283 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15284 VTs, InstOps, MVT::i64,
15285 MachinePointerInfo(SV),
15287 /*Volatile=*/false,
15289 /*WriteMem=*/true);
15290 Chain = VAARG.getValue(1);
15292 // Load the next argument and return it
15293 return DAG.getLoad(ArgVT, dl,
15296 MachinePointerInfo(),
15297 false, false, false, 0);
15300 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15301 SelectionDAG &DAG) {
15302 // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15303 // where a va_list is still an i8*.
15304 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15305 if (Subtarget->isCallingConvWin64(
15306 DAG.getMachineFunction().getFunction()->getCallingConv()))
15307 // Probably a Win64 va_copy.
15308 return DAG.expandVACopy(Op.getNode());
15310 SDValue Chain = Op.getOperand(0);
15311 SDValue DstPtr = Op.getOperand(1);
15312 SDValue SrcPtr = Op.getOperand(2);
15313 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15314 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15317 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15318 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15320 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15323 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15324 // amount is a constant. Takes immediate version of shift as input.
15325 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15326 SDValue SrcOp, uint64_t ShiftAmt,
15327 SelectionDAG &DAG) {
15328 MVT ElementType = VT.getVectorElementType();
15330 // Fold this packed shift into its first operand if ShiftAmt is 0.
15334 // Check for ShiftAmt >= element width
15335 if (ShiftAmt >= ElementType.getSizeInBits()) {
15336 if (Opc == X86ISD::VSRAI)
15337 ShiftAmt = ElementType.getSizeInBits() - 1;
15339 return DAG.getConstant(0, dl, VT);
15342 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15343 && "Unknown target vector shift-by-constant node");
15345 // Fold this packed vector shift into a build vector if SrcOp is a
15346 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15347 if (VT == SrcOp.getSimpleValueType() &&
15348 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15349 SmallVector<SDValue, 8> Elts;
15350 unsigned NumElts = SrcOp->getNumOperands();
15351 ConstantSDNode *ND;
15354 default: llvm_unreachable(nullptr);
15355 case X86ISD::VSHLI:
15356 for (unsigned i=0; i!=NumElts; ++i) {
15357 SDValue CurrentOp = SrcOp->getOperand(i);
15358 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15359 Elts.push_back(CurrentOp);
15362 ND = cast<ConstantSDNode>(CurrentOp);
15363 const APInt &C = ND->getAPIntValue();
15364 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15367 case X86ISD::VSRLI:
15368 for (unsigned i=0; i!=NumElts; ++i) {
15369 SDValue CurrentOp = SrcOp->getOperand(i);
15370 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15371 Elts.push_back(CurrentOp);
15374 ND = cast<ConstantSDNode>(CurrentOp);
15375 const APInt &C = ND->getAPIntValue();
15376 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15379 case X86ISD::VSRAI:
15380 for (unsigned i=0; i!=NumElts; ++i) {
15381 SDValue CurrentOp = SrcOp->getOperand(i);
15382 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15383 Elts.push_back(CurrentOp);
15386 ND = cast<ConstantSDNode>(CurrentOp);
15387 const APInt &C = ND->getAPIntValue();
15388 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15393 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15396 return DAG.getNode(Opc, dl, VT, SrcOp,
15397 DAG.getConstant(ShiftAmt, dl, MVT::i8));
15400 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15401 // may or may not be a constant. Takes immediate version of shift as input.
15402 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15403 SDValue SrcOp, SDValue ShAmt,
15404 SelectionDAG &DAG) {
15405 MVT SVT = ShAmt.getSimpleValueType();
15406 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15408 // Catch shift-by-constant.
15409 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15410 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15411 CShAmt->getZExtValue(), DAG);
15413 // Change opcode to non-immediate version
15415 default: llvm_unreachable("Unknown target vector shift node");
15416 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15417 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15418 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15421 const X86Subtarget &Subtarget =
15422 static_cast<const X86Subtarget &>(DAG.getSubtarget());
15423 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15424 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15425 // Let the shuffle legalizer expand this shift amount node.
15426 SDValue Op0 = ShAmt.getOperand(0);
15427 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15428 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15430 // Need to build a vector containing shift amount.
15431 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15432 SmallVector<SDValue, 4> ShOps;
15433 ShOps.push_back(ShAmt);
15434 if (SVT == MVT::i32) {
15435 ShOps.push_back(DAG.getConstant(0, dl, SVT));
15436 ShOps.push_back(DAG.getUNDEF(SVT));
15438 ShOps.push_back(DAG.getUNDEF(SVT));
15440 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15441 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15444 // The return type has to be a 128-bit type with the same element
15445 // type as the input type.
15446 MVT EltVT = VT.getVectorElementType();
15447 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15449 ShAmt = DAG.getBitcast(ShVT, ShAmt);
15450 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15453 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15454 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15455 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15456 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15457 SDValue PreservedSrc,
15458 const X86Subtarget *Subtarget,
15459 SelectionDAG &DAG) {
15460 EVT VT = Op.getValueType();
15461 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15462 MVT::i1, VT.getVectorNumElements());
15463 SDValue VMask = SDValue();
15464 unsigned OpcodeSelect = ISD::VSELECT;
15467 assert(MaskVT.isSimple() && "invalid mask type");
15469 if (isAllOnes(Mask))
15472 if (MaskVT.bitsGT(Mask.getValueType())) {
15473 EVT newMaskVT = EVT::getIntegerVT(*DAG.getContext(),
15474 MaskVT.getSizeInBits());
15475 VMask = DAG.getBitcast(MaskVT,
15476 DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15478 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15479 Mask.getValueType().getSizeInBits());
15480 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15481 // are extracted by EXTRACT_SUBVECTOR.
15482 VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15483 DAG.getBitcast(BitcastVT, Mask),
15484 DAG.getIntPtrConstant(0, dl));
15487 switch (Op.getOpcode()) {
15489 case X86ISD::PCMPEQM:
15490 case X86ISD::PCMPGTM:
15492 case X86ISD::CMPMU:
15493 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15494 case X86ISD::VTRUNC:
15495 case X86ISD::VTRUNCS:
15496 case X86ISD::VTRUNCUS:
15497 // We can't use ISD::VSELECT here because it is not always "Legal"
15498 // for the destination type. For example vpmovqb require only AVX512
15499 // and vselect that can operate on byte element type require BWI
15500 OpcodeSelect = X86ISD::SELECT;
15503 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15504 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15505 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15508 /// \brief Creates an SDNode for a predicated scalar operation.
15509 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15510 /// The mask is coming as MVT::i8 and it should be truncated
15511 /// to MVT::i1 while lowering masking intrinsics.
15512 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15513 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15514 /// for a scalar instruction.
15515 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15516 SDValue PreservedSrc,
15517 const X86Subtarget *Subtarget,
15518 SelectionDAG &DAG) {
15519 if (isAllOnes(Mask))
15522 EVT VT = Op.getValueType();
15524 // The mask should be of type MVT::i1
15525 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15527 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15528 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15529 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15532 static int getSEHRegistrationNodeSize(const Function *Fn) {
15533 if (!Fn->hasPersonalityFn())
15534 report_fatal_error(
15535 "querying registration node size for function without personality");
15536 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15537 // WinEHStatePass for the full struct definition.
15538 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15539 case EHPersonality::MSVC_X86SEH: return 24;
15540 case EHPersonality::MSVC_CXX: return 16;
15543 report_fatal_error("can only recover FP for MSVC EH personality functions");
15546 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15547 /// function or when returning to a parent frame after catching an exception, we
15548 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15549 /// Here's the math:
15550 /// RegNodeBase = EntryEBP - RegNodeSize
15551 /// ParentFP = RegNodeBase - RegNodeFrameOffset
15552 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15553 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15554 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15555 SDValue EntryEBP) {
15556 MachineFunction &MF = DAG.getMachineFunction();
15559 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15560 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15562 // It's possible that the parent function no longer has a personality function
15563 // if the exceptional code was optimized away, in which case we just return
15564 // the incoming EBP.
15565 if (!Fn->hasPersonalityFn())
15568 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15570 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15572 MCSymbol *OffsetSym =
15573 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15574 GlobalValue::getRealLinkageName(Fn->getName()));
15575 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15576 SDValue RegNodeFrameOffset =
15577 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15579 // RegNodeBase = EntryEBP - RegNodeSize
15580 // ParentFP = RegNodeBase - RegNodeFrameOffset
15581 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15582 DAG.getConstant(RegNodeSize, dl, PtrVT));
15583 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15586 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15587 SelectionDAG &DAG) {
15589 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15590 EVT VT = Op.getValueType();
15591 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15593 switch(IntrData->Type) {
15594 case INTR_TYPE_1OP:
15595 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15596 case INTR_TYPE_2OP:
15597 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15599 case INTR_TYPE_2OP_IMM8:
15600 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15601 DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
15602 case INTR_TYPE_3OP:
15603 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15604 Op.getOperand(2), Op.getOperand(3));
15605 case INTR_TYPE_4OP:
15606 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15607 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15608 case INTR_TYPE_1OP_MASK_RM: {
15609 SDValue Src = Op.getOperand(1);
15610 SDValue PassThru = Op.getOperand(2);
15611 SDValue Mask = Op.getOperand(3);
15612 SDValue RoundingMode;
15613 // We allways add rounding mode to the Node.
15614 // If the rounding mode is not specified, we add the
15615 // "current direction" mode.
15616 if (Op.getNumOperands() == 4)
15618 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15620 RoundingMode = Op.getOperand(4);
15621 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15622 if (IntrWithRoundingModeOpcode != 0)
15623 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15624 X86::STATIC_ROUNDING::CUR_DIRECTION)
15625 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15626 dl, Op.getValueType(), Src, RoundingMode),
15627 Mask, PassThru, Subtarget, DAG);
15628 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15630 Mask, PassThru, Subtarget, DAG);
15632 case INTR_TYPE_1OP_MASK: {
15633 SDValue Src = Op.getOperand(1);
15634 SDValue PassThru = Op.getOperand(2);
15635 SDValue Mask = Op.getOperand(3);
15636 // We add rounding mode to the Node when
15637 // - RM Opcode is specified and
15638 // - RM is not "current direction".
15639 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15640 if (IntrWithRoundingModeOpcode != 0) {
15641 SDValue Rnd = Op.getOperand(4);
15642 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15643 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15644 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15645 dl, Op.getValueType(),
15647 Mask, PassThru, Subtarget, DAG);
15650 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15651 Mask, PassThru, Subtarget, DAG);
15653 case INTR_TYPE_SCALAR_MASK_RM: {
15654 SDValue Src1 = Op.getOperand(1);
15655 SDValue Src2 = Op.getOperand(2);
15656 SDValue Src0 = Op.getOperand(3);
15657 SDValue Mask = Op.getOperand(4);
15658 // There are 2 kinds of intrinsics in this group:
15659 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15660 // (2) With rounding mode and sae - 7 operands.
15661 if (Op.getNumOperands() == 6) {
15662 SDValue Sae = Op.getOperand(5);
15663 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15664 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15666 Mask, Src0, Subtarget, DAG);
15668 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15669 SDValue RoundingMode = Op.getOperand(5);
15670 SDValue Sae = Op.getOperand(6);
15671 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15672 RoundingMode, Sae),
15673 Mask, Src0, Subtarget, DAG);
15675 case INTR_TYPE_2OP_MASK: {
15676 SDValue Src1 = Op.getOperand(1);
15677 SDValue Src2 = Op.getOperand(2);
15678 SDValue PassThru = Op.getOperand(3);
15679 SDValue Mask = Op.getOperand(4);
15680 // We specify 2 possible opcodes for intrinsics with rounding modes.
15681 // First, we check if the intrinsic may have non-default rounding mode,
15682 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15683 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15684 if (IntrWithRoundingModeOpcode != 0) {
15685 SDValue Rnd = Op.getOperand(5);
15686 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15687 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15688 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15689 dl, Op.getValueType(),
15691 Mask, PassThru, Subtarget, DAG);
15694 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15696 Mask, PassThru, Subtarget, DAG);
15698 case INTR_TYPE_2OP_MASK_RM: {
15699 SDValue Src1 = Op.getOperand(1);
15700 SDValue Src2 = Op.getOperand(2);
15701 SDValue PassThru = Op.getOperand(3);
15702 SDValue Mask = Op.getOperand(4);
15703 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15704 // First, we check if the intrinsic have rounding mode (6 operands),
15705 // if not, we set rounding mode to "current".
15707 if (Op.getNumOperands() == 6)
15708 Rnd = Op.getOperand(5);
15710 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15711 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15713 Mask, PassThru, Subtarget, DAG);
15715 case INTR_TYPE_3OP_SCALAR_MASK_RM: {
15716 SDValue Src1 = Op.getOperand(1);
15717 SDValue Src2 = Op.getOperand(2);
15718 SDValue Src3 = Op.getOperand(3);
15719 SDValue PassThru = Op.getOperand(4);
15720 SDValue Mask = Op.getOperand(5);
15721 SDValue Sae = Op.getOperand(6);
15723 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
15725 Mask, PassThru, Subtarget, DAG);
15727 case INTR_TYPE_3OP_MASK_RM: {
15728 SDValue Src1 = Op.getOperand(1);
15729 SDValue Src2 = Op.getOperand(2);
15730 SDValue Imm = Op.getOperand(3);
15731 SDValue PassThru = Op.getOperand(4);
15732 SDValue Mask = Op.getOperand(5);
15733 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15734 // First, we check if the intrinsic have rounding mode (7 operands),
15735 // if not, we set rounding mode to "current".
15737 if (Op.getNumOperands() == 7)
15738 Rnd = Op.getOperand(6);
15740 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15741 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15742 Src1, Src2, Imm, Rnd),
15743 Mask, PassThru, Subtarget, DAG);
15745 case INTR_TYPE_3OP_IMM8_MASK:
15746 case INTR_TYPE_3OP_MASK: {
15747 SDValue Src1 = Op.getOperand(1);
15748 SDValue Src2 = Op.getOperand(2);
15749 SDValue Src3 = Op.getOperand(3);
15750 SDValue PassThru = Op.getOperand(4);
15751 SDValue Mask = Op.getOperand(5);
15753 if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
15754 Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
15755 // We specify 2 possible opcodes for intrinsics with rounding modes.
15756 // First, we check if the intrinsic may have non-default rounding mode,
15757 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15758 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15759 if (IntrWithRoundingModeOpcode != 0) {
15760 SDValue Rnd = Op.getOperand(6);
15761 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15762 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15763 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15764 dl, Op.getValueType(),
15765 Src1, Src2, Src3, Rnd),
15766 Mask, PassThru, Subtarget, DAG);
15769 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15771 Mask, PassThru, Subtarget, DAG);
15773 case VPERM_3OP_MASKZ:
15774 case VPERM_3OP_MASK:
15777 case FMA_OP_MASK: {
15778 SDValue Src1 = Op.getOperand(1);
15779 SDValue Src2 = Op.getOperand(2);
15780 SDValue Src3 = Op.getOperand(3);
15781 SDValue Mask = Op.getOperand(4);
15782 EVT VT = Op.getValueType();
15783 SDValue PassThru = SDValue();
15785 // set PassThru element
15786 if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15787 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15788 else if (IntrData->Type == FMA_OP_MASK3)
15793 // We specify 2 possible opcodes for intrinsics with rounding modes.
15794 // First, we check if the intrinsic may have non-default rounding mode,
15795 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15796 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15797 if (IntrWithRoundingModeOpcode != 0) {
15798 SDValue Rnd = Op.getOperand(5);
15799 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15800 X86::STATIC_ROUNDING::CUR_DIRECTION)
15801 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15802 dl, Op.getValueType(),
15803 Src1, Src2, Src3, Rnd),
15804 Mask, PassThru, Subtarget, DAG);
15806 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15807 dl, Op.getValueType(),
15809 Mask, PassThru, Subtarget, DAG);
15812 case CMP_MASK_CC: {
15813 // Comparison intrinsics with masks.
15814 // Example of transformation:
15815 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15816 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15818 // (v8i1 (insert_subvector undef,
15819 // (v2i1 (and (PCMPEQM %a, %b),
15820 // (extract_subvector
15821 // (v8i1 (bitcast %mask)), 0))), 0))))
15822 EVT VT = Op.getOperand(1).getValueType();
15823 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15824 VT.getVectorNumElements());
15825 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15826 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15827 Mask.getValueType().getSizeInBits());
15829 if (IntrData->Type == CMP_MASK_CC) {
15830 SDValue CC = Op.getOperand(3);
15831 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15832 // We specify 2 possible opcodes for intrinsics with rounding modes.
15833 // First, we check if the intrinsic may have non-default rounding mode,
15834 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15835 if (IntrData->Opc1 != 0) {
15836 SDValue Rnd = Op.getOperand(5);
15837 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15838 X86::STATIC_ROUNDING::CUR_DIRECTION)
15839 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15840 Op.getOperand(2), CC, Rnd);
15842 //default rounding mode
15844 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15845 Op.getOperand(2), CC);
15848 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15849 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15852 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15853 DAG.getTargetConstant(0, dl,
15856 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15857 DAG.getUNDEF(BitcastVT), CmpMask,
15858 DAG.getIntPtrConstant(0, dl));
15859 return DAG.getBitcast(Op.getValueType(), Res);
15861 case COMI: { // Comparison intrinsics
15862 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15863 SDValue LHS = Op.getOperand(1);
15864 SDValue RHS = Op.getOperand(2);
15865 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15866 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15867 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15868 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15869 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15870 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15873 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15874 Op.getOperand(1), Op.getOperand(2), DAG);
15876 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15877 Op.getSimpleValueType(),
15879 Op.getOperand(2), DAG),
15880 Op.getOperand(4), Op.getOperand(3), Subtarget,
15882 case COMPRESS_EXPAND_IN_REG: {
15883 SDValue Mask = Op.getOperand(3);
15884 SDValue DataToCompress = Op.getOperand(1);
15885 SDValue PassThru = Op.getOperand(2);
15886 if (isAllOnes(Mask)) // return data as is
15887 return Op.getOperand(1);
15889 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15891 Mask, PassThru, Subtarget, DAG);
15894 SDValue Mask = Op.getOperand(3);
15895 EVT VT = Op.getValueType();
15896 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15897 VT.getVectorNumElements());
15898 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15899 Mask.getValueType().getSizeInBits());
15901 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15902 DAG.getBitcast(BitcastVT, Mask),
15903 DAG.getIntPtrConstant(0, dl));
15904 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15913 default: return SDValue(); // Don't custom lower most intrinsics.
15915 case Intrinsic::x86_avx2_permd:
15916 case Intrinsic::x86_avx2_permps:
15917 // Operands intentionally swapped. Mask is last operand to intrinsic,
15918 // but second operand for node/instruction.
15919 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15920 Op.getOperand(2), Op.getOperand(1));
15922 // ptest and testp intrinsics. The intrinsic these come from are designed to
15923 // return an integer value, not just an instruction so lower it to the ptest
15924 // or testp pattern and a setcc for the result.
15925 case Intrinsic::x86_sse41_ptestz:
15926 case Intrinsic::x86_sse41_ptestc:
15927 case Intrinsic::x86_sse41_ptestnzc:
15928 case Intrinsic::x86_avx_ptestz_256:
15929 case Intrinsic::x86_avx_ptestc_256:
15930 case Intrinsic::x86_avx_ptestnzc_256:
15931 case Intrinsic::x86_avx_vtestz_ps:
15932 case Intrinsic::x86_avx_vtestc_ps:
15933 case Intrinsic::x86_avx_vtestnzc_ps:
15934 case Intrinsic::x86_avx_vtestz_pd:
15935 case Intrinsic::x86_avx_vtestc_pd:
15936 case Intrinsic::x86_avx_vtestnzc_pd:
15937 case Intrinsic::x86_avx_vtestz_ps_256:
15938 case Intrinsic::x86_avx_vtestc_ps_256:
15939 case Intrinsic::x86_avx_vtestnzc_ps_256:
15940 case Intrinsic::x86_avx_vtestz_pd_256:
15941 case Intrinsic::x86_avx_vtestc_pd_256:
15942 case Intrinsic::x86_avx_vtestnzc_pd_256: {
15943 bool IsTestPacked = false;
15946 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15947 case Intrinsic::x86_avx_vtestz_ps:
15948 case Intrinsic::x86_avx_vtestz_pd:
15949 case Intrinsic::x86_avx_vtestz_ps_256:
15950 case Intrinsic::x86_avx_vtestz_pd_256:
15951 IsTestPacked = true; // Fallthrough
15952 case Intrinsic::x86_sse41_ptestz:
15953 case Intrinsic::x86_avx_ptestz_256:
15955 X86CC = X86::COND_E;
15957 case Intrinsic::x86_avx_vtestc_ps:
15958 case Intrinsic::x86_avx_vtestc_pd:
15959 case Intrinsic::x86_avx_vtestc_ps_256:
15960 case Intrinsic::x86_avx_vtestc_pd_256:
15961 IsTestPacked = true; // Fallthrough
15962 case Intrinsic::x86_sse41_ptestc:
15963 case Intrinsic::x86_avx_ptestc_256:
15965 X86CC = X86::COND_B;
15967 case Intrinsic::x86_avx_vtestnzc_ps:
15968 case Intrinsic::x86_avx_vtestnzc_pd:
15969 case Intrinsic::x86_avx_vtestnzc_ps_256:
15970 case Intrinsic::x86_avx_vtestnzc_pd_256:
15971 IsTestPacked = true; // Fallthrough
15972 case Intrinsic::x86_sse41_ptestnzc:
15973 case Intrinsic::x86_avx_ptestnzc_256:
15975 X86CC = X86::COND_A;
15979 SDValue LHS = Op.getOperand(1);
15980 SDValue RHS = Op.getOperand(2);
15981 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15982 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15983 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15984 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15985 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15987 case Intrinsic::x86_avx512_kortestz_w:
15988 case Intrinsic::x86_avx512_kortestc_w: {
15989 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15990 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15991 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15992 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15993 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15994 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15995 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15998 case Intrinsic::x86_sse42_pcmpistria128:
15999 case Intrinsic::x86_sse42_pcmpestria128:
16000 case Intrinsic::x86_sse42_pcmpistric128:
16001 case Intrinsic::x86_sse42_pcmpestric128:
16002 case Intrinsic::x86_sse42_pcmpistrio128:
16003 case Intrinsic::x86_sse42_pcmpestrio128:
16004 case Intrinsic::x86_sse42_pcmpistris128:
16005 case Intrinsic::x86_sse42_pcmpestris128:
16006 case Intrinsic::x86_sse42_pcmpistriz128:
16007 case Intrinsic::x86_sse42_pcmpestriz128: {
16011 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16012 case Intrinsic::x86_sse42_pcmpistria128:
16013 Opcode = X86ISD::PCMPISTRI;
16014 X86CC = X86::COND_A;
16016 case Intrinsic::x86_sse42_pcmpestria128:
16017 Opcode = X86ISD::PCMPESTRI;
16018 X86CC = X86::COND_A;
16020 case Intrinsic::x86_sse42_pcmpistric128:
16021 Opcode = X86ISD::PCMPISTRI;
16022 X86CC = X86::COND_B;
16024 case Intrinsic::x86_sse42_pcmpestric128:
16025 Opcode = X86ISD::PCMPESTRI;
16026 X86CC = X86::COND_B;
16028 case Intrinsic::x86_sse42_pcmpistrio128:
16029 Opcode = X86ISD::PCMPISTRI;
16030 X86CC = X86::COND_O;
16032 case Intrinsic::x86_sse42_pcmpestrio128:
16033 Opcode = X86ISD::PCMPESTRI;
16034 X86CC = X86::COND_O;
16036 case Intrinsic::x86_sse42_pcmpistris128:
16037 Opcode = X86ISD::PCMPISTRI;
16038 X86CC = X86::COND_S;
16040 case Intrinsic::x86_sse42_pcmpestris128:
16041 Opcode = X86ISD::PCMPESTRI;
16042 X86CC = X86::COND_S;
16044 case Intrinsic::x86_sse42_pcmpistriz128:
16045 Opcode = X86ISD::PCMPISTRI;
16046 X86CC = X86::COND_E;
16048 case Intrinsic::x86_sse42_pcmpestriz128:
16049 Opcode = X86ISD::PCMPESTRI;
16050 X86CC = X86::COND_E;
16053 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16054 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16055 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16056 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16057 DAG.getConstant(X86CC, dl, MVT::i8),
16058 SDValue(PCMP.getNode(), 1));
16059 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16062 case Intrinsic::x86_sse42_pcmpistri128:
16063 case Intrinsic::x86_sse42_pcmpestri128: {
16065 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16066 Opcode = X86ISD::PCMPISTRI;
16068 Opcode = X86ISD::PCMPESTRI;
16070 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16071 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16072 return DAG.getNode(Opcode, dl, VTs, NewOps);
16075 case Intrinsic::x86_seh_lsda: {
16076 // Compute the symbol for the LSDA. We know it'll get emitted later.
16077 MachineFunction &MF = DAG.getMachineFunction();
16078 SDValue Op1 = Op.getOperand(1);
16079 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16080 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16081 GlobalValue::getRealLinkageName(Fn->getName()));
16083 // Generate a simple absolute symbol reference. This intrinsic is only
16084 // supported on 32-bit Windows, which isn't PIC.
16085 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16086 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16089 case Intrinsic::x86_seh_recoverfp: {
16090 SDValue FnOp = Op.getOperand(1);
16091 SDValue IncomingFPOp = Op.getOperand(2);
16092 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16093 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16095 report_fatal_error(
16096 "llvm.x86.seh.recoverfp must take a function as the first argument");
16097 return recoverFramePointer(DAG, Fn, IncomingFPOp);
16100 case Intrinsic::localaddress: {
16101 // Returns one of the stack, base, or frame pointer registers, depending on
16102 // which is used to reference local variables.
16103 MachineFunction &MF = DAG.getMachineFunction();
16104 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16106 if (RegInfo->hasBasePointer(MF))
16107 Reg = RegInfo->getBaseRegister();
16108 else // This function handles the SP or FP case.
16109 Reg = RegInfo->getPtrSizedFrameRegister(MF);
16110 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16115 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16116 SDValue Src, SDValue Mask, SDValue Base,
16117 SDValue Index, SDValue ScaleOp, SDValue Chain,
16118 const X86Subtarget * Subtarget) {
16120 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16122 llvm_unreachable("Invalid scale type");
16123 unsigned ScaleVal = C->getZExtValue();
16124 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16125 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16127 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16128 EVT MaskVT = MVT::getVectorVT(MVT::i1,
16129 Index.getSimpleValueType().getVectorNumElements());
16131 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16133 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16135 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16136 Mask.getValueType().getSizeInBits());
16138 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16139 // are extracted by EXTRACT_SUBVECTOR.
16140 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16141 DAG.getBitcast(BitcastVT, Mask),
16142 DAG.getIntPtrConstant(0, dl));
16144 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16145 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16146 SDValue Segment = DAG.getRegister(0, MVT::i32);
16147 if (Src.getOpcode() == ISD::UNDEF)
16148 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
16149 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16150 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16151 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16152 return DAG.getMergeValues(RetOps, dl);
16155 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16156 SDValue Src, SDValue Mask, SDValue Base,
16157 SDValue Index, SDValue ScaleOp, SDValue Chain) {
16159 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16161 llvm_unreachable("Invalid scale type");
16162 unsigned ScaleVal = C->getZExtValue();
16163 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
16164 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
16166 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16167 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16168 SDValue Segment = DAG.getRegister(0, MVT::i32);
16169 EVT MaskVT = MVT::getVectorVT(MVT::i1,
16170 Index.getSimpleValueType().getVectorNumElements());
16172 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16174 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16176 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16177 Mask.getValueType().getSizeInBits());
16179 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16180 // are extracted by EXTRACT_SUBVECTOR.
16181 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16182 DAG.getBitcast(BitcastVT, Mask),
16183 DAG.getIntPtrConstant(0, dl));
16185 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16186 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16187 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16188 return SDValue(Res, 1);
16191 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16192 SDValue Mask, SDValue Base, SDValue Index,
16193 SDValue ScaleOp, SDValue Chain) {
16195 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
16196 assert(C && "Invalid scale type");
16197 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16198 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16199 SDValue Segment = DAG.getRegister(0, MVT::i32);
16201 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16203 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16205 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16207 MaskInReg = DAG.getBitcast(MaskVT, Mask);
16208 //SDVTList VTs = DAG.getVTList(MVT::Other);
16209 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16210 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16211 return SDValue(Res, 0);
16214 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16215 // read performance monitor counters (x86_rdpmc).
16216 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16217 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16218 SmallVectorImpl<SDValue> &Results) {
16219 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16220 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16223 // The ECX register is used to select the index of the performance counter
16225 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16227 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16229 // Reads the content of a 64-bit performance counter and returns it in the
16230 // registers EDX:EAX.
16231 if (Subtarget->is64Bit()) {
16232 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16233 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16236 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16237 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16240 Chain = HI.getValue(1);
16242 if (Subtarget->is64Bit()) {
16243 // The EAX register is loaded with the low-order 32 bits. The EDX register
16244 // is loaded with the supported high-order bits of the counter.
16245 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16246 DAG.getConstant(32, DL, MVT::i8));
16247 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16248 Results.push_back(Chain);
16252 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16253 SDValue Ops[] = { LO, HI };
16254 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16255 Results.push_back(Pair);
16256 Results.push_back(Chain);
16259 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16260 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16261 // also used to custom lower READCYCLECOUNTER nodes.
16262 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16263 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16264 SmallVectorImpl<SDValue> &Results) {
16265 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16266 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16269 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16270 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16271 // and the EAX register is loaded with the low-order 32 bits.
16272 if (Subtarget->is64Bit()) {
16273 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16274 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16277 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16278 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16281 SDValue Chain = HI.getValue(1);
16283 if (Opcode == X86ISD::RDTSCP_DAG) {
16284 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16286 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16287 // the ECX register. Add 'ecx' explicitly to the chain.
16288 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16290 // Explicitly store the content of ECX at the location passed in input
16291 // to the 'rdtscp' intrinsic.
16292 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16293 MachinePointerInfo(), false, false, 0);
16296 if (Subtarget->is64Bit()) {
16297 // The EDX register is loaded with the high-order 32 bits of the MSR, and
16298 // the EAX register is loaded with the low-order 32 bits.
16299 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16300 DAG.getConstant(32, DL, MVT::i8));
16301 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16302 Results.push_back(Chain);
16306 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16307 SDValue Ops[] = { LO, HI };
16308 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16309 Results.push_back(Pair);
16310 Results.push_back(Chain);
16313 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16314 SelectionDAG &DAG) {
16315 SmallVector<SDValue, 2> Results;
16317 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16319 return DAG.getMergeValues(Results, DL);
16322 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16323 SelectionDAG &DAG) {
16324 MachineFunction &MF = DAG.getMachineFunction();
16325 const Function *Fn = MF.getFunction();
16327 SDValue Chain = Op.getOperand(0);
16329 assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16330 "using llvm.x86.seh.restoreframe requires a frame pointer");
16332 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16333 MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16335 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16336 unsigned FrameReg =
16337 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16338 unsigned SPReg = RegInfo->getStackRegister();
16339 unsigned SlotSize = RegInfo->getSlotSize();
16341 // Get incoming EBP.
16342 SDValue IncomingEBP =
16343 DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16345 // SP is saved in the first field of every registration node, so load
16346 // [EBP-RegNodeSize] into SP.
16347 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16348 SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16349 DAG.getConstant(-RegNodeSize, dl, VT));
16351 DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16352 false, VT.getScalarSizeInBits() / 8);
16353 Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16355 if (!RegInfo->needsStackRealignment(MF)) {
16356 // Adjust EBP to point back to the original frame position.
16357 SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16358 Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16360 assert(RegInfo->hasBasePointer(MF) &&
16361 "functions with Win32 EH must use frame or base pointer register");
16363 // Reload the base pointer (ESI) with the adjusted incoming EBP.
16364 SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16365 Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16367 // Reload the spilled EBP value, now that the stack and base pointers are
16369 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16370 X86FI->setHasSEHFramePtrSave(true);
16371 int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16372 X86FI->setSEHFramePtrSaveIndex(FI);
16373 SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16374 MachinePointerInfo(), false, false, false,
16375 VT.getScalarSizeInBits() / 8);
16376 Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16382 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16383 /// return truncate Store/MaskedStore Node
16384 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16388 SDValue Mask = Op.getOperand(4);
16389 SDValue DataToTruncate = Op.getOperand(3);
16390 SDValue Addr = Op.getOperand(2);
16391 SDValue Chain = Op.getOperand(0);
16393 EVT VT = DataToTruncate.getValueType();
16394 EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16395 ElementType, VT.getVectorNumElements());
16397 if (isAllOnes(Mask)) // return just a truncate store
16398 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16399 MachinePointerInfo(), SVT, false, false,
16400 SVT.getScalarSizeInBits()/8);
16402 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16403 MVT::i1, VT.getVectorNumElements());
16404 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16405 Mask.getValueType().getSizeInBits());
16406 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16407 // are extracted by EXTRACT_SUBVECTOR.
16408 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16409 DAG.getBitcast(BitcastVT, Mask),
16410 DAG.getIntPtrConstant(0, dl));
16412 MachineMemOperand *MMO = DAG.getMachineFunction().
16413 getMachineMemOperand(MachinePointerInfo(),
16414 MachineMemOperand::MOStore, SVT.getStoreSize(),
16415 SVT.getScalarSizeInBits()/8);
16417 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16418 VMask, SVT, MMO, true);
16421 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16422 SelectionDAG &DAG) {
16423 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16425 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16427 if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16428 return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16433 switch(IntrData->Type) {
16435 llvm_unreachable("Unknown Intrinsic Type");
16439 // Emit the node with the right value type.
16440 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16441 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16443 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16444 // Otherwise return the value from Rand, which is always 0, casted to i32.
16445 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16446 DAG.getConstant(1, dl, Op->getValueType(1)),
16447 DAG.getConstant(X86::COND_B, dl, MVT::i32),
16448 SDValue(Result.getNode(), 1) };
16449 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16450 DAG.getVTList(Op->getValueType(1), MVT::Glue),
16453 // Return { result, isValid, chain }.
16454 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16455 SDValue(Result.getNode(), 2));
16458 //gather(v1, mask, index, base, scale);
16459 SDValue Chain = Op.getOperand(0);
16460 SDValue Src = Op.getOperand(2);
16461 SDValue Base = Op.getOperand(3);
16462 SDValue Index = Op.getOperand(4);
16463 SDValue Mask = Op.getOperand(5);
16464 SDValue Scale = Op.getOperand(6);
16465 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16469 //scatter(base, mask, index, v1, scale);
16470 SDValue Chain = Op.getOperand(0);
16471 SDValue Base = Op.getOperand(2);
16472 SDValue Mask = Op.getOperand(3);
16473 SDValue Index = Op.getOperand(4);
16474 SDValue Src = Op.getOperand(5);
16475 SDValue Scale = Op.getOperand(6);
16476 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16480 SDValue Hint = Op.getOperand(6);
16481 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16482 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16483 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16484 SDValue Chain = Op.getOperand(0);
16485 SDValue Mask = Op.getOperand(2);
16486 SDValue Index = Op.getOperand(3);
16487 SDValue Base = Op.getOperand(4);
16488 SDValue Scale = Op.getOperand(5);
16489 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16491 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16493 SmallVector<SDValue, 2> Results;
16494 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16496 return DAG.getMergeValues(Results, dl);
16498 // Read Performance Monitoring Counters.
16500 SmallVector<SDValue, 2> Results;
16501 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16502 return DAG.getMergeValues(Results, dl);
16504 // XTEST intrinsics.
16506 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16507 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16508 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16509 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16511 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16512 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16513 Ret, SDValue(InTrans.getNode(), 1));
16517 SmallVector<SDValue, 2> Results;
16518 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16519 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16520 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16521 DAG.getConstant(-1, dl, MVT::i8));
16522 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16523 Op.getOperand(4), GenCF.getValue(1));
16524 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16525 Op.getOperand(5), MachinePointerInfo(),
16527 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16528 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16530 Results.push_back(SetCC);
16531 Results.push_back(Store);
16532 return DAG.getMergeValues(Results, dl);
16534 case COMPRESS_TO_MEM: {
16536 SDValue Mask = Op.getOperand(4);
16537 SDValue DataToCompress = Op.getOperand(3);
16538 SDValue Addr = Op.getOperand(2);
16539 SDValue Chain = Op.getOperand(0);
16541 EVT VT = DataToCompress.getValueType();
16542 if (isAllOnes(Mask)) // return just a store
16543 return DAG.getStore(Chain, dl, DataToCompress, Addr,
16544 MachinePointerInfo(), false, false,
16545 VT.getScalarSizeInBits()/8);
16547 SDValue Compressed =
16548 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16549 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16550 return DAG.getStore(Chain, dl, Compressed, Addr,
16551 MachinePointerInfo(), false, false,
16552 VT.getScalarSizeInBits()/8);
16554 case TRUNCATE_TO_MEM_VI8:
16555 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16556 case TRUNCATE_TO_MEM_VI16:
16557 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16558 case TRUNCATE_TO_MEM_VI32:
16559 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16560 case EXPAND_FROM_MEM: {
16562 SDValue Mask = Op.getOperand(4);
16563 SDValue PassThru = Op.getOperand(3);
16564 SDValue Addr = Op.getOperand(2);
16565 SDValue Chain = Op.getOperand(0);
16566 EVT VT = Op.getValueType();
16568 if (isAllOnes(Mask)) // return just a load
16569 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16570 false, VT.getScalarSizeInBits()/8);
16572 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16573 false, false, false,
16574 VT.getScalarSizeInBits()/8);
16576 SDValue Results[] = {
16577 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16578 Mask, PassThru, Subtarget, DAG), Chain};
16579 return DAG.getMergeValues(Results, dl);
16584 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16585 SelectionDAG &DAG) const {
16586 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16587 MFI->setReturnAddressIsTaken(true);
16589 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16592 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16594 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16597 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16598 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16599 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16600 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16601 DAG.getNode(ISD::ADD, dl, PtrVT,
16602 FrameAddr, Offset),
16603 MachinePointerInfo(), false, false, false, 0);
16606 // Just load the return address.
16607 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16608 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16609 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16612 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16613 MachineFunction &MF = DAG.getMachineFunction();
16614 MachineFrameInfo *MFI = MF.getFrameInfo();
16615 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16616 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16617 EVT VT = Op.getValueType();
16619 MFI->setFrameAddressIsTaken(true);
16621 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16622 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
16623 // is not possible to crawl up the stack without looking at the unwind codes
16625 int FrameAddrIndex = FuncInfo->getFAIndex();
16626 if (!FrameAddrIndex) {
16627 // Set up a frame object for the return address.
16628 unsigned SlotSize = RegInfo->getSlotSize();
16629 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16630 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16631 FuncInfo->setFAIndex(FrameAddrIndex);
16633 return DAG.getFrameIndex(FrameAddrIndex, VT);
16636 unsigned FrameReg =
16637 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16638 SDLoc dl(Op); // FIXME probably not meaningful
16639 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16640 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16641 (FrameReg == X86::EBP && VT == MVT::i32)) &&
16642 "Invalid Frame Register!");
16643 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16645 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16646 MachinePointerInfo(),
16647 false, false, false, 0);
16651 // FIXME? Maybe this could be a TableGen attribute on some registers and
16652 // this table could be generated automatically from RegInfo.
16653 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16654 SelectionDAG &DAG) const {
16655 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16656 const MachineFunction &MF = DAG.getMachineFunction();
16658 unsigned Reg = StringSwitch<unsigned>(RegName)
16659 .Case("esp", X86::ESP)
16660 .Case("rsp", X86::RSP)
16661 .Case("ebp", X86::EBP)
16662 .Case("rbp", X86::RBP)
16665 if (Reg == X86::EBP || Reg == X86::RBP) {
16666 if (!TFI.hasFP(MF))
16667 report_fatal_error("register " + StringRef(RegName) +
16668 " is allocatable: function has no frame pointer");
16671 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16672 unsigned FrameReg =
16673 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16674 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16675 "Invalid Frame Register!");
16683 report_fatal_error("Invalid register name global variable");
16686 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16687 SelectionDAG &DAG) const {
16688 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16689 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16692 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16693 SDValue Chain = Op.getOperand(0);
16694 SDValue Offset = Op.getOperand(1);
16695 SDValue Handler = Op.getOperand(2);
16698 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16699 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16700 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16701 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16702 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16703 "Invalid Frame Register!");
16704 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16705 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16707 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16708 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16710 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16711 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16713 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16715 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16716 DAG.getRegister(StoreAddrReg, PtrVT));
16719 SDValue X86TargetLowering::LowerCATCHRET(SDValue Op, SelectionDAG &DAG) const {
16720 SDValue Chain = Op.getOperand(0);
16721 SDValue Dest = Op.getOperand(1);
16724 MVT PtrVT = getPointerTy(DAG.getDataLayout());
16725 unsigned ReturnReg = (PtrVT == MVT::i64 ? X86::RAX : X86::EAX);
16727 // Load the address of the destination block.
16728 MachineBasicBlock *DestMBB = cast<BasicBlockSDNode>(Dest)->getBasicBlock();
16729 SDValue BlockPtr = DAG.getMCSymbol(DestMBB->getSymbol(), PtrVT);
16730 unsigned WrapperKind =
16731 Subtarget->isPICStyleRIPRel() ? X86ISD::WrapperRIP : X86ISD::Wrapper;
16732 SDValue WrappedPtr = DAG.getNode(WrapperKind, DL, PtrVT, BlockPtr);
16733 Chain = DAG.getCopyToReg(Chain, DL, ReturnReg, WrappedPtr);
16734 return DAG.getNode(X86ISD::CATCHRET, DL, MVT::Other, Chain,
16735 DAG.getRegister(ReturnReg, PtrVT));
16738 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16739 SelectionDAG &DAG) const {
16741 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16742 DAG.getVTList(MVT::i32, MVT::Other),
16743 Op.getOperand(0), Op.getOperand(1));
16746 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16747 SelectionDAG &DAG) const {
16749 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16750 Op.getOperand(0), Op.getOperand(1));
16753 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16754 return Op.getOperand(0);
16757 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16758 SelectionDAG &DAG) const {
16759 SDValue Root = Op.getOperand(0);
16760 SDValue Trmp = Op.getOperand(1); // trampoline
16761 SDValue FPtr = Op.getOperand(2); // nested function
16762 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16765 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16766 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16768 if (Subtarget->is64Bit()) {
16769 SDValue OutChains[6];
16771 // Large code-model.
16772 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
16773 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16775 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16776 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16778 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16780 // Load the pointer to the nested function into R11.
16781 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16782 SDValue Addr = Trmp;
16783 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16784 Addr, MachinePointerInfo(TrmpAddr),
16787 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16788 DAG.getConstant(2, dl, MVT::i64));
16789 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16790 MachinePointerInfo(TrmpAddr, 2),
16793 // Load the 'nest' parameter value into R10.
16794 // R10 is specified in X86CallingConv.td
16795 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16796 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16797 DAG.getConstant(10, dl, MVT::i64));
16798 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16799 Addr, MachinePointerInfo(TrmpAddr, 10),
16802 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16803 DAG.getConstant(12, dl, MVT::i64));
16804 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16805 MachinePointerInfo(TrmpAddr, 12),
16808 // Jump to the nested function.
16809 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16810 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16811 DAG.getConstant(20, dl, MVT::i64));
16812 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16813 Addr, MachinePointerInfo(TrmpAddr, 20),
16816 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16817 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16818 DAG.getConstant(22, dl, MVT::i64));
16819 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16820 Addr, MachinePointerInfo(TrmpAddr, 22),
16823 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16825 const Function *Func =
16826 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16827 CallingConv::ID CC = Func->getCallingConv();
16832 llvm_unreachable("Unsupported calling convention");
16833 case CallingConv::C:
16834 case CallingConv::X86_StdCall: {
16835 // Pass 'nest' parameter in ECX.
16836 // Must be kept in sync with X86CallingConv.td
16837 NestReg = X86::ECX;
16839 // Check that ECX wasn't needed by an 'inreg' parameter.
16840 FunctionType *FTy = Func->getFunctionType();
16841 const AttributeSet &Attrs = Func->getAttributes();
16843 if (!Attrs.isEmpty() && !Func->isVarArg()) {
16844 unsigned InRegCount = 0;
16847 for (FunctionType::param_iterator I = FTy->param_begin(),
16848 E = FTy->param_end(); I != E; ++I, ++Idx)
16849 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16850 auto &DL = DAG.getDataLayout();
16851 // FIXME: should only count parameters that are lowered to integers.
16852 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16855 if (InRegCount > 2) {
16856 report_fatal_error("Nest register in use - reduce number of inreg"
16862 case CallingConv::X86_FastCall:
16863 case CallingConv::X86_ThisCall:
16864 case CallingConv::Fast:
16865 // Pass 'nest' parameter in EAX.
16866 // Must be kept in sync with X86CallingConv.td
16867 NestReg = X86::EAX;
16871 SDValue OutChains[4];
16872 SDValue Addr, Disp;
16874 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16875 DAG.getConstant(10, dl, MVT::i32));
16876 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16878 // This is storing the opcode for MOV32ri.
16879 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16880 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16881 OutChains[0] = DAG.getStore(Root, dl,
16882 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16883 Trmp, MachinePointerInfo(TrmpAddr),
16886 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16887 DAG.getConstant(1, dl, MVT::i32));
16888 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16889 MachinePointerInfo(TrmpAddr, 1),
16892 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16893 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16894 DAG.getConstant(5, dl, MVT::i32));
16895 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16896 Addr, MachinePointerInfo(TrmpAddr, 5),
16899 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16900 DAG.getConstant(6, dl, MVT::i32));
16901 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16902 MachinePointerInfo(TrmpAddr, 6),
16905 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16909 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16910 SelectionDAG &DAG) const {
16912 The rounding mode is in bits 11:10 of FPSR, and has the following
16914 00 Round to nearest
16919 FLT_ROUNDS, on the other hand, expects the following:
16926 To perform the conversion, we do:
16927 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16930 MachineFunction &MF = DAG.getMachineFunction();
16931 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16932 unsigned StackAlignment = TFI.getStackAlignment();
16933 MVT VT = Op.getSimpleValueType();
16936 // Save FP Control Word to stack slot
16937 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16938 SDValue StackSlot =
16939 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16941 MachineMemOperand *MMO =
16942 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
16943 MachineMemOperand::MOStore, 2, 2);
16945 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16946 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16947 DAG.getVTList(MVT::Other),
16948 Ops, MVT::i16, MMO);
16950 // Load FP Control Word from stack slot
16951 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16952 MachinePointerInfo(), false, false, false, 0);
16954 // Transform as necessary
16956 DAG.getNode(ISD::SRL, DL, MVT::i16,
16957 DAG.getNode(ISD::AND, DL, MVT::i16,
16958 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16959 DAG.getConstant(11, DL, MVT::i8));
16961 DAG.getNode(ISD::SRL, DL, MVT::i16,
16962 DAG.getNode(ISD::AND, DL, MVT::i16,
16963 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16964 DAG.getConstant(9, DL, MVT::i8));
16967 DAG.getNode(ISD::AND, DL, MVT::i16,
16968 DAG.getNode(ISD::ADD, DL, MVT::i16,
16969 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16970 DAG.getConstant(1, DL, MVT::i16)),
16971 DAG.getConstant(3, DL, MVT::i16));
16973 return DAG.getNode((VT.getSizeInBits() < 16 ?
16974 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16977 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16978 MVT VT = Op.getSimpleValueType();
16980 unsigned NumBits = VT.getSizeInBits();
16983 Op = Op.getOperand(0);
16984 if (VT == MVT::i8) {
16985 // Zero extend to i32 since there is not an i8 bsr.
16987 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16990 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16991 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16992 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16994 // If src is zero (i.e. bsr sets ZF), returns NumBits.
16997 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16998 DAG.getConstant(X86::COND_E, dl, MVT::i8),
17001 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17003 // Finally xor with NumBits-1.
17004 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17005 DAG.getConstant(NumBits - 1, dl, OpVT));
17008 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17012 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
17013 MVT VT = Op.getSimpleValueType();
17015 unsigned NumBits = VT.getSizeInBits();
17018 Op = Op.getOperand(0);
17019 if (VT == MVT::i8) {
17020 // Zero extend to i32 since there is not an i8 bsr.
17022 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17025 // Issue a bsr (scan bits in reverse).
17026 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17027 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17029 // And xor with NumBits-1.
17030 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17031 DAG.getConstant(NumBits - 1, dl, OpVT));
17034 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17038 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17039 MVT VT = Op.getSimpleValueType();
17040 unsigned NumBits = VT.getSizeInBits();
17042 Op = Op.getOperand(0);
17044 // Issue a bsf (scan bits forward) which also sets EFLAGS.
17045 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17046 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
17048 // If src is zero (i.e. bsf sets ZF), returns NumBits.
17051 DAG.getConstant(NumBits, dl, VT),
17052 DAG.getConstant(X86::COND_E, dl, MVT::i8),
17055 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17058 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17059 // ones, and then concatenate the result back.
17060 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17061 MVT VT = Op.getSimpleValueType();
17063 assert(VT.is256BitVector() && VT.isInteger() &&
17064 "Unsupported value type for operation");
17066 unsigned NumElems = VT.getVectorNumElements();
17069 // Extract the LHS vectors
17070 SDValue LHS = Op.getOperand(0);
17071 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17072 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17074 // Extract the RHS vectors
17075 SDValue RHS = Op.getOperand(1);
17076 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17077 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17079 MVT EltVT = VT.getVectorElementType();
17080 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17082 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17083 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17084 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17087 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17088 if (Op.getValueType() == MVT::i1)
17089 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17090 Op.getOperand(0), Op.getOperand(1));
17091 assert(Op.getSimpleValueType().is256BitVector() &&
17092 Op.getSimpleValueType().isInteger() &&
17093 "Only handle AVX 256-bit vector integer operation");
17094 return Lower256IntArith(Op, DAG);
17097 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17098 if (Op.getValueType() == MVT::i1)
17099 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17100 Op.getOperand(0), Op.getOperand(1));
17101 assert(Op.getSimpleValueType().is256BitVector() &&
17102 Op.getSimpleValueType().isInteger() &&
17103 "Only handle AVX 256-bit vector integer operation");
17104 return Lower256IntArith(Op, DAG);
17107 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17108 assert(Op.getSimpleValueType().is256BitVector() &&
17109 Op.getSimpleValueType().isInteger() &&
17110 "Only handle AVX 256-bit vector integer operation");
17111 return Lower256IntArith(Op, DAG);
17114 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17115 SelectionDAG &DAG) {
17117 MVT VT = Op.getSimpleValueType();
17120 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17122 // Decompose 256-bit ops into smaller 128-bit ops.
17123 if (VT.is256BitVector() && !Subtarget->hasInt256())
17124 return Lower256IntArith(Op, DAG);
17126 SDValue A = Op.getOperand(0);
17127 SDValue B = Op.getOperand(1);
17129 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17130 // pairs, multiply and truncate.
17131 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17132 if (Subtarget->hasInt256()) {
17133 if (VT == MVT::v32i8) {
17134 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17135 SDValue Lo = DAG.getIntPtrConstant(0, dl);
17136 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17137 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17138 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17139 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17140 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
17141 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17142 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
17143 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
17146 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
17147 return DAG.getNode(
17148 ISD::TRUNCATE, dl, VT,
17149 DAG.getNode(ISD::MUL, dl, ExVT,
17150 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
17151 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
17154 assert(VT == MVT::v16i8 &&
17155 "Pre-AVX2 support only supports v16i8 multiplication");
17156 MVT ExVT = MVT::v8i16;
17158 // Extract the lo parts and sign extend to i16
17160 if (Subtarget->hasSSE41()) {
17161 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
17162 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
17164 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
17165 -1, 4, -1, 5, -1, 6, -1, 7};
17166 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17167 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17168 ALo = DAG.getBitcast(ExVT, ALo);
17169 BLo = DAG.getBitcast(ExVT, BLo);
17170 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
17171 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
17174 // Extract the hi parts and sign extend to i16
17176 if (Subtarget->hasSSE41()) {
17177 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
17178 -1, -1, -1, -1, -1, -1, -1, -1};
17179 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17180 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17181 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
17182 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
17184 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
17185 -1, 12, -1, 13, -1, 14, -1, 15};
17186 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
17187 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
17188 AHi = DAG.getBitcast(ExVT, AHi);
17189 BHi = DAG.getBitcast(ExVT, BHi);
17190 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
17191 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
17194 // Multiply, mask the lower 8bits of the lo/hi results and pack
17195 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
17196 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
17197 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
17198 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
17199 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17202 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
17203 if (VT == MVT::v4i32) {
17204 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
17205 "Should not custom lower when pmuldq is available!");
17207 // Extract the odd parts.
17208 static const int UnpackMask[] = { 1, -1, 3, -1 };
17209 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
17210 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
17212 // Multiply the even parts.
17213 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
17214 // Now multiply odd parts.
17215 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
17217 Evens = DAG.getBitcast(VT, Evens);
17218 Odds = DAG.getBitcast(VT, Odds);
17220 // Merge the two vectors back together with a shuffle. This expands into 2
17222 static const int ShufMask[] = { 0, 4, 2, 6 };
17223 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
17226 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
17227 "Only know how to lower V2I64/V4I64/V8I64 multiply");
17229 // Ahi = psrlqi(a, 32);
17230 // Bhi = psrlqi(b, 32);
17232 // AloBlo = pmuludq(a, b);
17233 // AloBhi = pmuludq(a, Bhi);
17234 // AhiBlo = pmuludq(Ahi, b);
17236 // AloBhi = psllqi(AloBhi, 32);
17237 // AhiBlo = psllqi(AhiBlo, 32);
17238 // return AloBlo + AloBhi + AhiBlo;
17240 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
17241 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
17243 SDValue AhiBlo = Ahi;
17244 SDValue AloBhi = Bhi;
17245 // Bit cast to 32-bit vectors for MULUDQ
17246 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17247 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17248 A = DAG.getBitcast(MulVT, A);
17249 B = DAG.getBitcast(MulVT, B);
17250 Ahi = DAG.getBitcast(MulVT, Ahi);
17251 Bhi = DAG.getBitcast(MulVT, Bhi);
17253 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17254 // After shifting right const values the result may be all-zero.
17255 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17256 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17257 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17259 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17260 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17261 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17264 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17265 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17268 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17269 assert(Subtarget->isTargetWin64() && "Unexpected target");
17270 EVT VT = Op.getValueType();
17271 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17272 "Unexpected return type for lowering");
17276 switch (Op->getOpcode()) {
17277 default: llvm_unreachable("Unexpected request for libcall!");
17278 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
17279 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
17280 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
17281 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
17282 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
17283 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17287 SDValue InChain = DAG.getEntryNode();
17289 TargetLowering::ArgListTy Args;
17290 TargetLowering::ArgListEntry Entry;
17291 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17292 EVT ArgVT = Op->getOperand(i).getValueType();
17293 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17294 "Unexpected argument type for lowering");
17295 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17296 Entry.Node = StackPtr;
17297 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17299 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17300 Entry.Ty = PointerType::get(ArgTy,0);
17301 Entry.isSExt = false;
17302 Entry.isZExt = false;
17303 Args.push_back(Entry);
17306 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17307 getPointerTy(DAG.getDataLayout()));
17309 TargetLowering::CallLoweringInfo CLI(DAG);
17310 CLI.setDebugLoc(dl).setChain(InChain)
17311 .setCallee(getLibcallCallingConv(LC),
17312 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17313 Callee, std::move(Args), 0)
17314 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17316 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17317 return DAG.getBitcast(VT, CallInfo.first);
17320 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17321 SelectionDAG &DAG) {
17322 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17323 EVT VT = Op0.getValueType();
17326 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17327 (VT == MVT::v8i32 && Subtarget->hasInt256()));
17329 // PMULxD operations multiply each even value (starting at 0) of LHS with
17330 // the related value of RHS and produce a widen result.
17331 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17332 // => <2 x i64> <ae|cg>
17334 // In other word, to have all the results, we need to perform two PMULxD:
17335 // 1. one with the even values.
17336 // 2. one with the odd values.
17337 // To achieve #2, with need to place the odd values at an even position.
17339 // Place the odd value at an even position (basically, shift all values 1
17340 // step to the left):
17341 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17342 // <a|b|c|d> => <b|undef|d|undef>
17343 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17344 // <e|f|g|h> => <f|undef|h|undef>
17345 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17347 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17349 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17350 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17352 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17353 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17354 // => <2 x i64> <ae|cg>
17355 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17356 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17357 // => <2 x i64> <bf|dh>
17358 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17360 // Shuffle it back into the right order.
17361 SDValue Highs, Lows;
17362 if (VT == MVT::v8i32) {
17363 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17364 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17365 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17366 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17368 const int HighMask[] = {1, 5, 3, 7};
17369 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17370 const int LowMask[] = {0, 4, 2, 6};
17371 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17374 // If we have a signed multiply but no PMULDQ fix up the high parts of a
17375 // unsigned multiply.
17376 if (IsSigned && !Subtarget->hasSSE41()) {
17377 SDValue ShAmt = DAG.getConstant(
17379 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17380 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17381 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17382 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17383 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17385 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17386 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17389 // The first result of MUL_LOHI is actually the low value, followed by the
17391 SDValue Ops[] = {Lows, Highs};
17392 return DAG.getMergeValues(Ops, dl);
17395 // Return true if the required (according to Opcode) shift-imm form is natively
17396 // supported by the Subtarget
17397 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17399 if (VT.getScalarSizeInBits() < 16)
17402 if (VT.is512BitVector() &&
17403 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17406 bool LShift = VT.is128BitVector() ||
17407 (VT.is256BitVector() && Subtarget->hasInt256());
17409 bool AShift = LShift && (Subtarget->hasVLX() ||
17410 (VT != MVT::v2i64 && VT != MVT::v4i64));
17411 return (Opcode == ISD::SRA) ? AShift : LShift;
17414 // The shift amount is a variable, but it is the same for all vector lanes.
17415 // These instructions are defined together with shift-immediate.
17417 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17419 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17422 // Return true if the required (according to Opcode) variable-shift form is
17423 // natively supported by the Subtarget
17424 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17427 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17430 // vXi16 supported only on AVX-512, BWI
17431 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17434 if (VT.is512BitVector() || Subtarget->hasVLX())
17437 bool LShift = VT.is128BitVector() || VT.is256BitVector();
17438 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
17439 return (Opcode == ISD::SRA) ? AShift : LShift;
17442 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17443 const X86Subtarget *Subtarget) {
17444 MVT VT = Op.getSimpleValueType();
17446 SDValue R = Op.getOperand(0);
17447 SDValue Amt = Op.getOperand(1);
17449 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17450 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17452 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17453 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17454 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17455 SDValue Ex = DAG.getBitcast(ExVT, R);
17457 if (ShiftAmt >= 32) {
17458 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17460 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17461 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17462 ShiftAmt - 32, DAG);
17463 if (VT == MVT::v2i64)
17464 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17465 if (VT == MVT::v4i64)
17466 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17467 {9, 1, 11, 3, 13, 5, 15, 7});
17469 // SRA upper i32, SHL whole i64 and select lower i32.
17470 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17473 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17474 Lower = DAG.getBitcast(ExVT, Lower);
17475 if (VT == MVT::v2i64)
17476 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17477 if (VT == MVT::v4i64)
17478 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17479 {8, 1, 10, 3, 12, 5, 14, 7});
17481 return DAG.getBitcast(VT, Ex);
17484 // Optimize shl/srl/sra with constant shift amount.
17485 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17486 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17487 uint64_t ShiftAmt = ShiftConst->getZExtValue();
17489 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17490 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17492 // i64 SRA needs to be performed as partial shifts.
17493 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17494 Op.getOpcode() == ISD::SRA)
17495 return ArithmeticShiftRight64(ShiftAmt);
17497 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17498 unsigned NumElts = VT.getVectorNumElements();
17499 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17501 if (Op.getOpcode() == ISD::SHL) {
17502 // Simple i8 add case
17504 return DAG.getNode(ISD::ADD, dl, VT, R, R);
17506 // Make a large shift.
17507 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17509 SHL = DAG.getBitcast(VT, SHL);
17510 // Zero out the rightmost bits.
17511 SmallVector<SDValue, 32> V(
17512 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17513 return DAG.getNode(ISD::AND, dl, VT, SHL,
17514 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17516 if (Op.getOpcode() == ISD::SRL) {
17517 // Make a large shift.
17518 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17520 SRL = DAG.getBitcast(VT, SRL);
17521 // Zero out the leftmost bits.
17522 SmallVector<SDValue, 32> V(
17523 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17524 return DAG.getNode(ISD::AND, dl, VT, SRL,
17525 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17527 if (Op.getOpcode() == ISD::SRA) {
17528 if (ShiftAmt == 7) {
17529 // ashr(R, 7) === cmp_slt(R, 0)
17530 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17531 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17534 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17535 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17536 SmallVector<SDValue, 32> V(NumElts,
17537 DAG.getConstant(128 >> ShiftAmt, dl,
17539 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17540 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17541 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17544 llvm_unreachable("Unknown shift opcode.");
17549 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17550 if (!Subtarget->is64Bit() &&
17551 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17553 // Peek through any splat that was introduced for i64 shift vectorization.
17554 int SplatIndex = -1;
17555 if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17556 if (SVN->isSplat()) {
17557 SplatIndex = SVN->getSplatIndex();
17558 Amt = Amt.getOperand(0);
17559 assert(SplatIndex < (int)VT.getVectorNumElements() &&
17560 "Splat shuffle referencing second operand");
17563 if (Amt.getOpcode() != ISD::BITCAST ||
17564 Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17567 Amt = Amt.getOperand(0);
17568 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17569 VT.getVectorNumElements();
17570 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17571 uint64_t ShiftAmt = 0;
17572 unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17573 for (unsigned i = 0; i != Ratio; ++i) {
17574 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17578 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17581 // Check remaining shift amounts (if not a splat).
17582 if (SplatIndex < 0) {
17583 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17584 uint64_t ShAmt = 0;
17585 for (unsigned j = 0; j != Ratio; ++j) {
17586 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17590 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17592 if (ShAmt != ShiftAmt)
17597 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17598 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17600 if (Op.getOpcode() == ISD::SRA)
17601 return ArithmeticShiftRight64(ShiftAmt);
17607 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17608 const X86Subtarget* Subtarget) {
17609 MVT VT = Op.getSimpleValueType();
17611 SDValue R = Op.getOperand(0);
17612 SDValue Amt = Op.getOperand(1);
17614 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17615 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17617 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17618 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17620 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17622 EVT EltVT = VT.getVectorElementType();
17624 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17625 // Check if this build_vector node is doing a splat.
17626 // If so, then set BaseShAmt equal to the splat value.
17627 BaseShAmt = BV->getSplatValue();
17628 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17629 BaseShAmt = SDValue();
17631 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17632 Amt = Amt.getOperand(0);
17634 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17635 if (SVN && SVN->isSplat()) {
17636 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17637 SDValue InVec = Amt.getOperand(0);
17638 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17639 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17640 "Unexpected shuffle index found!");
17641 BaseShAmt = InVec.getOperand(SplatIdx);
17642 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17643 if (ConstantSDNode *C =
17644 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17645 if (C->getZExtValue() == SplatIdx)
17646 BaseShAmt = InVec.getOperand(1);
17651 // Avoid introducing an extract element from a shuffle.
17652 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17653 DAG.getIntPtrConstant(SplatIdx, dl));
17657 if (BaseShAmt.getNode()) {
17658 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17659 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17660 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17661 else if (EltVT.bitsLT(MVT::i32))
17662 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17664 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17668 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17669 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
17670 Amt.getOpcode() == ISD::BITCAST &&
17671 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17672 Amt = Amt.getOperand(0);
17673 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17674 VT.getVectorNumElements();
17675 std::vector<SDValue> Vals(Ratio);
17676 for (unsigned i = 0; i != Ratio; ++i)
17677 Vals[i] = Amt.getOperand(i);
17678 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17679 for (unsigned j = 0; j != Ratio; ++j)
17680 if (Vals[j] != Amt.getOperand(i + j))
17684 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17685 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17690 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17691 SelectionDAG &DAG) {
17692 MVT VT = Op.getSimpleValueType();
17694 SDValue R = Op.getOperand(0);
17695 SDValue Amt = Op.getOperand(1);
17697 assert(VT.isVector() && "Custom lowering only for vector shifts!");
17698 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17700 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17703 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17706 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17709 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17710 // shifts per-lane and then shuffle the partial results back together.
17711 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17712 // Splat the shift amounts so the scalar shifts above will catch it.
17713 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17714 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17715 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17716 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17717 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17720 // i64 vector arithmetic shift can be emulated with the transform:
17721 // M = lshr(SIGN_BIT, Amt)
17722 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17723 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17724 Op.getOpcode() == ISD::SRA) {
17725 SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17726 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17727 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17728 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17729 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17733 // If possible, lower this packed shift into a vector multiply instead of
17734 // expanding it into a sequence of scalar shifts.
17735 // Do this only if the vector shift count is a constant build_vector.
17736 if (Op.getOpcode() == ISD::SHL &&
17737 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17738 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17739 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17740 SmallVector<SDValue, 8> Elts;
17741 EVT SVT = VT.getScalarType();
17742 unsigned SVTBits = SVT.getSizeInBits();
17743 const APInt &One = APInt(SVTBits, 1);
17744 unsigned NumElems = VT.getVectorNumElements();
17746 for (unsigned i=0; i !=NumElems; ++i) {
17747 SDValue Op = Amt->getOperand(i);
17748 if (Op->getOpcode() == ISD::UNDEF) {
17749 Elts.push_back(Op);
17753 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17754 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17755 uint64_t ShAmt = C.getZExtValue();
17756 if (ShAmt >= SVTBits) {
17757 Elts.push_back(DAG.getUNDEF(SVT));
17760 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17762 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17763 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17766 // Lower SHL with variable shift amount.
17767 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17768 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17770 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17771 DAG.getConstant(0x3f800000U, dl, VT));
17772 Op = DAG.getBitcast(MVT::v4f32, Op);
17773 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17774 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17777 // If possible, lower this shift as a sequence of two shifts by
17778 // constant plus a MOVSS/MOVSD instead of scalarizing it.
17780 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17782 // Could be rewritten as:
17783 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17785 // The advantage is that the two shifts from the example would be
17786 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17787 // the vector shift into four scalar shifts plus four pairs of vector
17789 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17790 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17791 unsigned TargetOpcode = X86ISD::MOVSS;
17792 bool CanBeSimplified;
17793 // The splat value for the first packed shift (the 'X' from the example).
17794 SDValue Amt1 = Amt->getOperand(0);
17795 // The splat value for the second packed shift (the 'Y' from the example).
17796 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17797 Amt->getOperand(2);
17799 // See if it is possible to replace this node with a sequence of
17800 // two shifts followed by a MOVSS/MOVSD
17801 if (VT == MVT::v4i32) {
17802 // Check if it is legal to use a MOVSS.
17803 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17804 Amt2 == Amt->getOperand(3);
17805 if (!CanBeSimplified) {
17806 // Otherwise, check if we can still simplify this node using a MOVSD.
17807 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17808 Amt->getOperand(2) == Amt->getOperand(3);
17809 TargetOpcode = X86ISD::MOVSD;
17810 Amt2 = Amt->getOperand(2);
17813 // Do similar checks for the case where the machine value type
17815 CanBeSimplified = Amt1 == Amt->getOperand(1);
17816 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17817 CanBeSimplified = Amt2 == Amt->getOperand(i);
17819 if (!CanBeSimplified) {
17820 TargetOpcode = X86ISD::MOVSD;
17821 CanBeSimplified = true;
17822 Amt2 = Amt->getOperand(4);
17823 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17824 CanBeSimplified = Amt1 == Amt->getOperand(i);
17825 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17826 CanBeSimplified = Amt2 == Amt->getOperand(j);
17830 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17831 isa<ConstantSDNode>(Amt2)) {
17832 // Replace this node with two shifts followed by a MOVSS/MOVSD.
17833 EVT CastVT = MVT::v4i32;
17835 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17836 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17838 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17839 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17840 if (TargetOpcode == X86ISD::MOVSD)
17841 CastVT = MVT::v2i64;
17842 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17843 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17844 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17846 return DAG.getBitcast(VT, Result);
17850 // v4i32 Non Uniform Shifts.
17851 // If the shift amount is constant we can shift each lane using the SSE2
17852 // immediate shifts, else we need to zero-extend each lane to the lower i64
17853 // and shift using the SSE2 variable shifts.
17854 // The separate results can then be blended together.
17855 if (VT == MVT::v4i32) {
17856 unsigned Opc = Op.getOpcode();
17857 SDValue Amt0, Amt1, Amt2, Amt3;
17858 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17859 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17860 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17861 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17862 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17864 // ISD::SHL is handled above but we include it here for completeness.
17867 llvm_unreachable("Unknown target vector shift node");
17869 Opc = X86ISD::VSHL;
17872 Opc = X86ISD::VSRL;
17875 Opc = X86ISD::VSRA;
17878 // The SSE2 shifts use the lower i64 as the same shift amount for
17879 // all lanes and the upper i64 is ignored. These shuffle masks
17880 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17881 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17882 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17883 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17884 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17885 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17888 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17889 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17890 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17891 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17892 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17893 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17894 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17897 if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17898 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17899 unsigned ShiftOpcode = Op->getOpcode();
17901 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17902 // On SSE41 targets we make use of the fact that VSELECT lowers
17903 // to PBLENDVB which selects bytes based just on the sign bit.
17904 if (Subtarget->hasSSE41()) {
17905 V0 = DAG.getBitcast(VT, V0);
17906 V1 = DAG.getBitcast(VT, V1);
17907 Sel = DAG.getBitcast(VT, Sel);
17908 return DAG.getBitcast(SelVT,
17909 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17911 // On pre-SSE41 targets we test for the sign bit by comparing to
17912 // zero - a negative value will set all bits of the lanes to true
17913 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17914 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17915 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17916 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17919 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17920 // We can safely do this using i16 shifts as we're only interested in
17921 // the 3 lower bits of each byte.
17922 Amt = DAG.getBitcast(ExtVT, Amt);
17923 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17924 Amt = DAG.getBitcast(VT, Amt);
17926 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17927 // r = VSELECT(r, shift(r, 4), a);
17929 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17930 R = SignBitSelect(VT, Amt, M, R);
17933 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17935 // r = VSELECT(r, shift(r, 2), a);
17936 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17937 R = SignBitSelect(VT, Amt, M, R);
17940 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17942 // return VSELECT(r, shift(r, 1), a);
17943 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17944 R = SignBitSelect(VT, Amt, M, R);
17948 if (Op->getOpcode() == ISD::SRA) {
17949 // For SRA we need to unpack each byte to the higher byte of a i16 vector
17950 // so we can correctly sign extend. We don't care what happens to the
17952 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17953 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17954 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17955 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17956 ALo = DAG.getBitcast(ExtVT, ALo);
17957 AHi = DAG.getBitcast(ExtVT, AHi);
17958 RLo = DAG.getBitcast(ExtVT, RLo);
17959 RHi = DAG.getBitcast(ExtVT, RHi);
17961 // r = VSELECT(r, shift(r, 4), a);
17962 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17963 DAG.getConstant(4, dl, ExtVT));
17964 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17965 DAG.getConstant(4, dl, ExtVT));
17966 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17967 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17970 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17971 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17973 // r = VSELECT(r, shift(r, 2), a);
17974 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17975 DAG.getConstant(2, dl, ExtVT));
17976 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17977 DAG.getConstant(2, dl, ExtVT));
17978 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17979 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17982 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17983 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17985 // r = VSELECT(r, shift(r, 1), a);
17986 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17987 DAG.getConstant(1, dl, ExtVT));
17988 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17989 DAG.getConstant(1, dl, ExtVT));
17990 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17991 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17993 // Logical shift the result back to the lower byte, leaving a zero upper
17995 // meaning that we can safely pack with PACKUSWB.
17997 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17999 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18000 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18004 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18005 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18006 // solution better.
18007 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18008 MVT ExtVT = MVT::v8i32;
18010 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18011 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18012 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18013 return DAG.getNode(ISD::TRUNCATE, dl, VT,
18014 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18017 if (Subtarget->hasInt256() && VT == MVT::v16i16) {
18018 MVT ExtVT = MVT::v8i32;
18019 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18020 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18021 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18022 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18023 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18024 ALo = DAG.getBitcast(ExtVT, ALo);
18025 AHi = DAG.getBitcast(ExtVT, AHi);
18026 RLo = DAG.getBitcast(ExtVT, RLo);
18027 RHi = DAG.getBitcast(ExtVT, RHi);
18028 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18029 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18030 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18031 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18032 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18035 if (VT == MVT::v8i16) {
18036 unsigned ShiftOpcode = Op->getOpcode();
18038 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18039 // On SSE41 targets we make use of the fact that VSELECT lowers
18040 // to PBLENDVB which selects bytes based just on the sign bit.
18041 if (Subtarget->hasSSE41()) {
18042 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18043 V0 = DAG.getBitcast(ExtVT, V0);
18044 V1 = DAG.getBitcast(ExtVT, V1);
18045 Sel = DAG.getBitcast(ExtVT, Sel);
18046 return DAG.getBitcast(
18047 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18049 // On pre-SSE41 targets we splat the sign bit - a negative value will
18050 // set all bits of the lanes to true and VSELECT uses that in
18051 // its OR(AND(V0,C),AND(V1,~C)) lowering.
18053 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18054 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18057 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18058 if (Subtarget->hasSSE41()) {
18059 // On SSE41 targets we need to replicate the shift mask in both
18060 // bytes for PBLENDVB.
18063 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18064 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18066 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18069 // r = VSELECT(r, shift(r, 8), a);
18070 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18071 R = SignBitSelect(Amt, M, R);
18074 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18076 // r = VSELECT(r, shift(r, 4), a);
18077 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18078 R = SignBitSelect(Amt, M, R);
18081 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18083 // r = VSELECT(r, shift(r, 2), a);
18084 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18085 R = SignBitSelect(Amt, M, R);
18088 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18090 // return VSELECT(r, shift(r, 1), a);
18091 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18092 R = SignBitSelect(Amt, M, R);
18096 // Decompose 256-bit shifts into smaller 128-bit shifts.
18097 if (VT.is256BitVector()) {
18098 unsigned NumElems = VT.getVectorNumElements();
18099 MVT EltVT = VT.getVectorElementType();
18100 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18102 // Extract the two vectors
18103 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18104 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18106 // Recreate the shift amount vectors
18107 SDValue Amt1, Amt2;
18108 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18109 // Constant shift amount
18110 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18111 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18112 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18114 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18115 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18117 // Variable shift amount
18118 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18119 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
18122 // Issue new vector shifts for the smaller types
18123 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
18124 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
18126 // Concatenate the result back
18127 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
18133 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
18134 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
18135 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
18136 // looks for this combo and may remove the "setcc" instruction if the "setcc"
18137 // has only one use.
18138 SDNode *N = Op.getNode();
18139 SDValue LHS = N->getOperand(0);
18140 SDValue RHS = N->getOperand(1);
18141 unsigned BaseOp = 0;
18144 switch (Op.getOpcode()) {
18145 default: llvm_unreachable("Unknown ovf instruction!");
18147 // A subtract of one will be selected as a INC. Note that INC doesn't
18148 // set CF, so we can't do this for UADDO.
18149 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18151 BaseOp = X86ISD::INC;
18152 Cond = X86::COND_O;
18155 BaseOp = X86ISD::ADD;
18156 Cond = X86::COND_O;
18159 BaseOp = X86ISD::ADD;
18160 Cond = X86::COND_B;
18163 // A subtract of one will be selected as a DEC. Note that DEC doesn't
18164 // set CF, so we can't do this for USUBO.
18165 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
18167 BaseOp = X86ISD::DEC;
18168 Cond = X86::COND_O;
18171 BaseOp = X86ISD::SUB;
18172 Cond = X86::COND_O;
18175 BaseOp = X86ISD::SUB;
18176 Cond = X86::COND_B;
18179 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
18180 Cond = X86::COND_O;
18182 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
18183 if (N->getValueType(0) == MVT::i8) {
18184 BaseOp = X86ISD::UMUL8;
18185 Cond = X86::COND_O;
18188 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
18190 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
18193 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18194 DAG.getConstant(X86::COND_O, DL, MVT::i32),
18195 SDValue(Sum.getNode(), 2));
18197 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18201 // Also sets EFLAGS.
18202 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
18203 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
18206 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
18207 DAG.getConstant(Cond, DL, MVT::i32),
18208 SDValue(Sum.getNode(), 1));
18210 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
18213 /// Returns true if the operand type is exactly twice the native width, and
18214 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
18215 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
18216 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
18217 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
18218 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
18221 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
18222 else if (OpWidth == 128)
18223 return Subtarget->hasCmpxchg16b();
18228 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18229 return needsCmpXchgNb(SI->getValueOperand()->getType());
18232 // Note: this turns large loads into lock cmpxchg8b/16b.
18233 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
18234 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18235 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
18236 return needsCmpXchgNb(PTy->getElementType());
18239 TargetLoweringBase::AtomicRMWExpansionKind
18240 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18241 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18242 Type *MemType = AI->getType();
18244 // If the operand is too big, we must see if cmpxchg8/16b is available
18245 // and default to library calls otherwise.
18246 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18247 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
18248 : AtomicRMWExpansionKind::None;
18251 AtomicRMWInst::BinOp Op = AI->getOperation();
18254 llvm_unreachable("Unknown atomic operation");
18255 case AtomicRMWInst::Xchg:
18256 case AtomicRMWInst::Add:
18257 case AtomicRMWInst::Sub:
18258 // It's better to use xadd, xsub or xchg for these in all cases.
18259 return AtomicRMWExpansionKind::None;
18260 case AtomicRMWInst::Or:
18261 case AtomicRMWInst::And:
18262 case AtomicRMWInst::Xor:
18263 // If the atomicrmw's result isn't actually used, we can just add a "lock"
18264 // prefix to a normal instruction for these operations.
18265 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
18266 : AtomicRMWExpansionKind::None;
18267 case AtomicRMWInst::Nand:
18268 case AtomicRMWInst::Max:
18269 case AtomicRMWInst::Min:
18270 case AtomicRMWInst::UMax:
18271 case AtomicRMWInst::UMin:
18272 // These always require a non-trivial set of data operations on x86. We must
18273 // use a cmpxchg loop.
18274 return AtomicRMWExpansionKind::CmpXChg;
18278 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18279 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18280 // no-sse2). There isn't any reason to disable it if the target processor
18282 return Subtarget.hasSSE2() || Subtarget.is64Bit();
18286 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18287 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18288 Type *MemType = AI->getType();
18289 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18290 // there is no benefit in turning such RMWs into loads, and it is actually
18291 // harmful as it introduces a mfence.
18292 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18295 auto Builder = IRBuilder<>(AI);
18296 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18297 auto SynchScope = AI->getSynchScope();
18298 // We must restrict the ordering to avoid generating loads with Release or
18299 // ReleaseAcquire orderings.
18300 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18301 auto Ptr = AI->getPointerOperand();
18303 // Before the load we need a fence. Here is an example lifted from
18304 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18307 // x.store(1, relaxed);
18308 // r1 = y.fetch_add(0, release);
18310 // y.fetch_add(42, acquire);
18311 // r2 = x.load(relaxed);
18312 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18313 // lowered to just a load without a fence. A mfence flushes the store buffer,
18314 // making the optimization clearly correct.
18315 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18316 // otherwise, we might be able to be more aggressive on relaxed idempotent
18317 // rmw. In practice, they do not look useful, so we don't try to be
18318 // especially clever.
18319 if (SynchScope == SingleThread)
18320 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18321 // the IR level, so we must wrap it in an intrinsic.
18324 if (!hasMFENCE(*Subtarget))
18325 // FIXME: it might make sense to use a locked operation here but on a
18326 // different cache-line to prevent cache-line bouncing. In practice it
18327 // is probably a small win, and x86 processors without mfence are rare
18328 // enough that we do not bother.
18332 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18333 Builder.CreateCall(MFence, {});
18335 // Finally we can emit the atomic load.
18336 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18337 AI->getType()->getPrimitiveSizeInBits());
18338 Loaded->setAtomic(Order, SynchScope);
18339 AI->replaceAllUsesWith(Loaded);
18340 AI->eraseFromParent();
18344 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18345 SelectionDAG &DAG) {
18347 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18348 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18349 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18350 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18352 // The only fence that needs an instruction is a sequentially-consistent
18353 // cross-thread fence.
18354 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18355 if (hasMFENCE(*Subtarget))
18356 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18358 SDValue Chain = Op.getOperand(0);
18359 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18361 DAG.getRegister(X86::ESP, MVT::i32), // Base
18362 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
18363 DAG.getRegister(0, MVT::i32), // Index
18364 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
18365 DAG.getRegister(0, MVT::i32), // Segment.
18369 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18370 return SDValue(Res, 0);
18373 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18374 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18377 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18378 SelectionDAG &DAG) {
18379 MVT T = Op.getSimpleValueType();
18383 switch(T.SimpleTy) {
18384 default: llvm_unreachable("Invalid value type!");
18385 case MVT::i8: Reg = X86::AL; size = 1; break;
18386 case MVT::i16: Reg = X86::AX; size = 2; break;
18387 case MVT::i32: Reg = X86::EAX; size = 4; break;
18389 assert(Subtarget->is64Bit() && "Node not type legal!");
18390 Reg = X86::RAX; size = 8;
18393 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18394 Op.getOperand(2), SDValue());
18395 SDValue Ops[] = { cpIn.getValue(0),
18398 DAG.getTargetConstant(size, DL, MVT::i8),
18399 cpIn.getValue(1) };
18400 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18401 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18402 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18406 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18407 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18408 MVT::i32, cpOut.getValue(2));
18409 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18410 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18413 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18414 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18415 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18419 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18420 SelectionDAG &DAG) {
18421 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18422 MVT DstVT = Op.getSimpleValueType();
18424 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18425 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18426 if (DstVT != MVT::f64)
18427 // This conversion needs to be expanded.
18430 SDValue InVec = Op->getOperand(0);
18432 unsigned NumElts = SrcVT.getVectorNumElements();
18433 EVT SVT = SrcVT.getVectorElementType();
18435 // Widen the vector in input in the case of MVT::v2i32.
18436 // Example: from MVT::v2i32 to MVT::v4i32.
18437 SmallVector<SDValue, 16> Elts;
18438 for (unsigned i = 0, e = NumElts; i != e; ++i)
18439 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18440 DAG.getIntPtrConstant(i, dl)));
18442 // Explicitly mark the extra elements as Undef.
18443 Elts.append(NumElts, DAG.getUNDEF(SVT));
18445 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18446 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18447 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18448 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18449 DAG.getIntPtrConstant(0, dl));
18452 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18453 Subtarget->hasMMX() && "Unexpected custom BITCAST");
18454 assert((DstVT == MVT::i64 ||
18455 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18456 "Unexpected custom BITCAST");
18457 // i64 <=> MMX conversions are Legal.
18458 if (SrcVT==MVT::i64 && DstVT.isVector())
18460 if (DstVT==MVT::i64 && SrcVT.isVector())
18462 // MMX <=> MMX conversions are Legal.
18463 if (SrcVT.isVector() && DstVT.isVector())
18465 // All other conversions need to be expanded.
18469 /// Compute the horizontal sum of bytes in V for the elements of VT.
18471 /// Requires V to be a byte vector and VT to be an integer vector type with
18472 /// wider elements than V's type. The width of the elements of VT determines
18473 /// how many bytes of V are summed horizontally to produce each element of the
18475 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18476 const X86Subtarget *Subtarget,
18477 SelectionDAG &DAG) {
18479 MVT ByteVecVT = V.getSimpleValueType();
18480 MVT EltVT = VT.getVectorElementType();
18481 int NumElts = VT.getVectorNumElements();
18482 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18483 "Expected value to have byte element type.");
18484 assert(EltVT != MVT::i8 &&
18485 "Horizontal byte sum only makes sense for wider elements!");
18486 unsigned VecSize = VT.getSizeInBits();
18487 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18489 // PSADBW instruction horizontally add all bytes and leave the result in i64
18490 // chunks, thus directly computes the pop count for v2i64 and v4i64.
18491 if (EltVT == MVT::i64) {
18492 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18493 V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18494 return DAG.getBitcast(VT, V);
18497 if (EltVT == MVT::i32) {
18498 // We unpack the low half and high half into i32s interleaved with zeros so
18499 // that we can use PSADBW to horizontally sum them. The most useful part of
18500 // this is that it lines up the results of two PSADBW instructions to be
18501 // two v2i64 vectors which concatenated are the 4 population counts. We can
18502 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18503 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18504 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18505 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18507 // Do the horizontal sums into two v2i64s.
18508 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18509 Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18510 DAG.getBitcast(ByteVecVT, Low), Zeros);
18511 High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18512 DAG.getBitcast(ByteVecVT, High), Zeros);
18514 // Merge them together.
18515 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18516 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18517 DAG.getBitcast(ShortVecVT, Low),
18518 DAG.getBitcast(ShortVecVT, High));
18520 return DAG.getBitcast(VT, V);
18523 // The only element type left is i16.
18524 assert(EltVT == MVT::i16 && "Unknown how to handle type");
18526 // To obtain pop count for each i16 element starting from the pop count for
18527 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18528 // right by 8. It is important to shift as i16s as i8 vector shift isn't
18529 // directly supported.
18530 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18531 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18532 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18533 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18534 DAG.getBitcast(ByteVecVT, V));
18535 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18538 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18539 const X86Subtarget *Subtarget,
18540 SelectionDAG &DAG) {
18541 MVT VT = Op.getSimpleValueType();
18542 MVT EltVT = VT.getVectorElementType();
18543 unsigned VecSize = VT.getSizeInBits();
18545 // Implement a lookup table in register by using an algorithm based on:
18546 // http://wm.ite.pl/articles/sse-popcount.html
18548 // The general idea is that every lower byte nibble in the input vector is an
18549 // index into a in-register pre-computed pop count table. We then split up the
18550 // input vector in two new ones: (1) a vector with only the shifted-right
18551 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18552 // masked out higher ones) for each byte. PSHUB is used separately with both
18553 // to index the in-register table. Next, both are added and the result is a
18554 // i8 vector where each element contains the pop count for input byte.
18556 // To obtain the pop count for elements != i8, we follow up with the same
18557 // approach and use additional tricks as described below.
18559 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18560 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18561 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18562 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18564 int NumByteElts = VecSize / 8;
18565 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18566 SDValue In = DAG.getBitcast(ByteVecVT, Op);
18567 SmallVector<SDValue, 16> LUTVec;
18568 for (int i = 0; i < NumByteElts; ++i)
18569 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18570 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18571 SmallVector<SDValue, 16> Mask0F(NumByteElts,
18572 DAG.getConstant(0x0F, DL, MVT::i8));
18573 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18576 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18577 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18578 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18581 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18583 // The input vector is used as the shuffle mask that index elements into the
18584 // LUT. After counting low and high nibbles, add the vector to obtain the
18585 // final pop count per i8 element.
18586 SDValue HighPopCnt =
18587 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18588 SDValue LowPopCnt =
18589 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18590 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18592 if (EltVT == MVT::i8)
18595 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18598 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18599 const X86Subtarget *Subtarget,
18600 SelectionDAG &DAG) {
18601 MVT VT = Op.getSimpleValueType();
18602 assert(VT.is128BitVector() &&
18603 "Only 128-bit vector bitmath lowering supported.");
18605 int VecSize = VT.getSizeInBits();
18606 MVT EltVT = VT.getVectorElementType();
18607 int Len = EltVT.getSizeInBits();
18609 // This is the vectorized version of the "best" algorithm from
18610 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18611 // with a minor tweak to use a series of adds + shifts instead of vector
18612 // multiplications. Implemented for all integer vector types. We only use
18613 // this when we don't have SSSE3 which allows a LUT-based lowering that is
18614 // much faster, even faster than using native popcnt instructions.
18616 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18617 MVT VT = V.getSimpleValueType();
18618 SmallVector<SDValue, 32> Shifters(
18619 VT.getVectorNumElements(),
18620 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18621 return DAG.getNode(OpCode, DL, VT, V,
18622 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18624 auto GetMask = [&](SDValue V, APInt Mask) {
18625 MVT VT = V.getSimpleValueType();
18626 SmallVector<SDValue, 32> Masks(
18627 VT.getVectorNumElements(),
18628 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18629 return DAG.getNode(ISD::AND, DL, VT, V,
18630 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18633 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18634 // x86, so set the SRL type to have elements at least i16 wide. This is
18635 // correct because all of our SRLs are followed immediately by a mask anyways
18636 // that handles any bits that sneak into the high bits of the byte elements.
18637 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18641 // v = v - ((v >> 1) & 0x55555555...)
18643 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18644 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18645 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18647 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18648 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18649 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18650 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18651 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18653 // v = (v + (v >> 4)) & 0x0F0F0F0F...
18654 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18655 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18656 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18658 // At this point, V contains the byte-wise population count, and we are
18659 // merely doing a horizontal sum if necessary to get the wider element
18661 if (EltVT == MVT::i8)
18664 return LowerHorizontalByteSum(
18665 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18669 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18670 SelectionDAG &DAG) {
18671 MVT VT = Op.getSimpleValueType();
18672 // FIXME: Need to add AVX-512 support here!
18673 assert((VT.is256BitVector() || VT.is128BitVector()) &&
18674 "Unknown CTPOP type to handle");
18675 SDLoc DL(Op.getNode());
18676 SDValue Op0 = Op.getOperand(0);
18678 if (!Subtarget->hasSSSE3()) {
18679 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18680 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18681 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18684 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18685 unsigned NumElems = VT.getVectorNumElements();
18687 // Extract each 128-bit vector, compute pop count and concat the result.
18688 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18689 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18691 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18692 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18693 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18696 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18699 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18700 SelectionDAG &DAG) {
18701 assert(Op.getValueType().isVector() &&
18702 "We only do custom lowering for vector population count.");
18703 return LowerVectorCTPOP(Op, Subtarget, DAG);
18706 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18707 SDNode *Node = Op.getNode();
18709 EVT T = Node->getValueType(0);
18710 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18711 DAG.getConstant(0, dl, T), Node->getOperand(2));
18712 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18713 cast<AtomicSDNode>(Node)->getMemoryVT(),
18714 Node->getOperand(0),
18715 Node->getOperand(1), negOp,
18716 cast<AtomicSDNode>(Node)->getMemOperand(),
18717 cast<AtomicSDNode>(Node)->getOrdering(),
18718 cast<AtomicSDNode>(Node)->getSynchScope());
18721 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18722 SDNode *Node = Op.getNode();
18724 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18726 // Convert seq_cst store -> xchg
18727 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18728 // FIXME: On 32-bit, store -> fist or movq would be more efficient
18729 // (The only way to get a 16-byte store is cmpxchg16b)
18730 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18731 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18732 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18733 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18734 cast<AtomicSDNode>(Node)->getMemoryVT(),
18735 Node->getOperand(0),
18736 Node->getOperand(1), Node->getOperand(2),
18737 cast<AtomicSDNode>(Node)->getMemOperand(),
18738 cast<AtomicSDNode>(Node)->getOrdering(),
18739 cast<AtomicSDNode>(Node)->getSynchScope());
18740 return Swap.getValue(1);
18742 // Other atomic stores have a simple pattern.
18746 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18747 EVT VT = Op.getNode()->getSimpleValueType(0);
18749 // Let legalize expand this if it isn't a legal type yet.
18750 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18753 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18756 bool ExtraOp = false;
18757 switch (Op.getOpcode()) {
18758 default: llvm_unreachable("Invalid code");
18759 case ISD::ADDC: Opc = X86ISD::ADD; break;
18760 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18761 case ISD::SUBC: Opc = X86ISD::SUB; break;
18762 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18766 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18768 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18769 Op.getOperand(1), Op.getOperand(2));
18772 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18773 SelectionDAG &DAG) {
18774 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18776 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18777 // which returns the values as { float, float } (in XMM0) or
18778 // { double, double } (which is returned in XMM0, XMM1).
18780 SDValue Arg = Op.getOperand(0);
18781 EVT ArgVT = Arg.getValueType();
18782 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18784 TargetLowering::ArgListTy Args;
18785 TargetLowering::ArgListEntry Entry;
18789 Entry.isSExt = false;
18790 Entry.isZExt = false;
18791 Args.push_back(Entry);
18793 bool isF64 = ArgVT == MVT::f64;
18794 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18795 // the small struct {f32, f32} is returned in (eax, edx). For f64,
18796 // the results are returned via SRet in memory.
18797 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
18798 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18800 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18802 Type *RetTy = isF64
18803 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18804 : (Type*)VectorType::get(ArgTy, 4);
18806 TargetLowering::CallLoweringInfo CLI(DAG);
18807 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18808 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18810 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18813 // Returned in xmm0 and xmm1.
18814 return CallResult.first;
18816 // Returned in bits 0:31 and 32:64 xmm0.
18817 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18818 CallResult.first, DAG.getIntPtrConstant(0, dl));
18819 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18820 CallResult.first, DAG.getIntPtrConstant(1, dl));
18821 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18822 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18825 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18826 SelectionDAG &DAG) {
18827 assert(Subtarget->hasAVX512() &&
18828 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18830 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18831 EVT VT = N->getValue().getValueType();
18832 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18835 // X86 scatter kills mask register, so its type should be added to
18836 // the list of return values
18837 if (N->getNumValues() == 1) {
18838 SDValue Index = N->getIndex();
18839 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18840 !Index.getValueType().is512BitVector())
18841 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18843 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18844 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18845 N->getOperand(3), Index };
18847 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18848 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18849 return SDValue(NewScatter.getNode(), 0);
18854 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18855 SelectionDAG &DAG) {
18856 assert(Subtarget->hasAVX512() &&
18857 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18859 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18860 EVT VT = Op.getValueType();
18861 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18864 SDValue Index = N->getIndex();
18865 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18866 !Index.getValueType().is512BitVector()) {
18867 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18868 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18869 N->getOperand(3), Index };
18870 DAG.UpdateNodeOperands(N, Ops);
18875 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18876 SelectionDAG &DAG) const {
18877 // TODO: Eventually, the lowering of these nodes should be informed by or
18878 // deferred to the GC strategy for the function in which they appear. For
18879 // now, however, they must be lowered to something. Since they are logically
18880 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18881 // require special handling for these nodes), lower them as literal NOOPs for
18883 SmallVector<SDValue, 2> Ops;
18885 Ops.push_back(Op.getOperand(0));
18886 if (Op->getGluedNode())
18887 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18890 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18891 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18896 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18897 SelectionDAG &DAG) const {
18898 // TODO: Eventually, the lowering of these nodes should be informed by or
18899 // deferred to the GC strategy for the function in which they appear. For
18900 // now, however, they must be lowered to something. Since they are logically
18901 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18902 // require special handling for these nodes), lower them as literal NOOPs for
18904 SmallVector<SDValue, 2> Ops;
18906 Ops.push_back(Op.getOperand(0));
18907 if (Op->getGluedNode())
18908 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18911 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18912 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18917 /// LowerOperation - Provide custom lowering hooks for some operations.
18919 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18920 switch (Op.getOpcode()) {
18921 default: llvm_unreachable("Should not custom lower this!");
18922 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18923 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18924 return LowerCMP_SWAP(Op, Subtarget, DAG);
18925 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
18926 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
18927 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
18928 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
18929 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18930 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
18931 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
18932 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18933 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
18934 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18935 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18936 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
18937 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
18938 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
18939 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
18940 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
18941 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
18942 case ISD::SHL_PARTS:
18943 case ISD::SRA_PARTS:
18944 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
18945 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
18946 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
18947 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
18948 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
18949 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18950 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
18951 case ISD::SIGN_EXTEND_VECTOR_INREG:
18952 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18953 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
18954 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
18955 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
18956 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
18958 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
18959 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
18960 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
18961 case ISD::SETCC: return LowerSETCC(Op, DAG);
18962 case ISD::SELECT: return LowerSELECT(Op, DAG);
18963 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
18964 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
18965 case ISD::VASTART: return LowerVASTART(Op, DAG);
18966 case ISD::VAARG: return LowerVAARG(Op, DAG);
18967 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
18968 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18969 case ISD::INTRINSIC_VOID:
18970 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18971 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
18972 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
18973 case ISD::FRAME_TO_ARGS_OFFSET:
18974 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18975 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18976 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
18977 case ISD::CATCHRET: return LowerCATCHRET(Op, DAG);
18978 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
18979 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
18980 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
18981 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
18982 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
18983 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
18984 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18985 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
18986 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
18987 case ISD::UMUL_LOHI:
18988 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
18991 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
18997 case ISD::UMULO: return LowerXALUO(Op, DAG);
18998 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18999 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
19003 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
19004 case ISD::ADD: return LowerADD(Op, DAG);
19005 case ISD::SUB: return LowerSUB(Op, DAG);
19009 case ISD::UMIN: return LowerMINMAX(Op, DAG);
19010 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
19011 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
19012 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
19013 case ISD::GC_TRANSITION_START:
19014 return LowerGC_TRANSITION_START(Op, DAG);
19015 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
19019 /// ReplaceNodeResults - Replace a node with an illegal result type
19020 /// with a new node built out of custom code.
19021 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
19022 SmallVectorImpl<SDValue>&Results,
19023 SelectionDAG &DAG) const {
19025 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19026 switch (N->getOpcode()) {
19028 llvm_unreachable("Do not know how to custom type legalize this operation!");
19029 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
19030 case X86ISD::FMINC:
19032 case X86ISD::FMAXC:
19033 case X86ISD::FMAX: {
19034 EVT VT = N->getValueType(0);
19035 if (VT != MVT::v2f32)
19036 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
19037 SDValue UNDEF = DAG.getUNDEF(VT);
19038 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19039 N->getOperand(0), UNDEF);
19040 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
19041 N->getOperand(1), UNDEF);
19042 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
19045 case ISD::SIGN_EXTEND_INREG:
19050 // We don't want to expand or promote these.
19057 case ISD::UDIVREM: {
19058 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
19059 Results.push_back(V);
19062 case ISD::FP_TO_SINT:
19063 case ISD::FP_TO_UINT: {
19064 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
19066 std::pair<SDValue,SDValue> Vals =
19067 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
19068 SDValue FIST = Vals.first, StackSlot = Vals.second;
19069 if (FIST.getNode()) {
19070 EVT VT = N->getValueType(0);
19071 // Return a load from the stack slot.
19072 if (StackSlot.getNode())
19073 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
19074 MachinePointerInfo(),
19075 false, false, false, 0));
19077 Results.push_back(FIST);
19081 case ISD::UINT_TO_FP: {
19082 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19083 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
19084 N->getValueType(0) != MVT::v2f32)
19086 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
19088 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19090 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
19091 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
19092 DAG.getBitcast(MVT::v2i64, VBias));
19093 Or = DAG.getBitcast(MVT::v2f64, Or);
19094 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
19095 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
19098 case ISD::FP_ROUND: {
19099 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
19101 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
19102 Results.push_back(V);
19105 case ISD::FP_EXTEND: {
19106 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
19107 // No other ValueType for FP_EXTEND should reach this point.
19108 assert(N->getValueType(0) == MVT::v2f32 &&
19109 "Do not know how to legalize this Node");
19112 case ISD::INTRINSIC_W_CHAIN: {
19113 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
19115 default : llvm_unreachable("Do not know how to custom type "
19116 "legalize this intrinsic operation!");
19117 case Intrinsic::x86_rdtsc:
19118 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19120 case Intrinsic::x86_rdtscp:
19121 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
19123 case Intrinsic::x86_rdpmc:
19124 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
19127 case ISD::READCYCLECOUNTER: {
19128 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
19131 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
19132 EVT T = N->getValueType(0);
19133 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
19134 bool Regs64bit = T == MVT::i128;
19135 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
19136 SDValue cpInL, cpInH;
19137 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19138 DAG.getConstant(0, dl, HalfT));
19139 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
19140 DAG.getConstant(1, dl, HalfT));
19141 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
19142 Regs64bit ? X86::RAX : X86::EAX,
19144 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
19145 Regs64bit ? X86::RDX : X86::EDX,
19146 cpInH, cpInL.getValue(1));
19147 SDValue swapInL, swapInH;
19148 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19149 DAG.getConstant(0, dl, HalfT));
19150 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
19151 DAG.getConstant(1, dl, HalfT));
19152 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
19153 Regs64bit ? X86::RBX : X86::EBX,
19154 swapInL, cpInH.getValue(1));
19155 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
19156 Regs64bit ? X86::RCX : X86::ECX,
19157 swapInH, swapInL.getValue(1));
19158 SDValue Ops[] = { swapInH.getValue(0),
19160 swapInH.getValue(1) };
19161 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19162 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
19163 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
19164 X86ISD::LCMPXCHG8_DAG;
19165 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
19166 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
19167 Regs64bit ? X86::RAX : X86::EAX,
19168 HalfT, Result.getValue(1));
19169 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
19170 Regs64bit ? X86::RDX : X86::EDX,
19171 HalfT, cpOutL.getValue(2));
19172 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
19174 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
19175 MVT::i32, cpOutH.getValue(2));
19177 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19178 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
19179 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
19181 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
19182 Results.push_back(Success);
19183 Results.push_back(EFLAGS.getValue(1));
19186 case ISD::ATOMIC_SWAP:
19187 case ISD::ATOMIC_LOAD_ADD:
19188 case ISD::ATOMIC_LOAD_SUB:
19189 case ISD::ATOMIC_LOAD_AND:
19190 case ISD::ATOMIC_LOAD_OR:
19191 case ISD::ATOMIC_LOAD_XOR:
19192 case ISD::ATOMIC_LOAD_NAND:
19193 case ISD::ATOMIC_LOAD_MIN:
19194 case ISD::ATOMIC_LOAD_MAX:
19195 case ISD::ATOMIC_LOAD_UMIN:
19196 case ISD::ATOMIC_LOAD_UMAX:
19197 case ISD::ATOMIC_LOAD: {
19198 // Delegate to generic TypeLegalization. Situations we can really handle
19199 // should have already been dealt with by AtomicExpandPass.cpp.
19202 case ISD::BITCAST: {
19203 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19204 EVT DstVT = N->getValueType(0);
19205 EVT SrcVT = N->getOperand(0)->getValueType(0);
19207 if (SrcVT != MVT::f64 ||
19208 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
19211 unsigned NumElts = DstVT.getVectorNumElements();
19212 EVT SVT = DstVT.getVectorElementType();
19213 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19214 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
19215 MVT::v2f64, N->getOperand(0));
19216 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
19218 if (ExperimentalVectorWideningLegalization) {
19219 // If we are legalizing vectors by widening, we already have the desired
19220 // legal vector type, just return it.
19221 Results.push_back(ToVecInt);
19225 SmallVector<SDValue, 8> Elts;
19226 for (unsigned i = 0, e = NumElts; i != e; ++i)
19227 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
19228 ToVecInt, DAG.getIntPtrConstant(i, dl)));
19230 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
19235 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
19236 switch ((X86ISD::NodeType)Opcode) {
19237 case X86ISD::FIRST_NUMBER: break;
19238 case X86ISD::BSF: return "X86ISD::BSF";
19239 case X86ISD::BSR: return "X86ISD::BSR";
19240 case X86ISD::SHLD: return "X86ISD::SHLD";
19241 case X86ISD::SHRD: return "X86ISD::SHRD";
19242 case X86ISD::FAND: return "X86ISD::FAND";
19243 case X86ISD::FANDN: return "X86ISD::FANDN";
19244 case X86ISD::FOR: return "X86ISD::FOR";
19245 case X86ISD::FXOR: return "X86ISD::FXOR";
19246 case X86ISD::FILD: return "X86ISD::FILD";
19247 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
19248 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19249 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19250 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19251 case X86ISD::FLD: return "X86ISD::FLD";
19252 case X86ISD::FST: return "X86ISD::FST";
19253 case X86ISD::CALL: return "X86ISD::CALL";
19254 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
19255 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
19256 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
19257 case X86ISD::BT: return "X86ISD::BT";
19258 case X86ISD::CMP: return "X86ISD::CMP";
19259 case X86ISD::COMI: return "X86ISD::COMI";
19260 case X86ISD::UCOMI: return "X86ISD::UCOMI";
19261 case X86ISD::CMPM: return "X86ISD::CMPM";
19262 case X86ISD::CMPMU: return "X86ISD::CMPMU";
19263 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
19264 case X86ISD::SETCC: return "X86ISD::SETCC";
19265 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
19266 case X86ISD::FSETCC: return "X86ISD::FSETCC";
19267 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
19268 case X86ISD::CMOV: return "X86ISD::CMOV";
19269 case X86ISD::BRCOND: return "X86ISD::BRCOND";
19270 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
19271 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
19272 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
19273 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
19274 case X86ISD::Wrapper: return "X86ISD::Wrapper";
19275 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
19276 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
19277 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
19278 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
19279 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
19280 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
19281 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
19282 case X86ISD::PINSRB: return "X86ISD::PINSRB";
19283 case X86ISD::PINSRW: return "X86ISD::PINSRW";
19284 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
19285 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
19286 case X86ISD::ANDNP: return "X86ISD::ANDNP";
19287 case X86ISD::PSIGN: return "X86ISD::PSIGN";
19288 case X86ISD::BLENDI: return "X86ISD::BLENDI";
19289 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
19290 case X86ISD::ADDUS: return "X86ISD::ADDUS";
19291 case X86ISD::SUBUS: return "X86ISD::SUBUS";
19292 case X86ISD::HADD: return "X86ISD::HADD";
19293 case X86ISD::HSUB: return "X86ISD::HSUB";
19294 case X86ISD::FHADD: return "X86ISD::FHADD";
19295 case X86ISD::FHSUB: return "X86ISD::FHSUB";
19296 case X86ISD::ABS: return "X86ISD::ABS";
19297 case X86ISD::CONFLICT: return "X86ISD::CONFLICT";
19298 case X86ISD::FMAX: return "X86ISD::FMAX";
19299 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
19300 case X86ISD::FMIN: return "X86ISD::FMIN";
19301 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
19302 case X86ISD::FMAXC: return "X86ISD::FMAXC";
19303 case X86ISD::FMINC: return "X86ISD::FMINC";
19304 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
19305 case X86ISD::FRCP: return "X86ISD::FRCP";
19306 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
19307 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
19308 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
19309 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
19310 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
19311 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
19312 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
19313 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
19314 case X86ISD::CATCHRET: return "X86ISD::CATCHRET";
19315 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
19316 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
19317 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
19318 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
19319 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
19320 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
19321 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
19322 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
19323 case X86ISD::VZEXT: return "X86ISD::VZEXT";
19324 case X86ISD::VSEXT: return "X86ISD::VSEXT";
19325 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
19326 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
19327 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
19328 case X86ISD::VINSERT: return "X86ISD::VINSERT";
19329 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
19330 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
19331 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
19332 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
19333 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
19334 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
19335 case X86ISD::VSHL: return "X86ISD::VSHL";
19336 case X86ISD::VSRL: return "X86ISD::VSRL";
19337 case X86ISD::VSRA: return "X86ISD::VSRA";
19338 case X86ISD::VSHLI: return "X86ISD::VSHLI";
19339 case X86ISD::VSRLI: return "X86ISD::VSRLI";
19340 case X86ISD::VSRAI: return "X86ISD::VSRAI";
19341 case X86ISD::CMPP: return "X86ISD::CMPP";
19342 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
19343 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
19344 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
19345 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
19346 case X86ISD::ADD: return "X86ISD::ADD";
19347 case X86ISD::SUB: return "X86ISD::SUB";
19348 case X86ISD::ADC: return "X86ISD::ADC";
19349 case X86ISD::SBB: return "X86ISD::SBB";
19350 case X86ISD::SMUL: return "X86ISD::SMUL";
19351 case X86ISD::UMUL: return "X86ISD::UMUL";
19352 case X86ISD::SMUL8: return "X86ISD::SMUL8";
19353 case X86ISD::UMUL8: return "X86ISD::UMUL8";
19354 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19355 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19356 case X86ISD::INC: return "X86ISD::INC";
19357 case X86ISD::DEC: return "X86ISD::DEC";
19358 case X86ISD::OR: return "X86ISD::OR";
19359 case X86ISD::XOR: return "X86ISD::XOR";
19360 case X86ISD::AND: return "X86ISD::AND";
19361 case X86ISD::BEXTR: return "X86ISD::BEXTR";
19362 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
19363 case X86ISD::PTEST: return "X86ISD::PTEST";
19364 case X86ISD::TESTP: return "X86ISD::TESTP";
19365 case X86ISD::TESTM: return "X86ISD::TESTM";
19366 case X86ISD::TESTNM: return "X86ISD::TESTNM";
19367 case X86ISD::KORTEST: return "X86ISD::KORTEST";
19368 case X86ISD::KTEST: return "X86ISD::KTEST";
19369 case X86ISD::PACKSS: return "X86ISD::PACKSS";
19370 case X86ISD::PACKUS: return "X86ISD::PACKUS";
19371 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
19372 case X86ISD::VALIGN: return "X86ISD::VALIGN";
19373 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
19374 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
19375 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
19376 case X86ISD::SHUFP: return "X86ISD::SHUFP";
19377 case X86ISD::SHUF128: return "X86ISD::SHUF128";
19378 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
19379 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
19380 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
19381 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
19382 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
19383 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
19384 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
19385 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
19386 case X86ISD::MOVSD: return "X86ISD::MOVSD";
19387 case X86ISD::MOVSS: return "X86ISD::MOVSS";
19388 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
19389 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
19390 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
19391 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
19392 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
19393 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
19394 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
19395 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
19396 case X86ISD::VPERMV: return "X86ISD::VPERMV";
19397 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
19398 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
19399 case X86ISD::VPERMI: return "X86ISD::VPERMI";
19400 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
19401 case X86ISD::VRANGE: return "X86ISD::VRANGE";
19402 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
19403 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
19404 case X86ISD::PSADBW: return "X86ISD::PSADBW";
19405 case X86ISD::DBPSADBW: return "X86ISD::DBPSADBW";
19406 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19407 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
19408 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
19409 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
19410 case X86ISD::MFENCE: return "X86ISD::MFENCE";
19411 case X86ISD::SFENCE: return "X86ISD::SFENCE";
19412 case X86ISD::LFENCE: return "X86ISD::LFENCE";
19413 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
19414 case X86ISD::SAHF: return "X86ISD::SAHF";
19415 case X86ISD::RDRAND: return "X86ISD::RDRAND";
19416 case X86ISD::RDSEED: return "X86ISD::RDSEED";
19417 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
19418 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
19419 case X86ISD::FMADD: return "X86ISD::FMADD";
19420 case X86ISD::FMSUB: return "X86ISD::FMSUB";
19421 case X86ISD::FNMADD: return "X86ISD::FNMADD";
19422 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
19423 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
19424 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
19425 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
19426 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
19427 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
19428 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
19429 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
19430 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
19431 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
19432 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
19433 case X86ISD::VGETMANT: return "X86ISD::VGETMANT";
19434 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
19435 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
19436 case X86ISD::XTEST: return "X86ISD::XTEST";
19437 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
19438 case X86ISD::EXPAND: return "X86ISD::EXPAND";
19439 case X86ISD::SELECT: return "X86ISD::SELECT";
19440 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
19441 case X86ISD::RCP28: return "X86ISD::RCP28";
19442 case X86ISD::EXP2: return "X86ISD::EXP2";
19443 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
19444 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
19445 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
19446 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
19447 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
19448 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
19449 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
19450 case X86ISD::SCALEF: return "X86ISD::SCALEF";
19451 case X86ISD::ADDS: return "X86ISD::ADDS";
19452 case X86ISD::SUBS: return "X86ISD::SUBS";
19453 case X86ISD::AVG: return "X86ISD::AVG";
19454 case X86ISD::MULHRS: return "X86ISD::MULHRS";
19455 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
19456 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
19457 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
19458 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
19463 // isLegalAddressingMode - Return true if the addressing mode represented
19464 // by AM is legal for this target, for a load/store of the specified type.
19465 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19466 const AddrMode &AM, Type *Ty,
19467 unsigned AS) const {
19468 // X86 supports extremely general addressing modes.
19469 CodeModel::Model M = getTargetMachine().getCodeModel();
19470 Reloc::Model R = getTargetMachine().getRelocationModel();
19472 // X86 allows a sign-extended 32-bit immediate field as a displacement.
19473 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19478 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19480 // If a reference to this global requires an extra load, we can't fold it.
19481 if (isGlobalStubReference(GVFlags))
19484 // If BaseGV requires a register for the PIC base, we cannot also have a
19485 // BaseReg specified.
19486 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19489 // If lower 4G is not available, then we must use rip-relative addressing.
19490 if ((M != CodeModel::Small || R != Reloc::Static) &&
19491 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19495 switch (AM.Scale) {
19501 // These scales always work.
19506 // These scales are formed with basereg+scalereg. Only accept if there is
19511 default: // Other stuff never works.
19518 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19519 unsigned Bits = Ty->getScalarSizeInBits();
19521 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19522 // particularly cheaper than those without.
19526 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19527 // variable shifts just as cheap as scalar ones.
19528 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19531 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19532 // fully general vector.
19536 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19537 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19539 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19540 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19541 return NumBits1 > NumBits2;
19544 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19545 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19548 if (!isTypeLegal(EVT::getEVT(Ty1)))
19551 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19553 // Assuming the caller doesn't have a zeroext or signext return parameter,
19554 // truncation all the way down to i1 is valid.
19558 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19559 return isInt<32>(Imm);
19562 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19563 // Can also use sub to handle negated immediates.
19564 return isInt<32>(Imm);
19567 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19568 if (!VT1.isInteger() || !VT2.isInteger())
19570 unsigned NumBits1 = VT1.getSizeInBits();
19571 unsigned NumBits2 = VT2.getSizeInBits();
19572 return NumBits1 > NumBits2;
19575 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19576 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19577 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19580 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19581 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19582 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19585 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19586 EVT VT1 = Val.getValueType();
19587 if (isZExtFree(VT1, VT2))
19590 if (Val.getOpcode() != ISD::LOAD)
19593 if (!VT1.isSimple() || !VT1.isInteger() ||
19594 !VT2.isSimple() || !VT2.isInteger())
19597 switch (VT1.getSimpleVT().SimpleTy) {
19602 // X86 has 8, 16, and 32-bit zero-extending loads.
19609 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19612 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19613 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19616 VT = VT.getScalarType();
19618 if (!VT.isSimple())
19621 switch (VT.getSimpleVT().SimpleTy) {
19632 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19633 // i16 instructions are longer (0x66 prefix) and potentially slower.
19634 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19637 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19638 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19639 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19640 /// are assumed to be legal.
19642 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19644 if (!VT.isSimple())
19647 // Not for i1 vectors
19648 if (VT.getScalarType() == MVT::i1)
19651 // Very little shuffling can be done for 64-bit vectors right now.
19652 if (VT.getSizeInBits() == 64)
19655 // We only care that the types being shuffled are legal. The lowering can
19656 // handle any possible shuffle mask that results.
19657 return isTypeLegal(VT.getSimpleVT());
19661 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19663 // Just delegate to the generic legality, clear masks aren't special.
19664 return isShuffleMaskLegal(Mask, VT);
19667 //===----------------------------------------------------------------------===//
19668 // X86 Scheduler Hooks
19669 //===----------------------------------------------------------------------===//
19671 /// Utility function to emit xbegin specifying the start of an RTM region.
19672 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19673 const TargetInstrInfo *TII) {
19674 DebugLoc DL = MI->getDebugLoc();
19676 const BasicBlock *BB = MBB->getBasicBlock();
19677 MachineFunction::iterator I = MBB;
19680 // For the v = xbegin(), we generate
19691 MachineBasicBlock *thisMBB = MBB;
19692 MachineFunction *MF = MBB->getParent();
19693 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19694 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19695 MF->insert(I, mainMBB);
19696 MF->insert(I, sinkMBB);
19698 // Transfer the remainder of BB and its successor edges to sinkMBB.
19699 sinkMBB->splice(sinkMBB->begin(), MBB,
19700 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19701 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19705 // # fallthrough to mainMBB
19706 // # abortion to sinkMBB
19707 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19708 thisMBB->addSuccessor(mainMBB);
19709 thisMBB->addSuccessor(sinkMBB);
19713 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19714 mainMBB->addSuccessor(sinkMBB);
19717 // EAX is live into the sinkMBB
19718 sinkMBB->addLiveIn(X86::EAX);
19719 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19720 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19723 MI->eraseFromParent();
19727 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19728 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19729 // in the .td file.
19730 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19731 const TargetInstrInfo *TII) {
19733 switch (MI->getOpcode()) {
19734 default: llvm_unreachable("illegal opcode!");
19735 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
19736 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19737 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
19738 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19739 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
19740 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19741 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
19742 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19745 DebugLoc dl = MI->getDebugLoc();
19746 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19748 unsigned NumArgs = MI->getNumOperands();
19749 for (unsigned i = 1; i < NumArgs; ++i) {
19750 MachineOperand &Op = MI->getOperand(i);
19751 if (!(Op.isReg() && Op.isImplicit()))
19752 MIB.addOperand(Op);
19754 if (MI->hasOneMemOperand())
19755 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19757 BuildMI(*BB, MI, dl,
19758 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19759 .addReg(X86::XMM0);
19761 MI->eraseFromParent();
19765 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19766 // defs in an instruction pattern
19767 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19768 const TargetInstrInfo *TII) {
19770 switch (MI->getOpcode()) {
19771 default: llvm_unreachable("illegal opcode!");
19772 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
19773 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19774 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
19775 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19776 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
19777 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19778 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
19779 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19782 DebugLoc dl = MI->getDebugLoc();
19783 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19785 unsigned NumArgs = MI->getNumOperands(); // remove the results
19786 for (unsigned i = 1; i < NumArgs; ++i) {
19787 MachineOperand &Op = MI->getOperand(i);
19788 if (!(Op.isReg() && Op.isImplicit()))
19789 MIB.addOperand(Op);
19791 if (MI->hasOneMemOperand())
19792 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19794 BuildMI(*BB, MI, dl,
19795 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19798 MI->eraseFromParent();
19802 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19803 const X86Subtarget *Subtarget) {
19804 DebugLoc dl = MI->getDebugLoc();
19805 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19806 // Address into RAX/EAX, other two args into ECX, EDX.
19807 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19808 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19809 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19810 for (int i = 0; i < X86::AddrNumOperands; ++i)
19811 MIB.addOperand(MI->getOperand(i));
19813 unsigned ValOps = X86::AddrNumOperands;
19814 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19815 .addReg(MI->getOperand(ValOps).getReg());
19816 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19817 .addReg(MI->getOperand(ValOps+1).getReg());
19819 // The instruction doesn't actually take any operands though.
19820 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19822 MI->eraseFromParent(); // The pseudo is gone now.
19826 MachineBasicBlock *
19827 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19828 MachineBasicBlock *MBB) const {
19829 // Emit va_arg instruction on X86-64.
19831 // Operands to this pseudo-instruction:
19832 // 0 ) Output : destination address (reg)
19833 // 1-5) Input : va_list address (addr, i64mem)
19834 // 6 ) ArgSize : Size (in bytes) of vararg type
19835 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19836 // 8 ) Align : Alignment of type
19837 // 9 ) EFLAGS (implicit-def)
19839 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19840 static_assert(X86::AddrNumOperands == 5,
19841 "VAARG_64 assumes 5 address operands");
19843 unsigned DestReg = MI->getOperand(0).getReg();
19844 MachineOperand &Base = MI->getOperand(1);
19845 MachineOperand &Scale = MI->getOperand(2);
19846 MachineOperand &Index = MI->getOperand(3);
19847 MachineOperand &Disp = MI->getOperand(4);
19848 MachineOperand &Segment = MI->getOperand(5);
19849 unsigned ArgSize = MI->getOperand(6).getImm();
19850 unsigned ArgMode = MI->getOperand(7).getImm();
19851 unsigned Align = MI->getOperand(8).getImm();
19853 // Memory Reference
19854 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19855 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19856 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19858 // Machine Information
19859 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19860 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19861 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19862 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19863 DebugLoc DL = MI->getDebugLoc();
19865 // struct va_list {
19868 // i64 overflow_area (address)
19869 // i64 reg_save_area (address)
19871 // sizeof(va_list) = 24
19872 // alignment(va_list) = 8
19874 unsigned TotalNumIntRegs = 6;
19875 unsigned TotalNumXMMRegs = 8;
19876 bool UseGPOffset = (ArgMode == 1);
19877 bool UseFPOffset = (ArgMode == 2);
19878 unsigned MaxOffset = TotalNumIntRegs * 8 +
19879 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19881 /* Align ArgSize to a multiple of 8 */
19882 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19883 bool NeedsAlign = (Align > 8);
19885 MachineBasicBlock *thisMBB = MBB;
19886 MachineBasicBlock *overflowMBB;
19887 MachineBasicBlock *offsetMBB;
19888 MachineBasicBlock *endMBB;
19890 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
19891 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
19892 unsigned OffsetReg = 0;
19894 if (!UseGPOffset && !UseFPOffset) {
19895 // If we only pull from the overflow region, we don't create a branch.
19896 // We don't need to alter control flow.
19897 OffsetDestReg = 0; // unused
19898 OverflowDestReg = DestReg;
19900 offsetMBB = nullptr;
19901 overflowMBB = thisMBB;
19904 // First emit code to check if gp_offset (or fp_offset) is below the bound.
19905 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19906 // If not, pull from overflow_area. (branch to overflowMBB)
19911 // offsetMBB overflowMBB
19916 // Registers for the PHI in endMBB
19917 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19918 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19920 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19921 MachineFunction *MF = MBB->getParent();
19922 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19923 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19924 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19926 MachineFunction::iterator MBBIter = MBB;
19929 // Insert the new basic blocks
19930 MF->insert(MBBIter, offsetMBB);
19931 MF->insert(MBBIter, overflowMBB);
19932 MF->insert(MBBIter, endMBB);
19934 // Transfer the remainder of MBB and its successor edges to endMBB.
19935 endMBB->splice(endMBB->begin(), thisMBB,
19936 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19937 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19939 // Make offsetMBB and overflowMBB successors of thisMBB
19940 thisMBB->addSuccessor(offsetMBB);
19941 thisMBB->addSuccessor(overflowMBB);
19943 // endMBB is a successor of both offsetMBB and overflowMBB
19944 offsetMBB->addSuccessor(endMBB);
19945 overflowMBB->addSuccessor(endMBB);
19947 // Load the offset value into a register
19948 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19949 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19953 .addDisp(Disp, UseFPOffset ? 4 : 0)
19954 .addOperand(Segment)
19955 .setMemRefs(MMOBegin, MMOEnd);
19957 // Check if there is enough room left to pull this argument.
19958 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19960 .addImm(MaxOffset + 8 - ArgSizeA8);
19962 // Branch to "overflowMBB" if offset >= max
19963 // Fall through to "offsetMBB" otherwise
19964 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19965 .addMBB(overflowMBB);
19968 // In offsetMBB, emit code to use the reg_save_area.
19970 assert(OffsetReg != 0);
19972 // Read the reg_save_area address.
19973 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19974 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19979 .addOperand(Segment)
19980 .setMemRefs(MMOBegin, MMOEnd);
19982 // Zero-extend the offset
19983 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19984 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19987 .addImm(X86::sub_32bit);
19989 // Add the offset to the reg_save_area to get the final address.
19990 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19991 .addReg(OffsetReg64)
19992 .addReg(RegSaveReg);
19994 // Compute the offset for the next argument
19995 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19996 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19998 .addImm(UseFPOffset ? 16 : 8);
20000 // Store it back into the va_list.
20001 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
20005 .addDisp(Disp, UseFPOffset ? 4 : 0)
20006 .addOperand(Segment)
20007 .addReg(NextOffsetReg)
20008 .setMemRefs(MMOBegin, MMOEnd);
20011 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
20016 // Emit code to use overflow area
20019 // Load the overflow_area address into a register.
20020 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
20021 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
20026 .addOperand(Segment)
20027 .setMemRefs(MMOBegin, MMOEnd);
20029 // If we need to align it, do so. Otherwise, just copy the address
20030 // to OverflowDestReg.
20032 // Align the overflow address
20033 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
20034 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
20036 // aligned_addr = (addr + (align-1)) & ~(align-1)
20037 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
20038 .addReg(OverflowAddrReg)
20041 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
20043 .addImm(~(uint64_t)(Align-1));
20045 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
20046 .addReg(OverflowAddrReg);
20049 // Compute the next overflow address after this argument.
20050 // (the overflow address should be kept 8-byte aligned)
20051 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
20052 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
20053 .addReg(OverflowDestReg)
20054 .addImm(ArgSizeA8);
20056 // Store the new overflow address.
20057 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
20062 .addOperand(Segment)
20063 .addReg(NextAddrReg)
20064 .setMemRefs(MMOBegin, MMOEnd);
20066 // If we branched, emit the PHI to the front of endMBB.
20068 BuildMI(*endMBB, endMBB->begin(), DL,
20069 TII->get(X86::PHI), DestReg)
20070 .addReg(OffsetDestReg).addMBB(offsetMBB)
20071 .addReg(OverflowDestReg).addMBB(overflowMBB);
20074 // Erase the pseudo instruction
20075 MI->eraseFromParent();
20080 MachineBasicBlock *
20081 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
20083 MachineBasicBlock *MBB) const {
20084 // Emit code to save XMM registers to the stack. The ABI says that the
20085 // number of registers to save is given in %al, so it's theoretically
20086 // possible to do an indirect jump trick to avoid saving all of them,
20087 // however this code takes a simpler approach and just executes all
20088 // of the stores if %al is non-zero. It's less code, and it's probably
20089 // easier on the hardware branch predictor, and stores aren't all that
20090 // expensive anyway.
20092 // Create the new basic blocks. One block contains all the XMM stores,
20093 // and one block is the final destination regardless of whether any
20094 // stores were performed.
20095 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20096 MachineFunction *F = MBB->getParent();
20097 MachineFunction::iterator MBBIter = MBB;
20099 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
20100 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
20101 F->insert(MBBIter, XMMSaveMBB);
20102 F->insert(MBBIter, EndMBB);
20104 // Transfer the remainder of MBB and its successor edges to EndMBB.
20105 EndMBB->splice(EndMBB->begin(), MBB,
20106 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20107 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
20109 // The original block will now fall through to the XMM save block.
20110 MBB->addSuccessor(XMMSaveMBB);
20111 // The XMMSaveMBB will fall through to the end block.
20112 XMMSaveMBB->addSuccessor(EndMBB);
20114 // Now add the instructions.
20115 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20116 DebugLoc DL = MI->getDebugLoc();
20118 unsigned CountReg = MI->getOperand(0).getReg();
20119 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
20120 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
20122 if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
20123 // If %al is 0, branch around the XMM save block.
20124 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
20125 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
20126 MBB->addSuccessor(EndMBB);
20129 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
20130 // that was just emitted, but clearly shouldn't be "saved".
20131 assert((MI->getNumOperands() <= 3 ||
20132 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
20133 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
20134 && "Expected last argument to be EFLAGS");
20135 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
20136 // In the XMM save block, save all the XMM argument registers.
20137 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
20138 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
20139 MachineMemOperand *MMO = F->getMachineMemOperand(
20140 MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
20141 MachineMemOperand::MOStore,
20142 /*Size=*/16, /*Align=*/16);
20143 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
20144 .addFrameIndex(RegSaveFrameIndex)
20145 .addImm(/*Scale=*/1)
20146 .addReg(/*IndexReg=*/0)
20147 .addImm(/*Disp=*/Offset)
20148 .addReg(/*Segment=*/0)
20149 .addReg(MI->getOperand(i).getReg())
20150 .addMemOperand(MMO);
20153 MI->eraseFromParent(); // The pseudo instruction is gone now.
20158 // The EFLAGS operand of SelectItr might be missing a kill marker
20159 // because there were multiple uses of EFLAGS, and ISel didn't know
20160 // which to mark. Figure out whether SelectItr should have had a
20161 // kill marker, and set it if it should. Returns the correct kill
20163 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
20164 MachineBasicBlock* BB,
20165 const TargetRegisterInfo* TRI) {
20166 // Scan forward through BB for a use/def of EFLAGS.
20167 MachineBasicBlock::iterator miI(std::next(SelectItr));
20168 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
20169 const MachineInstr& mi = *miI;
20170 if (mi.readsRegister(X86::EFLAGS))
20172 if (mi.definesRegister(X86::EFLAGS))
20173 break; // Should have kill-flag - update below.
20176 // If we hit the end of the block, check whether EFLAGS is live into a
20178 if (miI == BB->end()) {
20179 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
20180 sEnd = BB->succ_end();
20181 sItr != sEnd; ++sItr) {
20182 MachineBasicBlock* succ = *sItr;
20183 if (succ->isLiveIn(X86::EFLAGS))
20188 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
20189 // out. SelectMI should have a kill flag on EFLAGS.
20190 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
20194 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
20195 // together with other CMOV pseudo-opcodes into a single basic-block with
20196 // conditional jump around it.
20197 static bool isCMOVPseudo(MachineInstr *MI) {
20198 switch (MI->getOpcode()) {
20199 case X86::CMOV_FR32:
20200 case X86::CMOV_FR64:
20201 case X86::CMOV_GR8:
20202 case X86::CMOV_GR16:
20203 case X86::CMOV_GR32:
20204 case X86::CMOV_RFP32:
20205 case X86::CMOV_RFP64:
20206 case X86::CMOV_RFP80:
20207 case X86::CMOV_V2F64:
20208 case X86::CMOV_V2I64:
20209 case X86::CMOV_V4F32:
20210 case X86::CMOV_V4F64:
20211 case X86::CMOV_V4I64:
20212 case X86::CMOV_V16F32:
20213 case X86::CMOV_V8F32:
20214 case X86::CMOV_V8F64:
20215 case X86::CMOV_V8I64:
20216 case X86::CMOV_V8I1:
20217 case X86::CMOV_V16I1:
20218 case X86::CMOV_V32I1:
20219 case X86::CMOV_V64I1:
20227 MachineBasicBlock *
20228 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
20229 MachineBasicBlock *BB) const {
20230 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20231 DebugLoc DL = MI->getDebugLoc();
20233 // To "insert" a SELECT_CC instruction, we actually have to insert the
20234 // diamond control-flow pattern. The incoming instruction knows the
20235 // destination vreg to set, the condition code register to branch on, the
20236 // true/false values to select between, and a branch opcode to use.
20237 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20238 MachineFunction::iterator It = BB;
20244 // cmpTY ccX, r1, r2
20246 // fallthrough --> copy0MBB
20247 MachineBasicBlock *thisMBB = BB;
20248 MachineFunction *F = BB->getParent();
20250 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20251 // as described above, by inserting a BB, and then making a PHI at the join
20252 // point to select the true and false operands of the CMOV in the PHI.
20254 // The code also handles two different cases of multiple CMOV opcodes
20258 // In this case, there are multiple CMOVs in a row, all which are based on
20259 // the same condition setting (or the exact opposite condition setting).
20260 // In this case we can lower all the CMOVs using a single inserted BB, and
20261 // then make a number of PHIs at the join point to model the CMOVs. The only
20262 // trickiness here, is that in a case like:
20264 // t2 = CMOV cond1 t1, f1
20265 // t3 = CMOV cond1 t2, f2
20267 // when rewriting this into PHIs, we have to perform some renaming on the
20268 // temps since you cannot have a PHI operand refer to a PHI result earlier
20269 // in the same block. The "simple" but wrong lowering would be:
20271 // t2 = PHI t1(BB1), f1(BB2)
20272 // t3 = PHI t2(BB1), f2(BB2)
20274 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20275 // renaming is to note that on the path through BB1, t2 is really just a
20276 // copy of t1, and do that renaming, properly generating:
20278 // t2 = PHI t1(BB1), f1(BB2)
20279 // t3 = PHI t1(BB1), f2(BB2)
20281 // Case 2, we lower cascaded CMOVs such as
20283 // (CMOV (CMOV F, T, cc1), T, cc2)
20285 // to two successives branches. For that, we look for another CMOV as the
20286 // following instruction.
20288 // Without this, we would add a PHI between the two jumps, which ends up
20289 // creating a few copies all around. For instance, for
20291 // (sitofp (zext (fcmp une)))
20293 // we would generate:
20295 // ucomiss %xmm1, %xmm0
20296 // movss <1.0f>, %xmm0
20297 // movaps %xmm0, %xmm1
20299 // xorps %xmm1, %xmm1
20302 // movaps %xmm1, %xmm0
20306 // because this custom-inserter would have generated:
20318 // A: X = ...; Y = ...
20320 // C: Z = PHI [X, A], [Y, B]
20322 // E: PHI [X, C], [Z, D]
20324 // If we lower both CMOVs in a single step, we can instead generate:
20336 // A: X = ...; Y = ...
20338 // E: PHI [X, A], [X, C], [Y, D]
20340 // Which, in our sitofp/fcmp example, gives us something like:
20342 // ucomiss %xmm1, %xmm0
20343 // movss <1.0f>, %xmm0
20346 // xorps %xmm0, %xmm0
20350 MachineInstr *CascadedCMOV = nullptr;
20351 MachineInstr *LastCMOV = MI;
20352 X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20353 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20354 MachineBasicBlock::iterator NextMIIt =
20355 std::next(MachineBasicBlock::iterator(MI));
20357 // Check for case 1, where there are multiple CMOVs with the same condition
20358 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
20359 // number of jumps the most.
20361 if (isCMOVPseudo(MI)) {
20362 // See if we have a string of CMOVS with the same condition.
20363 while (NextMIIt != BB->end() &&
20364 isCMOVPseudo(NextMIIt) &&
20365 (NextMIIt->getOperand(3).getImm() == CC ||
20366 NextMIIt->getOperand(3).getImm() == OppCC)) {
20367 LastCMOV = &*NextMIIt;
20372 // This checks for case 2, but only do this if we didn't already find
20373 // case 1, as indicated by LastCMOV == MI.
20374 if (LastCMOV == MI &&
20375 NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20376 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20377 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20378 CascadedCMOV = &*NextMIIt;
20381 MachineBasicBlock *jcc1MBB = nullptr;
20383 // If we have a cascaded CMOV, we lower it to two successive branches to
20384 // the same block. EFLAGS is used by both, so mark it as live in the second.
20385 if (CascadedCMOV) {
20386 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20387 F->insert(It, jcc1MBB);
20388 jcc1MBB->addLiveIn(X86::EFLAGS);
20391 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20392 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20393 F->insert(It, copy0MBB);
20394 F->insert(It, sinkMBB);
20396 // If the EFLAGS register isn't dead in the terminator, then claim that it's
20397 // live into the sink and copy blocks.
20398 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20400 MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20401 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20402 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20403 copy0MBB->addLiveIn(X86::EFLAGS);
20404 sinkMBB->addLiveIn(X86::EFLAGS);
20407 // Transfer the remainder of BB and its successor edges to sinkMBB.
20408 sinkMBB->splice(sinkMBB->begin(), BB,
20409 std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20410 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20412 // Add the true and fallthrough blocks as its successors.
20413 if (CascadedCMOV) {
20414 // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20415 BB->addSuccessor(jcc1MBB);
20417 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20418 // jump to the sinkMBB.
20419 jcc1MBB->addSuccessor(copy0MBB);
20420 jcc1MBB->addSuccessor(sinkMBB);
20422 BB->addSuccessor(copy0MBB);
20425 // The true block target of the first (or only) branch is always sinkMBB.
20426 BB->addSuccessor(sinkMBB);
20428 // Create the conditional branch instruction.
20429 unsigned Opc = X86::GetCondBranchFromCond(CC);
20430 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20432 if (CascadedCMOV) {
20433 unsigned Opc2 = X86::GetCondBranchFromCond(
20434 (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20435 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20439 // %FalseValue = ...
20440 // # fallthrough to sinkMBB
20441 copy0MBB->addSuccessor(sinkMBB);
20444 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20446 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20447 MachineBasicBlock::iterator MIItEnd =
20448 std::next(MachineBasicBlock::iterator(LastCMOV));
20449 MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20450 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20451 MachineInstrBuilder MIB;
20453 // As we are creating the PHIs, we have to be careful if there is more than
20454 // one. Later CMOVs may reference the results of earlier CMOVs, but later
20455 // PHIs have to reference the individual true/false inputs from earlier PHIs.
20456 // That also means that PHI construction must work forward from earlier to
20457 // later, and that the code must maintain a mapping from earlier PHI's
20458 // destination registers, and the registers that went into the PHI.
20460 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20461 unsigned DestReg = MIIt->getOperand(0).getReg();
20462 unsigned Op1Reg = MIIt->getOperand(1).getReg();
20463 unsigned Op2Reg = MIIt->getOperand(2).getReg();
20465 // If this CMOV we are generating is the opposite condition from
20466 // the jump we generated, then we have to swap the operands for the
20467 // PHI that is going to be generated.
20468 if (MIIt->getOperand(3).getImm() == OppCC)
20469 std::swap(Op1Reg, Op2Reg);
20471 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20472 Op1Reg = RegRewriteTable[Op1Reg].first;
20474 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20475 Op2Reg = RegRewriteTable[Op2Reg].second;
20477 MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20478 TII->get(X86::PHI), DestReg)
20479 .addReg(Op1Reg).addMBB(copy0MBB)
20480 .addReg(Op2Reg).addMBB(thisMBB);
20482 // Add this PHI to the rewrite table.
20483 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20486 // If we have a cascaded CMOV, the second Jcc provides the same incoming
20487 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20488 if (CascadedCMOV) {
20489 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20490 // Copy the PHI result to the register defined by the second CMOV.
20491 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20492 DL, TII->get(TargetOpcode::COPY),
20493 CascadedCMOV->getOperand(0).getReg())
20494 .addReg(MI->getOperand(0).getReg());
20495 CascadedCMOV->eraseFromParent();
20498 // Now remove the CMOV(s).
20499 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20500 (MIIt++)->eraseFromParent();
20505 MachineBasicBlock *
20506 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20507 MachineBasicBlock *BB) const {
20508 // Combine the following atomic floating-point modification pattern:
20509 // a.store(reg OP a.load(acquire), release)
20510 // Transform them into:
20511 // OPss (%gpr), %xmm
20512 // movss %xmm, (%gpr)
20513 // Or sd equivalent for 64-bit operations.
20515 switch (MI->getOpcode()) {
20516 default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20517 case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20518 case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20520 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20521 DebugLoc DL = MI->getDebugLoc();
20522 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20523 unsigned MSrc = MI->getOperand(0).getReg();
20524 unsigned VSrc = MI->getOperand(5).getReg();
20525 MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20526 .addReg(/*Base=*/MSrc)
20527 .addImm(/*Scale=*/1)
20528 .addReg(/*Index=*/0)
20531 MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20532 MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20534 .addReg(/*Base=*/MSrc)
20535 .addImm(/*Scale=*/1)
20536 .addReg(/*Index=*/0)
20537 .addImm(/*Disp=*/0)
20538 .addReg(/*Segment=*/0);
20539 MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20540 MI->eraseFromParent(); // The pseudo instruction is gone now.
20544 MachineBasicBlock *
20545 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20546 MachineBasicBlock *BB) const {
20547 MachineFunction *MF = BB->getParent();
20548 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20549 DebugLoc DL = MI->getDebugLoc();
20550 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20552 assert(MF->shouldSplitStack());
20554 const bool Is64Bit = Subtarget->is64Bit();
20555 const bool IsLP64 = Subtarget->isTarget64BitLP64();
20557 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20558 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20561 // ... [Till the alloca]
20562 // If stacklet is not large enough, jump to mallocMBB
20565 // Allocate by subtracting from RSP
20566 // Jump to continueMBB
20569 // Allocate by call to runtime
20573 // [rest of original BB]
20576 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20577 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20578 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20580 MachineRegisterInfo &MRI = MF->getRegInfo();
20581 const TargetRegisterClass *AddrRegClass =
20582 getRegClassFor(getPointerTy(MF->getDataLayout()));
20584 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20585 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20586 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20587 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20588 sizeVReg = MI->getOperand(1).getReg(),
20589 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20591 MachineFunction::iterator MBBIter = BB;
20594 MF->insert(MBBIter, bumpMBB);
20595 MF->insert(MBBIter, mallocMBB);
20596 MF->insert(MBBIter, continueMBB);
20598 continueMBB->splice(continueMBB->begin(), BB,
20599 std::next(MachineBasicBlock::iterator(MI)), BB->end());
20600 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20602 // Add code to the main basic block to check if the stack limit has been hit,
20603 // and if so, jump to mallocMBB otherwise to bumpMBB.
20604 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20605 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20606 .addReg(tmpSPVReg).addReg(sizeVReg);
20607 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20608 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20609 .addReg(SPLimitVReg);
20610 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20612 // bumpMBB simply decreases the stack pointer, since we know the current
20613 // stacklet has enough space.
20614 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20615 .addReg(SPLimitVReg);
20616 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20617 .addReg(SPLimitVReg);
20618 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20620 // Calls into a routine in libgcc to allocate more space from the heap.
20621 const uint32_t *RegMask =
20622 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20624 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20626 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20627 .addExternalSymbol("__morestack_allocate_stack_space")
20628 .addRegMask(RegMask)
20629 .addReg(X86::RDI, RegState::Implicit)
20630 .addReg(X86::RAX, RegState::ImplicitDefine);
20631 } else if (Is64Bit) {
20632 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20634 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20635 .addExternalSymbol("__morestack_allocate_stack_space")
20636 .addRegMask(RegMask)
20637 .addReg(X86::EDI, RegState::Implicit)
20638 .addReg(X86::EAX, RegState::ImplicitDefine);
20640 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20642 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20643 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20644 .addExternalSymbol("__morestack_allocate_stack_space")
20645 .addRegMask(RegMask)
20646 .addReg(X86::EAX, RegState::ImplicitDefine);
20650 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20653 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20654 .addReg(IsLP64 ? X86::RAX : X86::EAX);
20655 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20657 // Set up the CFG correctly.
20658 BB->addSuccessor(bumpMBB);
20659 BB->addSuccessor(mallocMBB);
20660 mallocMBB->addSuccessor(continueMBB);
20661 bumpMBB->addSuccessor(continueMBB);
20663 // Take care of the PHI nodes.
20664 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20665 MI->getOperand(0).getReg())
20666 .addReg(mallocPtrVReg).addMBB(mallocMBB)
20667 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20669 // Delete the original pseudo instruction.
20670 MI->eraseFromParent();
20673 return continueMBB;
20676 MachineBasicBlock *
20677 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20678 MachineBasicBlock *BB) const {
20679 DebugLoc DL = MI->getDebugLoc();
20681 assert(!Subtarget->isTargetMachO());
20683 Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20686 MI->eraseFromParent(); // The pseudo instruction is gone now.
20690 MachineBasicBlock *
20691 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20692 MachineBasicBlock *BB) const {
20693 // This is pretty easy. We're taking the value that we received from
20694 // our load from the relocation, sticking it in either RDI (x86-64)
20695 // or EAX and doing an indirect call. The return value will then
20696 // be in the normal return register.
20697 MachineFunction *F = BB->getParent();
20698 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20699 DebugLoc DL = MI->getDebugLoc();
20701 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20702 assert(MI->getOperand(3).isGlobal() && "This should be a global");
20704 // Get a register mask for the lowered call.
20705 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20706 // proper register mask.
20707 const uint32_t *RegMask =
20708 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20709 if (Subtarget->is64Bit()) {
20710 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20711 TII->get(X86::MOV64rm), X86::RDI)
20713 .addImm(0).addReg(0)
20714 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20715 MI->getOperand(3).getTargetFlags())
20717 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20718 addDirectMem(MIB, X86::RDI);
20719 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20720 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20721 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20722 TII->get(X86::MOV32rm), X86::EAX)
20724 .addImm(0).addReg(0)
20725 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20726 MI->getOperand(3).getTargetFlags())
20728 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20729 addDirectMem(MIB, X86::EAX);
20730 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20732 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20733 TII->get(X86::MOV32rm), X86::EAX)
20734 .addReg(TII->getGlobalBaseReg(F))
20735 .addImm(0).addReg(0)
20736 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20737 MI->getOperand(3).getTargetFlags())
20739 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20740 addDirectMem(MIB, X86::EAX);
20741 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20744 MI->eraseFromParent(); // The pseudo instruction is gone now.
20748 MachineBasicBlock *
20749 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20750 MachineBasicBlock *MBB) const {
20751 DebugLoc DL = MI->getDebugLoc();
20752 MachineFunction *MF = MBB->getParent();
20753 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20754 MachineRegisterInfo &MRI = MF->getRegInfo();
20756 const BasicBlock *BB = MBB->getBasicBlock();
20757 MachineFunction::iterator I = MBB;
20760 // Memory Reference
20761 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20762 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20765 unsigned MemOpndSlot = 0;
20767 unsigned CurOp = 0;
20769 DstReg = MI->getOperand(CurOp++).getReg();
20770 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20771 assert(RC->hasType(MVT::i32) && "Invalid destination!");
20772 unsigned mainDstReg = MRI.createVirtualRegister(RC);
20773 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20775 MemOpndSlot = CurOp;
20777 MVT PVT = getPointerTy(MF->getDataLayout());
20778 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20779 "Invalid Pointer Size!");
20781 // For v = setjmp(buf), we generate
20784 // buf[LabelOffset] = restoreMBB
20785 // SjLjSetup restoreMBB
20791 // v = phi(main, restore)
20794 // if base pointer being used, load it from frame
20797 MachineBasicBlock *thisMBB = MBB;
20798 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20799 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20800 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20801 MF->insert(I, mainMBB);
20802 MF->insert(I, sinkMBB);
20803 MF->push_back(restoreMBB);
20805 MachineInstrBuilder MIB;
20807 // Transfer the remainder of BB and its successor edges to sinkMBB.
20808 sinkMBB->splice(sinkMBB->begin(), MBB,
20809 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20810 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20813 unsigned PtrStoreOpc = 0;
20814 unsigned LabelReg = 0;
20815 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20816 Reloc::Model RM = MF->getTarget().getRelocationModel();
20817 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20818 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20820 // Prepare IP either in reg or imm.
20821 if (!UseImmLabel) {
20822 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20823 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20824 LabelReg = MRI.createVirtualRegister(PtrRC);
20825 if (Subtarget->is64Bit()) {
20826 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20830 .addMBB(restoreMBB)
20833 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20834 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20835 .addReg(XII->getGlobalBaseReg(MF))
20838 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20842 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20844 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20845 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20846 if (i == X86::AddrDisp)
20847 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20849 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20852 MIB.addReg(LabelReg);
20854 MIB.addMBB(restoreMBB);
20855 MIB.setMemRefs(MMOBegin, MMOEnd);
20857 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20858 .addMBB(restoreMBB);
20860 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20861 MIB.addRegMask(RegInfo->getNoPreservedMask());
20862 thisMBB->addSuccessor(mainMBB);
20863 thisMBB->addSuccessor(restoreMBB);
20867 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20868 mainMBB->addSuccessor(sinkMBB);
20871 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20872 TII->get(X86::PHI), DstReg)
20873 .addReg(mainDstReg).addMBB(mainMBB)
20874 .addReg(restoreDstReg).addMBB(restoreMBB);
20877 if (RegInfo->hasBasePointer(*MF)) {
20878 const bool Uses64BitFramePtr =
20879 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20880 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20881 X86FI->setRestoreBasePointer(MF);
20882 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20883 unsigned BasePtr = RegInfo->getBaseRegister();
20884 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20885 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20886 FramePtr, true, X86FI->getRestoreBasePointerOffset())
20887 .setMIFlag(MachineInstr::FrameSetup);
20889 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20890 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20891 restoreMBB->addSuccessor(sinkMBB);
20893 MI->eraseFromParent();
20897 MachineBasicBlock *
20898 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20899 MachineBasicBlock *MBB) const {
20900 DebugLoc DL = MI->getDebugLoc();
20901 MachineFunction *MF = MBB->getParent();
20902 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20903 MachineRegisterInfo &MRI = MF->getRegInfo();
20905 // Memory Reference
20906 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20907 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20909 MVT PVT = getPointerTy(MF->getDataLayout());
20910 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20911 "Invalid Pointer Size!");
20913 const TargetRegisterClass *RC =
20914 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20915 unsigned Tmp = MRI.createVirtualRegister(RC);
20916 // Since FP is only updated here but NOT referenced, it's treated as GPR.
20917 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20918 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20919 unsigned SP = RegInfo->getStackRegister();
20921 MachineInstrBuilder MIB;
20923 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20924 const int64_t SPOffset = 2 * PVT.getStoreSize();
20926 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20927 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20930 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20931 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20932 MIB.addOperand(MI->getOperand(i));
20933 MIB.setMemRefs(MMOBegin, MMOEnd);
20935 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20936 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20937 if (i == X86::AddrDisp)
20938 MIB.addDisp(MI->getOperand(i), LabelOffset);
20940 MIB.addOperand(MI->getOperand(i));
20942 MIB.setMemRefs(MMOBegin, MMOEnd);
20944 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20945 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20946 if (i == X86::AddrDisp)
20947 MIB.addDisp(MI->getOperand(i), SPOffset);
20949 MIB.addOperand(MI->getOperand(i));
20951 MIB.setMemRefs(MMOBegin, MMOEnd);
20953 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20955 MI->eraseFromParent();
20959 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20960 // accumulator loops. Writing back to the accumulator allows the coalescer
20961 // to remove extra copies in the loop.
20962 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
20963 MachineBasicBlock *
20964 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20965 MachineBasicBlock *MBB) const {
20966 MachineOperand &AddendOp = MI->getOperand(3);
20968 // Bail out early if the addend isn't a register - we can't switch these.
20969 if (!AddendOp.isReg())
20972 MachineFunction &MF = *MBB->getParent();
20973 MachineRegisterInfo &MRI = MF.getRegInfo();
20975 // Check whether the addend is defined by a PHI:
20976 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20977 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20978 if (!AddendDef.isPHI())
20981 // Look for the following pattern:
20983 // %addend = phi [%entry, 0], [%loop, %result]
20985 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20989 // %addend = phi [%entry, 0], [%loop, %result]
20991 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20993 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20994 assert(AddendDef.getOperand(i).isReg());
20995 MachineOperand PHISrcOp = AddendDef.getOperand(i);
20996 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20997 if (&PHISrcInst == MI) {
20998 // Found a matching instruction.
20999 unsigned NewFMAOpc = 0;
21000 switch (MI->getOpcode()) {
21001 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
21002 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
21003 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
21004 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
21005 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
21006 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
21007 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
21008 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
21009 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
21010 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
21011 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
21012 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
21013 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
21014 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
21015 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
21016 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
21017 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
21018 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
21019 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
21020 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
21022 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
21023 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
21024 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
21025 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
21026 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
21027 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
21028 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
21029 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
21030 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
21031 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
21032 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
21033 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
21034 default: llvm_unreachable("Unrecognized FMA variant.");
21037 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21038 MachineInstrBuilder MIB =
21039 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
21040 .addOperand(MI->getOperand(0))
21041 .addOperand(MI->getOperand(3))
21042 .addOperand(MI->getOperand(2))
21043 .addOperand(MI->getOperand(1));
21044 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
21045 MI->eraseFromParent();
21052 MachineBasicBlock *
21053 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
21054 MachineBasicBlock *BB) const {
21055 switch (MI->getOpcode()) {
21056 default: llvm_unreachable("Unexpected instr type to insert");
21057 case X86::TAILJMPd64:
21058 case X86::TAILJMPr64:
21059 case X86::TAILJMPm64:
21060 case X86::TAILJMPd64_REX:
21061 case X86::TAILJMPr64_REX:
21062 case X86::TAILJMPm64_REX:
21063 llvm_unreachable("TAILJMP64 would not be touched here.");
21064 case X86::TCRETURNdi64:
21065 case X86::TCRETURNri64:
21066 case X86::TCRETURNmi64:
21068 case X86::WIN_ALLOCA:
21069 return EmitLoweredWinAlloca(MI, BB);
21070 case X86::SEG_ALLOCA_32:
21071 case X86::SEG_ALLOCA_64:
21072 return EmitLoweredSegAlloca(MI, BB);
21073 case X86::TLSCall_32:
21074 case X86::TLSCall_64:
21075 return EmitLoweredTLSCall(MI, BB);
21076 case X86::CMOV_FR32:
21077 case X86::CMOV_FR64:
21078 case X86::CMOV_GR8:
21079 case X86::CMOV_GR16:
21080 case X86::CMOV_GR32:
21081 case X86::CMOV_RFP32:
21082 case X86::CMOV_RFP64:
21083 case X86::CMOV_RFP80:
21084 case X86::CMOV_V2F64:
21085 case X86::CMOV_V2I64:
21086 case X86::CMOV_V4F32:
21087 case X86::CMOV_V4F64:
21088 case X86::CMOV_V4I64:
21089 case X86::CMOV_V16F32:
21090 case X86::CMOV_V8F32:
21091 case X86::CMOV_V8F64:
21092 case X86::CMOV_V8I64:
21093 case X86::CMOV_V8I1:
21094 case X86::CMOV_V16I1:
21095 case X86::CMOV_V32I1:
21096 case X86::CMOV_V64I1:
21097 return EmitLoweredSelect(MI, BB);
21099 case X86::RELEASE_FADD32mr:
21100 case X86::RELEASE_FADD64mr:
21101 return EmitLoweredAtomicFP(MI, BB);
21103 case X86::FP32_TO_INT16_IN_MEM:
21104 case X86::FP32_TO_INT32_IN_MEM:
21105 case X86::FP32_TO_INT64_IN_MEM:
21106 case X86::FP64_TO_INT16_IN_MEM:
21107 case X86::FP64_TO_INT32_IN_MEM:
21108 case X86::FP64_TO_INT64_IN_MEM:
21109 case X86::FP80_TO_INT16_IN_MEM:
21110 case X86::FP80_TO_INT32_IN_MEM:
21111 case X86::FP80_TO_INT64_IN_MEM: {
21112 MachineFunction *F = BB->getParent();
21113 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21114 DebugLoc DL = MI->getDebugLoc();
21116 // Change the floating point control register to use "round towards zero"
21117 // mode when truncating to an integer value.
21118 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
21119 addFrameReference(BuildMI(*BB, MI, DL,
21120 TII->get(X86::FNSTCW16m)), CWFrameIdx);
21122 // Load the old value of the high byte of the control word...
21124 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
21125 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
21128 // Set the high part to be round to zero...
21129 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
21132 // Reload the modified control word now...
21133 addFrameReference(BuildMI(*BB, MI, DL,
21134 TII->get(X86::FLDCW16m)), CWFrameIdx);
21136 // Restore the memory image of control word to original value
21137 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
21140 // Get the X86 opcode to use.
21142 switch (MI->getOpcode()) {
21143 default: llvm_unreachable("illegal opcode!");
21144 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
21145 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
21146 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
21147 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
21148 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
21149 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
21150 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
21151 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
21152 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
21156 MachineOperand &Op = MI->getOperand(0);
21158 AM.BaseType = X86AddressMode::RegBase;
21159 AM.Base.Reg = Op.getReg();
21161 AM.BaseType = X86AddressMode::FrameIndexBase;
21162 AM.Base.FrameIndex = Op.getIndex();
21164 Op = MI->getOperand(1);
21166 AM.Scale = Op.getImm();
21167 Op = MI->getOperand(2);
21169 AM.IndexReg = Op.getImm();
21170 Op = MI->getOperand(3);
21171 if (Op.isGlobal()) {
21172 AM.GV = Op.getGlobal();
21174 AM.Disp = Op.getImm();
21176 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
21177 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
21179 // Reload the original control word now.
21180 addFrameReference(BuildMI(*BB, MI, DL,
21181 TII->get(X86::FLDCW16m)), CWFrameIdx);
21183 MI->eraseFromParent(); // The pseudo instruction is gone now.
21186 // String/text processing lowering.
21187 case X86::PCMPISTRM128REG:
21188 case X86::VPCMPISTRM128REG:
21189 case X86::PCMPISTRM128MEM:
21190 case X86::VPCMPISTRM128MEM:
21191 case X86::PCMPESTRM128REG:
21192 case X86::VPCMPESTRM128REG:
21193 case X86::PCMPESTRM128MEM:
21194 case X86::VPCMPESTRM128MEM:
21195 assert(Subtarget->hasSSE42() &&
21196 "Target must have SSE4.2 or AVX features enabled");
21197 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
21199 // String/text processing lowering.
21200 case X86::PCMPISTRIREG:
21201 case X86::VPCMPISTRIREG:
21202 case X86::PCMPISTRIMEM:
21203 case X86::VPCMPISTRIMEM:
21204 case X86::PCMPESTRIREG:
21205 case X86::VPCMPESTRIREG:
21206 case X86::PCMPESTRIMEM:
21207 case X86::VPCMPESTRIMEM:
21208 assert(Subtarget->hasSSE42() &&
21209 "Target must have SSE4.2 or AVX features enabled");
21210 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
21212 // Thread synchronization.
21214 return EmitMonitor(MI, BB, Subtarget);
21218 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
21220 case X86::VASTART_SAVE_XMM_REGS:
21221 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
21223 case X86::VAARG_64:
21224 return EmitVAARG64WithCustomInserter(MI, BB);
21226 case X86::EH_SjLj_SetJmp32:
21227 case X86::EH_SjLj_SetJmp64:
21228 return emitEHSjLjSetJmp(MI, BB);
21230 case X86::EH_SjLj_LongJmp32:
21231 case X86::EH_SjLj_LongJmp64:
21232 return emitEHSjLjLongJmp(MI, BB);
21234 case TargetOpcode::STATEPOINT:
21235 // As an implementation detail, STATEPOINT shares the STACKMAP format at
21236 // this point in the process. We diverge later.
21237 return emitPatchPoint(MI, BB);
21239 case TargetOpcode::STACKMAP:
21240 case TargetOpcode::PATCHPOINT:
21241 return emitPatchPoint(MI, BB);
21243 case X86::VFMADDPDr213r:
21244 case X86::VFMADDPSr213r:
21245 case X86::VFMADDSDr213r:
21246 case X86::VFMADDSSr213r:
21247 case X86::VFMSUBPDr213r:
21248 case X86::VFMSUBPSr213r:
21249 case X86::VFMSUBSDr213r:
21250 case X86::VFMSUBSSr213r:
21251 case X86::VFNMADDPDr213r:
21252 case X86::VFNMADDPSr213r:
21253 case X86::VFNMADDSDr213r:
21254 case X86::VFNMADDSSr213r:
21255 case X86::VFNMSUBPDr213r:
21256 case X86::VFNMSUBPSr213r:
21257 case X86::VFNMSUBSDr213r:
21258 case X86::VFNMSUBSSr213r:
21259 case X86::VFMADDSUBPDr213r:
21260 case X86::VFMADDSUBPSr213r:
21261 case X86::VFMSUBADDPDr213r:
21262 case X86::VFMSUBADDPSr213r:
21263 case X86::VFMADDPDr213rY:
21264 case X86::VFMADDPSr213rY:
21265 case X86::VFMSUBPDr213rY:
21266 case X86::VFMSUBPSr213rY:
21267 case X86::VFNMADDPDr213rY:
21268 case X86::VFNMADDPSr213rY:
21269 case X86::VFNMSUBPDr213rY:
21270 case X86::VFNMSUBPSr213rY:
21271 case X86::VFMADDSUBPDr213rY:
21272 case X86::VFMADDSUBPSr213rY:
21273 case X86::VFMSUBADDPDr213rY:
21274 case X86::VFMSUBADDPSr213rY:
21275 return emitFMA3Instr(MI, BB);
21279 //===----------------------------------------------------------------------===//
21280 // X86 Optimization Hooks
21281 //===----------------------------------------------------------------------===//
21283 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21286 const SelectionDAG &DAG,
21287 unsigned Depth) const {
21288 unsigned BitWidth = KnownZero.getBitWidth();
21289 unsigned Opc = Op.getOpcode();
21290 assert((Opc >= ISD::BUILTIN_OP_END ||
21291 Opc == ISD::INTRINSIC_WO_CHAIN ||
21292 Opc == ISD::INTRINSIC_W_CHAIN ||
21293 Opc == ISD::INTRINSIC_VOID) &&
21294 "Should use MaskedValueIsZero if you don't know whether Op"
21295 " is a target node!");
21297 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
21311 // These nodes' second result is a boolean.
21312 if (Op.getResNo() == 0)
21315 case X86ISD::SETCC:
21316 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21318 case ISD::INTRINSIC_WO_CHAIN: {
21319 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21320 unsigned NumLoBits = 0;
21323 case Intrinsic::x86_sse_movmsk_ps:
21324 case Intrinsic::x86_avx_movmsk_ps_256:
21325 case Intrinsic::x86_sse2_movmsk_pd:
21326 case Intrinsic::x86_avx_movmsk_pd_256:
21327 case Intrinsic::x86_mmx_pmovmskb:
21328 case Intrinsic::x86_sse2_pmovmskb_128:
21329 case Intrinsic::x86_avx2_pmovmskb: {
21330 // High bits of movmskp{s|d}, pmovmskb are known zero.
21332 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
21333 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
21334 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
21335 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
21336 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
21337 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
21338 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
21339 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
21341 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21350 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21352 const SelectionDAG &,
21353 unsigned Depth) const {
21354 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21355 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21356 return Op.getValueType().getScalarType().getSizeInBits();
21362 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21363 /// node is a GlobalAddress + offset.
21364 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21365 const GlobalValue* &GA,
21366 int64_t &Offset) const {
21367 if (N->getOpcode() == X86ISD::Wrapper) {
21368 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21369 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21370 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21374 return TargetLowering::isGAPlusOffset(N, GA, Offset);
21377 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21378 /// same as extracting the high 128-bit part of 256-bit vector and then
21379 /// inserting the result into the low part of a new 256-bit vector
21380 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21381 EVT VT = SVOp->getValueType(0);
21382 unsigned NumElems = VT.getVectorNumElements();
21384 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21385 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21386 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21387 SVOp->getMaskElt(j) >= 0)
21393 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21394 /// same as extracting the low 128-bit part of 256-bit vector and then
21395 /// inserting the result into the high part of a new 256-bit vector
21396 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21397 EVT VT = SVOp->getValueType(0);
21398 unsigned NumElems = VT.getVectorNumElements();
21400 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21401 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21402 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21403 SVOp->getMaskElt(j) >= 0)
21409 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21410 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21411 TargetLowering::DAGCombinerInfo &DCI,
21412 const X86Subtarget* Subtarget) {
21414 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21415 SDValue V1 = SVOp->getOperand(0);
21416 SDValue V2 = SVOp->getOperand(1);
21417 EVT VT = SVOp->getValueType(0);
21418 unsigned NumElems = VT.getVectorNumElements();
21420 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21421 V2.getOpcode() == ISD::CONCAT_VECTORS) {
21425 // V UNDEF BUILD_VECTOR UNDEF
21427 // CONCAT_VECTOR CONCAT_VECTOR
21430 // RESULT: V + zero extended
21432 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21433 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21434 V1.getOperand(1).getOpcode() != ISD::UNDEF)
21437 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21440 // To match the shuffle mask, the first half of the mask should
21441 // be exactly the first vector, and all the rest a splat with the
21442 // first element of the second one.
21443 for (unsigned i = 0; i != NumElems/2; ++i)
21444 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21445 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21448 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21449 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21450 if (Ld->hasNUsesOfValue(1, 0)) {
21451 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21452 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21454 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21456 Ld->getPointerInfo(),
21457 Ld->getAlignment(),
21458 false/*isVolatile*/, true/*ReadMem*/,
21459 false/*WriteMem*/);
21461 // Make sure the newly-created LOAD is in the same position as Ld in
21462 // terms of dependency. We create a TokenFactor for Ld and ResNode,
21463 // and update uses of Ld's output chain to use the TokenFactor.
21464 if (Ld->hasAnyUseOfValue(1)) {
21465 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21466 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21467 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21468 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21469 SDValue(ResNode.getNode(), 1));
21472 return DAG.getBitcast(VT, ResNode);
21476 // Emit a zeroed vector and insert the desired subvector on its
21478 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21479 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21480 return DCI.CombineTo(N, InsV);
21483 //===--------------------------------------------------------------------===//
21484 // Combine some shuffles into subvector extracts and inserts:
21487 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21488 if (isShuffleHigh128VectorInsertLow(SVOp)) {
21489 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21490 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21491 return DCI.CombineTo(N, InsV);
21494 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21495 if (isShuffleLow128VectorInsertHigh(SVOp)) {
21496 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21497 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21498 return DCI.CombineTo(N, InsV);
21504 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21507 /// This is the leaf of the recursive combinine below. When we have found some
21508 /// chain of single-use x86 shuffle instructions and accumulated the combined
21509 /// shuffle mask represented by them, this will try to pattern match that mask
21510 /// into either a single instruction if there is a special purpose instruction
21511 /// for this operation, or into a PSHUFB instruction which is a fully general
21512 /// instruction but should only be used to replace chains over a certain depth.
21513 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21514 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21515 TargetLowering::DAGCombinerInfo &DCI,
21516 const X86Subtarget *Subtarget) {
21517 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21519 // Find the operand that enters the chain. Note that multiple uses are OK
21520 // here, we're not going to remove the operand we find.
21521 SDValue Input = Op.getOperand(0);
21522 while (Input.getOpcode() == ISD::BITCAST)
21523 Input = Input.getOperand(0);
21525 MVT VT = Input.getSimpleValueType();
21526 MVT RootVT = Root.getSimpleValueType();
21529 // Just remove no-op shuffle masks.
21530 if (Mask.size() == 1) {
21531 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21536 // Use the float domain if the operand type is a floating point type.
21537 bool FloatDomain = VT.isFloatingPoint();
21539 // For floating point shuffles, we don't have free copies in the shuffle
21540 // instructions or the ability to load as part of the instruction, so
21541 // canonicalize their shuffles to UNPCK or MOV variants.
21543 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21544 // vectors because it can have a load folded into it that UNPCK cannot. This
21545 // doesn't preclude something switching to the shorter encoding post-RA.
21547 // FIXME: Should teach these routines about AVX vector widths.
21548 if (FloatDomain && VT.getSizeInBits() == 128) {
21549 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21550 bool Lo = Mask.equals({0, 0});
21553 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21554 // is no slower than UNPCKLPD but has the option to fold the input operand
21555 // into even an unaligned memory load.
21556 if (Lo && Subtarget->hasSSE3()) {
21557 Shuffle = X86ISD::MOVDDUP;
21558 ShuffleVT = MVT::v2f64;
21560 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21561 // than the UNPCK variants.
21562 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21563 ShuffleVT = MVT::v4f32;
21565 if (Depth == 1 && Root->getOpcode() == Shuffle)
21566 return false; // Nothing to do!
21567 Op = DAG.getBitcast(ShuffleVT, Input);
21568 DCI.AddToWorklist(Op.getNode());
21569 if (Shuffle == X86ISD::MOVDDUP)
21570 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21572 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21573 DCI.AddToWorklist(Op.getNode());
21574 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21578 if (Subtarget->hasSSE3() &&
21579 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21580 bool Lo = Mask.equals({0, 0, 2, 2});
21581 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21582 MVT ShuffleVT = MVT::v4f32;
21583 if (Depth == 1 && Root->getOpcode() == Shuffle)
21584 return false; // Nothing to do!
21585 Op = DAG.getBitcast(ShuffleVT, Input);
21586 DCI.AddToWorklist(Op.getNode());
21587 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21588 DCI.AddToWorklist(Op.getNode());
21589 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21593 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21594 bool Lo = Mask.equals({0, 0, 1, 1});
21595 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21596 MVT ShuffleVT = MVT::v4f32;
21597 if (Depth == 1 && Root->getOpcode() == Shuffle)
21598 return false; // Nothing to do!
21599 Op = DAG.getBitcast(ShuffleVT, Input);
21600 DCI.AddToWorklist(Op.getNode());
21601 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21602 DCI.AddToWorklist(Op.getNode());
21603 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21609 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21610 // variants as none of these have single-instruction variants that are
21611 // superior to the UNPCK formulation.
21612 if (!FloatDomain && VT.getSizeInBits() == 128 &&
21613 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21614 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21615 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21617 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21618 bool Lo = Mask[0] == 0;
21619 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21620 if (Depth == 1 && Root->getOpcode() == Shuffle)
21621 return false; // Nothing to do!
21623 switch (Mask.size()) {
21625 ShuffleVT = MVT::v8i16;
21628 ShuffleVT = MVT::v16i8;
21631 llvm_unreachable("Impossible mask size!");
21633 Op = DAG.getBitcast(ShuffleVT, Input);
21634 DCI.AddToWorklist(Op.getNode());
21635 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21636 DCI.AddToWorklist(Op.getNode());
21637 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21642 // Don't try to re-form single instruction chains under any circumstances now
21643 // that we've done encoding canonicalization for them.
21647 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21648 // can replace them with a single PSHUFB instruction profitably. Intel's
21649 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21650 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21651 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21652 SmallVector<SDValue, 16> PSHUFBMask;
21653 int NumBytes = VT.getSizeInBits() / 8;
21654 int Ratio = NumBytes / Mask.size();
21655 for (int i = 0; i < NumBytes; ++i) {
21656 if (Mask[i / Ratio] == SM_SentinelUndef) {
21657 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21660 int M = Mask[i / Ratio] != SM_SentinelZero
21661 ? Ratio * Mask[i / Ratio] + i % Ratio
21663 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21665 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21666 Op = DAG.getBitcast(ByteVT, Input);
21667 DCI.AddToWorklist(Op.getNode());
21668 SDValue PSHUFBMaskOp =
21669 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21670 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21671 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21672 DCI.AddToWorklist(Op.getNode());
21673 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21678 // Failed to find any combines.
21682 /// \brief Fully generic combining of x86 shuffle instructions.
21684 /// This should be the last combine run over the x86 shuffle instructions. Once
21685 /// they have been fully optimized, this will recursively consider all chains
21686 /// of single-use shuffle instructions, build a generic model of the cumulative
21687 /// shuffle operation, and check for simpler instructions which implement this
21688 /// operation. We use this primarily for two purposes:
21690 /// 1) Collapse generic shuffles to specialized single instructions when
21691 /// equivalent. In most cases, this is just an encoding size win, but
21692 /// sometimes we will collapse multiple generic shuffles into a single
21693 /// special-purpose shuffle.
21694 /// 2) Look for sequences of shuffle instructions with 3 or more total
21695 /// instructions, and replace them with the slightly more expensive SSSE3
21696 /// PSHUFB instruction if available. We do this as the last combining step
21697 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
21698 /// a suitable short sequence of other instructions. The PHUFB will either
21699 /// use a register or have to read from memory and so is slightly (but only
21700 /// slightly) more expensive than the other shuffle instructions.
21702 /// Because this is inherently a quadratic operation (for each shuffle in
21703 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21704 /// This should never be an issue in practice as the shuffle lowering doesn't
21705 /// produce sequences of more than 8 instructions.
21707 /// FIXME: We will currently miss some cases where the redundant shuffling
21708 /// would simplify under the threshold for PSHUFB formation because of
21709 /// combine-ordering. To fix this, we should do the redundant instruction
21710 /// combining in this recursive walk.
21711 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21712 ArrayRef<int> RootMask,
21713 int Depth, bool HasPSHUFB,
21715 TargetLowering::DAGCombinerInfo &DCI,
21716 const X86Subtarget *Subtarget) {
21717 // Bound the depth of our recursive combine because this is ultimately
21718 // quadratic in nature.
21722 // Directly rip through bitcasts to find the underlying operand.
21723 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21724 Op = Op.getOperand(0);
21726 MVT VT = Op.getSimpleValueType();
21727 if (!VT.isVector())
21728 return false; // Bail if we hit a non-vector.
21730 assert(Root.getSimpleValueType().isVector() &&
21731 "Shuffles operate on vector types!");
21732 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21733 "Can only combine shuffles of the same vector register size.");
21735 if (!isTargetShuffle(Op.getOpcode()))
21737 SmallVector<int, 16> OpMask;
21739 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21740 // We only can combine unary shuffles which we can decode the mask for.
21741 if (!HaveMask || !IsUnary)
21744 assert(VT.getVectorNumElements() == OpMask.size() &&
21745 "Different mask size from vector size!");
21746 assert(((RootMask.size() > OpMask.size() &&
21747 RootMask.size() % OpMask.size() == 0) ||
21748 (OpMask.size() > RootMask.size() &&
21749 OpMask.size() % RootMask.size() == 0) ||
21750 OpMask.size() == RootMask.size()) &&
21751 "The smaller number of elements must divide the larger.");
21752 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21753 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21754 assert(((RootRatio == 1 && OpRatio == 1) ||
21755 (RootRatio == 1) != (OpRatio == 1)) &&
21756 "Must not have a ratio for both incoming and op masks!");
21758 SmallVector<int, 16> Mask;
21759 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21761 // Merge this shuffle operation's mask into our accumulated mask. Note that
21762 // this shuffle's mask will be the first applied to the input, followed by the
21763 // root mask to get us all the way to the root value arrangement. The reason
21764 // for this order is that we are recursing up the operation chain.
21765 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21766 int RootIdx = i / RootRatio;
21767 if (RootMask[RootIdx] < 0) {
21768 // This is a zero or undef lane, we're done.
21769 Mask.push_back(RootMask[RootIdx]);
21773 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21774 int OpIdx = RootMaskedIdx / OpRatio;
21775 if (OpMask[OpIdx] < 0) {
21776 // The incoming lanes are zero or undef, it doesn't matter which ones we
21778 Mask.push_back(OpMask[OpIdx]);
21782 // Ok, we have non-zero lanes, map them through.
21783 Mask.push_back(OpMask[OpIdx] * OpRatio +
21784 RootMaskedIdx % OpRatio);
21787 // See if we can recurse into the operand to combine more things.
21788 switch (Op.getOpcode()) {
21789 case X86ISD::PSHUFB:
21791 case X86ISD::PSHUFD:
21792 case X86ISD::PSHUFHW:
21793 case X86ISD::PSHUFLW:
21794 if (Op.getOperand(0).hasOneUse() &&
21795 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21796 HasPSHUFB, DAG, DCI, Subtarget))
21800 case X86ISD::UNPCKL:
21801 case X86ISD::UNPCKH:
21802 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21803 // We can't check for single use, we have to check that this shuffle is the only user.
21804 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21805 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21806 HasPSHUFB, DAG, DCI, Subtarget))
21811 // Minor canonicalization of the accumulated shuffle mask to make it easier
21812 // to match below. All this does is detect masks with squential pairs of
21813 // elements, and shrink them to the half-width mask. It does this in a loop
21814 // so it will reduce the size of the mask to the minimal width mask which
21815 // performs an equivalent shuffle.
21816 SmallVector<int, 16> WidenedMask;
21817 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21818 Mask = std::move(WidenedMask);
21819 WidenedMask.clear();
21822 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21826 /// \brief Get the PSHUF-style mask from PSHUF node.
21828 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21829 /// PSHUF-style masks that can be reused with such instructions.
21830 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21831 MVT VT = N.getSimpleValueType();
21832 SmallVector<int, 4> Mask;
21834 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21838 // If we have more than 128-bits, only the low 128-bits of shuffle mask
21839 // matter. Check that the upper masks are repeats and remove them.
21840 if (VT.getSizeInBits() > 128) {
21841 int LaneElts = 128 / VT.getScalarSizeInBits();
21843 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21844 for (int j = 0; j < LaneElts; ++j)
21845 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21846 "Mask doesn't repeat in high 128-bit lanes!");
21848 Mask.resize(LaneElts);
21851 switch (N.getOpcode()) {
21852 case X86ISD::PSHUFD:
21854 case X86ISD::PSHUFLW:
21857 case X86ISD::PSHUFHW:
21858 Mask.erase(Mask.begin(), Mask.begin() + 4);
21859 for (int &M : Mask)
21863 llvm_unreachable("No valid shuffle instruction found!");
21867 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21869 /// We walk up the chain and look for a combinable shuffle, skipping over
21870 /// shuffles that we could hoist this shuffle's transformation past without
21871 /// altering anything.
21873 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21875 TargetLowering::DAGCombinerInfo &DCI) {
21876 assert(N.getOpcode() == X86ISD::PSHUFD &&
21877 "Called with something other than an x86 128-bit half shuffle!");
21880 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21881 // of the shuffles in the chain so that we can form a fresh chain to replace
21883 SmallVector<SDValue, 8> Chain;
21884 SDValue V = N.getOperand(0);
21885 for (; V.hasOneUse(); V = V.getOperand(0)) {
21886 switch (V.getOpcode()) {
21888 return SDValue(); // Nothing combined!
21891 // Skip bitcasts as we always know the type for the target specific
21895 case X86ISD::PSHUFD:
21896 // Found another dword shuffle.
21899 case X86ISD::PSHUFLW:
21900 // Check that the low words (being shuffled) are the identity in the
21901 // dword shuffle, and the high words are self-contained.
21902 if (Mask[0] != 0 || Mask[1] != 1 ||
21903 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21906 Chain.push_back(V);
21909 case X86ISD::PSHUFHW:
21910 // Check that the high words (being shuffled) are the identity in the
21911 // dword shuffle, and the low words are self-contained.
21912 if (Mask[2] != 2 || Mask[3] != 3 ||
21913 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21916 Chain.push_back(V);
21919 case X86ISD::UNPCKL:
21920 case X86ISD::UNPCKH:
21921 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21922 // shuffle into a preceding word shuffle.
21923 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21924 V.getSimpleValueType().getScalarType() != MVT::i16)
21927 // Search for a half-shuffle which we can combine with.
21928 unsigned CombineOp =
21929 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21930 if (V.getOperand(0) != V.getOperand(1) ||
21931 !V->isOnlyUserOf(V.getOperand(0).getNode()))
21933 Chain.push_back(V);
21934 V = V.getOperand(0);
21936 switch (V.getOpcode()) {
21938 return SDValue(); // Nothing to combine.
21940 case X86ISD::PSHUFLW:
21941 case X86ISD::PSHUFHW:
21942 if (V.getOpcode() == CombineOp)
21945 Chain.push_back(V);
21949 V = V.getOperand(0);
21953 } while (V.hasOneUse());
21956 // Break out of the loop if we break out of the switch.
21960 if (!V.hasOneUse())
21961 // We fell out of the loop without finding a viable combining instruction.
21964 // Merge this node's mask and our incoming mask.
21965 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21966 for (int &M : Mask)
21968 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21969 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21971 // Rebuild the chain around this new shuffle.
21972 while (!Chain.empty()) {
21973 SDValue W = Chain.pop_back_val();
21975 if (V.getValueType() != W.getOperand(0).getValueType())
21976 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21978 switch (W.getOpcode()) {
21980 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21982 case X86ISD::UNPCKL:
21983 case X86ISD::UNPCKH:
21984 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21987 case X86ISD::PSHUFD:
21988 case X86ISD::PSHUFLW:
21989 case X86ISD::PSHUFHW:
21990 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21994 if (V.getValueType() != N.getValueType())
21995 V = DAG.getBitcast(N.getValueType(), V);
21997 // Return the new chain to replace N.
22001 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
22003 /// We walk up the chain, skipping shuffles of the other half and looking
22004 /// through shuffles which switch halves trying to find a shuffle of the same
22005 /// pair of dwords.
22006 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
22008 TargetLowering::DAGCombinerInfo &DCI) {
22010 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
22011 "Called with something other than an x86 128-bit half shuffle!");
22013 unsigned CombineOpcode = N.getOpcode();
22015 // Walk up a single-use chain looking for a combinable shuffle.
22016 SDValue V = N.getOperand(0);
22017 for (; V.hasOneUse(); V = V.getOperand(0)) {
22018 switch (V.getOpcode()) {
22020 return false; // Nothing combined!
22023 // Skip bitcasts as we always know the type for the target specific
22027 case X86ISD::PSHUFLW:
22028 case X86ISD::PSHUFHW:
22029 if (V.getOpcode() == CombineOpcode)
22032 // Other-half shuffles are no-ops.
22035 // Break out of the loop if we break out of the switch.
22039 if (!V.hasOneUse())
22040 // We fell out of the loop without finding a viable combining instruction.
22043 // Combine away the bottom node as its shuffle will be accumulated into
22044 // a preceding shuffle.
22045 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22047 // Record the old value.
22050 // Merge this node's mask and our incoming mask (adjusted to account for all
22051 // the pshufd instructions encountered).
22052 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22053 for (int &M : Mask)
22055 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
22056 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
22058 // Check that the shuffles didn't cancel each other out. If not, we need to
22059 // combine to the new one.
22061 // Replace the combinable shuffle with the combined one, updating all users
22062 // so that we re-evaluate the chain here.
22063 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
22068 /// \brief Try to combine x86 target specific shuffles.
22069 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
22070 TargetLowering::DAGCombinerInfo &DCI,
22071 const X86Subtarget *Subtarget) {
22073 MVT VT = N.getSimpleValueType();
22074 SmallVector<int, 4> Mask;
22076 switch (N.getOpcode()) {
22077 case X86ISD::PSHUFD:
22078 case X86ISD::PSHUFLW:
22079 case X86ISD::PSHUFHW:
22080 Mask = getPSHUFShuffleMask(N);
22081 assert(Mask.size() == 4);
22087 // Nuke no-op shuffles that show up after combining.
22088 if (isNoopShuffleMask(Mask))
22089 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
22091 // Look for simplifications involving one or two shuffle instructions.
22092 SDValue V = N.getOperand(0);
22093 switch (N.getOpcode()) {
22096 case X86ISD::PSHUFLW:
22097 case X86ISD::PSHUFHW:
22098 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
22100 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
22101 return SDValue(); // We combined away this shuffle, so we're done.
22103 // See if this reduces to a PSHUFD which is no more expensive and can
22104 // combine with more operations. Note that it has to at least flip the
22105 // dwords as otherwise it would have been removed as a no-op.
22106 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
22107 int DMask[] = {0, 1, 2, 3};
22108 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
22109 DMask[DOffset + 0] = DOffset + 1;
22110 DMask[DOffset + 1] = DOffset + 0;
22111 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
22112 V = DAG.getBitcast(DVT, V);
22113 DCI.AddToWorklist(V.getNode());
22114 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
22115 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
22116 DCI.AddToWorklist(V.getNode());
22117 return DAG.getBitcast(VT, V);
22120 // Look for shuffle patterns which can be implemented as a single unpack.
22121 // FIXME: This doesn't handle the location of the PSHUFD generically, and
22122 // only works when we have a PSHUFD followed by two half-shuffles.
22123 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
22124 (V.getOpcode() == X86ISD::PSHUFLW ||
22125 V.getOpcode() == X86ISD::PSHUFHW) &&
22126 V.getOpcode() != N.getOpcode() &&
22128 SDValue D = V.getOperand(0);
22129 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
22130 D = D.getOperand(0);
22131 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
22132 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
22133 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
22134 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22135 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
22137 for (int i = 0; i < 4; ++i) {
22138 WordMask[i + NOffset] = Mask[i] + NOffset;
22139 WordMask[i + VOffset] = VMask[i] + VOffset;
22141 // Map the word mask through the DWord mask.
22143 for (int i = 0; i < 8; ++i)
22144 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
22145 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22146 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
22147 // We can replace all three shuffles with an unpack.
22148 V = DAG.getBitcast(VT, D.getOperand(0));
22149 DCI.AddToWorklist(V.getNode());
22150 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
22159 case X86ISD::PSHUFD:
22160 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
22169 /// \brief Try to combine a shuffle into a target-specific add-sub node.
22171 /// We combine this directly on the abstract vector shuffle nodes so it is
22172 /// easier to generically match. We also insert dummy vector shuffle nodes for
22173 /// the operands which explicitly discard the lanes which are unused by this
22174 /// operation to try to flow through the rest of the combiner the fact that
22175 /// they're unused.
22176 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
22178 EVT VT = N->getValueType(0);
22180 // We only handle target-independent shuffles.
22181 // FIXME: It would be easy and harmless to use the target shuffle mask
22182 // extraction tool to support more.
22183 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
22186 auto *SVN = cast<ShuffleVectorSDNode>(N);
22187 ArrayRef<int> Mask = SVN->getMask();
22188 SDValue V1 = N->getOperand(0);
22189 SDValue V2 = N->getOperand(1);
22191 // We require the first shuffle operand to be the SUB node, and the second to
22192 // be the ADD node.
22193 // FIXME: We should support the commuted patterns.
22194 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
22197 // If there are other uses of these operations we can't fold them.
22198 if (!V1->hasOneUse() || !V2->hasOneUse())
22201 // Ensure that both operations have the same operands. Note that we can
22202 // commute the FADD operands.
22203 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
22204 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
22205 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
22208 // We're looking for blends between FADD and FSUB nodes. We insist on these
22209 // nodes being lined up in a specific expected pattern.
22210 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
22211 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
22212 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
22215 // Only specific types are legal at this point, assert so we notice if and
22216 // when these change.
22217 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
22218 VT == MVT::v4f64) &&
22219 "Unknown vector type encountered!");
22221 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
22224 /// PerformShuffleCombine - Performs several different shuffle combines.
22225 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
22226 TargetLowering::DAGCombinerInfo &DCI,
22227 const X86Subtarget *Subtarget) {
22229 SDValue N0 = N->getOperand(0);
22230 SDValue N1 = N->getOperand(1);
22231 EVT VT = N->getValueType(0);
22233 // Don't create instructions with illegal types after legalize types has run.
22234 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22235 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
22238 // If we have legalized the vector types, look for blends of FADD and FSUB
22239 // nodes that we can fuse into an ADDSUB node.
22240 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
22241 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22244 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22245 if (Subtarget->hasFp256() && VT.is256BitVector() &&
22246 N->getOpcode() == ISD::VECTOR_SHUFFLE)
22247 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22249 // During Type Legalization, when promoting illegal vector types,
22250 // the backend might introduce new shuffle dag nodes and bitcasts.
22252 // This code performs the following transformation:
22253 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22254 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22256 // We do this only if both the bitcast and the BINOP dag nodes have
22257 // one use. Also, perform this transformation only if the new binary
22258 // operation is legal. This is to avoid introducing dag nodes that
22259 // potentially need to be further expanded (or custom lowered) into a
22260 // less optimal sequence of dag nodes.
22261 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22262 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22263 N0.getOpcode() == ISD::BITCAST) {
22264 SDValue BC0 = N0.getOperand(0);
22265 EVT SVT = BC0.getValueType();
22266 unsigned Opcode = BC0.getOpcode();
22267 unsigned NumElts = VT.getVectorNumElements();
22269 if (BC0.hasOneUse() && SVT.isVector() &&
22270 SVT.getVectorNumElements() * 2 == NumElts &&
22271 TLI.isOperationLegal(Opcode, VT)) {
22272 bool CanFold = false;
22284 unsigned SVTNumElts = SVT.getVectorNumElements();
22285 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22286 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22287 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22288 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22289 CanFold = SVOp->getMaskElt(i) < 0;
22292 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22293 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22294 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22295 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22300 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22301 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22302 // consecutive, non-overlapping, and in the right order.
22303 SmallVector<SDValue, 16> Elts;
22304 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22305 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22307 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22310 if (isTargetShuffle(N->getOpcode())) {
22312 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22313 if (Shuffle.getNode())
22316 // Try recursively combining arbitrary sequences of x86 shuffle
22317 // instructions into higher-order shuffles. We do this after combining
22318 // specific PSHUF instruction sequences into their minimal form so that we
22319 // can evaluate how many specialized shuffle instructions are involved in
22320 // a particular chain.
22321 SmallVector<int, 1> NonceMask; // Just a placeholder.
22322 NonceMask.push_back(0);
22323 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22324 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22326 return SDValue(); // This routine will use CombineTo to replace N.
22332 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22333 /// specific shuffle of a load can be folded into a single element load.
22334 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22335 /// shuffles have been custom lowered so we need to handle those here.
22336 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22337 TargetLowering::DAGCombinerInfo &DCI) {
22338 if (DCI.isBeforeLegalizeOps())
22341 SDValue InVec = N->getOperand(0);
22342 SDValue EltNo = N->getOperand(1);
22344 if (!isa<ConstantSDNode>(EltNo))
22347 EVT OriginalVT = InVec.getValueType();
22349 if (InVec.getOpcode() == ISD::BITCAST) {
22350 // Don't duplicate a load with other uses.
22351 if (!InVec.hasOneUse())
22353 EVT BCVT = InVec.getOperand(0).getValueType();
22354 if (!BCVT.isVector() ||
22355 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22357 InVec = InVec.getOperand(0);
22360 EVT CurrentVT = InVec.getValueType();
22362 if (!isTargetShuffle(InVec.getOpcode()))
22365 // Don't duplicate a load with other uses.
22366 if (!InVec.hasOneUse())
22369 SmallVector<int, 16> ShuffleMask;
22371 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22372 ShuffleMask, UnaryShuffle))
22375 // Select the input vector, guarding against out of range extract vector.
22376 unsigned NumElems = CurrentVT.getVectorNumElements();
22377 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22378 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22379 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22380 : InVec.getOperand(1);
22382 // If inputs to shuffle are the same for both ops, then allow 2 uses
22383 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22384 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22386 if (LdNode.getOpcode() == ISD::BITCAST) {
22387 // Don't duplicate a load with other uses.
22388 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22391 AllowedUses = 1; // only allow 1 load use if we have a bitcast
22392 LdNode = LdNode.getOperand(0);
22395 if (!ISD::isNormalLoad(LdNode.getNode()))
22398 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22400 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22403 EVT EltVT = N->getValueType(0);
22404 // If there's a bitcast before the shuffle, check if the load type and
22405 // alignment is valid.
22406 unsigned Align = LN0->getAlignment();
22407 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22408 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22409 EltVT.getTypeForEVT(*DAG.getContext()));
22411 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22414 // All checks match so transform back to vector_shuffle so that DAG combiner
22415 // can finish the job
22418 // Create shuffle node taking into account the case that its a unary shuffle
22419 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22420 : InVec.getOperand(1);
22421 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22422 InVec.getOperand(0), Shuffle,
22424 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22425 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22429 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22430 /// special and don't usually play with other vector types, it's better to
22431 /// handle them early to be sure we emit efficient code by avoiding
22432 /// store-load conversions.
22433 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22434 if (N->getValueType(0) != MVT::x86mmx ||
22435 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22436 N->getOperand(0)->getValueType(0) != MVT::v2i32)
22439 SDValue V = N->getOperand(0);
22440 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22441 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22442 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22443 N->getValueType(0), V.getOperand(0));
22448 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22449 /// generation and convert it from being a bunch of shuffles and extracts
22450 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22451 /// storing the value and loading scalars back, while for x64 we should
22452 /// use 64-bit extracts and shifts.
22453 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22454 TargetLowering::DAGCombinerInfo &DCI) {
22455 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22458 SDValue InputVector = N->getOperand(0);
22459 SDLoc dl(InputVector);
22460 // Detect mmx to i32 conversion through a v2i32 elt extract.
22461 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22462 N->getValueType(0) == MVT::i32 &&
22463 InputVector.getValueType() == MVT::v2i32) {
22465 // The bitcast source is a direct mmx result.
22466 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22467 if (MMXSrc.getValueType() == MVT::x86mmx)
22468 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22469 N->getValueType(0),
22470 InputVector.getNode()->getOperand(0));
22472 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22473 SDValue MMXSrcOp = MMXSrc.getOperand(0);
22474 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22475 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22476 MMXSrcOp.getOpcode() == ISD::BITCAST &&
22477 MMXSrcOp.getValueType() == MVT::v1i64 &&
22478 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22479 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22480 N->getValueType(0),
22481 MMXSrcOp.getOperand(0));
22484 EVT VT = N->getValueType(0);
22486 if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22487 InputVector.getOpcode() == ISD::BITCAST &&
22488 dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22489 uint64_t ExtractedElt =
22490 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22491 uint64_t InputValue =
22492 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22493 uint64_t Res = (InputValue >> ExtractedElt) & 1;
22494 return DAG.getConstant(Res, dl, MVT::i1);
22496 // Only operate on vectors of 4 elements, where the alternative shuffling
22497 // gets to be more expensive.
22498 if (InputVector.getValueType() != MVT::v4i32)
22501 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22502 // single use which is a sign-extend or zero-extend, and all elements are
22504 SmallVector<SDNode *, 4> Uses;
22505 unsigned ExtractedElements = 0;
22506 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22507 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22508 if (UI.getUse().getResNo() != InputVector.getResNo())
22511 SDNode *Extract = *UI;
22512 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22515 if (Extract->getValueType(0) != MVT::i32)
22517 if (!Extract->hasOneUse())
22519 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22520 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22522 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22525 // Record which element was extracted.
22526 ExtractedElements |=
22527 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22529 Uses.push_back(Extract);
22532 // If not all the elements were used, this may not be worthwhile.
22533 if (ExtractedElements != 15)
22536 // Ok, we've now decided to do the transformation.
22537 // If 64-bit shifts are legal, use the extract-shift sequence,
22538 // otherwise bounce the vector off the cache.
22539 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22542 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22543 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22544 auto &DL = DAG.getDataLayout();
22545 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22546 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22547 DAG.getConstant(0, dl, VecIdxTy));
22548 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22549 DAG.getConstant(1, dl, VecIdxTy));
22551 SDValue ShAmt = DAG.getConstant(
22552 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22553 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22554 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22555 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22556 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22557 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22558 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22560 // Store the value to a temporary stack slot.
22561 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22562 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22563 MachinePointerInfo(), false, false, 0);
22565 EVT ElementType = InputVector.getValueType().getVectorElementType();
22566 unsigned EltSize = ElementType.getSizeInBits() / 8;
22568 // Replace each use (extract) with a load of the appropriate element.
22569 for (unsigned i = 0; i < 4; ++i) {
22570 uint64_t Offset = EltSize * i;
22571 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22572 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22574 SDValue ScalarAddr =
22575 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22577 // Load the scalar.
22578 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22579 ScalarAddr, MachinePointerInfo(),
22580 false, false, false, 0);
22585 // Replace the extracts
22586 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22587 UE = Uses.end(); UI != UE; ++UI) {
22588 SDNode *Extract = *UI;
22590 SDValue Idx = Extract->getOperand(1);
22591 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22592 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22595 // The replacement was made in place; don't return anything.
22600 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22601 const X86Subtarget *Subtarget) {
22603 SDValue Cond = N->getOperand(0);
22604 SDValue LHS = N->getOperand(1);
22605 SDValue RHS = N->getOperand(2);
22607 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22608 SDValue CondSrc = Cond->getOperand(0);
22609 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22610 Cond = CondSrc->getOperand(0);
22613 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22616 // A vselect where all conditions and data are constants can be optimized into
22617 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22618 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22619 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22622 unsigned MaskValue = 0;
22623 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22626 MVT VT = N->getSimpleValueType(0);
22627 unsigned NumElems = VT.getVectorNumElements();
22628 SmallVector<int, 8> ShuffleMask(NumElems, -1);
22629 for (unsigned i = 0; i < NumElems; ++i) {
22630 // Be sure we emit undef where we can.
22631 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22632 ShuffleMask[i] = -1;
22634 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22637 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22638 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22640 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22643 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22645 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22646 TargetLowering::DAGCombinerInfo &DCI,
22647 const X86Subtarget *Subtarget) {
22649 SDValue Cond = N->getOperand(0);
22650 // Get the LHS/RHS of the select.
22651 SDValue LHS = N->getOperand(1);
22652 SDValue RHS = N->getOperand(2);
22653 EVT VT = LHS.getValueType();
22654 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22656 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22657 // instructions match the semantics of the common C idiom x<y?x:y but not
22658 // x<=y?x:y, because of how they handle negative zero (which can be
22659 // ignored in unsafe-math mode).
22660 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22661 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22662 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22663 (Subtarget->hasSSE2() ||
22664 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22665 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22667 unsigned Opcode = 0;
22668 // Check for x CC y ? x : y.
22669 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22670 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22674 // Converting this to a min would handle NaNs incorrectly, and swapping
22675 // the operands would cause it to handle comparisons between positive
22676 // and negative zero incorrectly.
22677 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22678 if (!DAG.getTarget().Options.UnsafeFPMath &&
22679 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22681 std::swap(LHS, RHS);
22683 Opcode = X86ISD::FMIN;
22686 // Converting this to a min would handle comparisons between positive
22687 // and negative zero incorrectly.
22688 if (!DAG.getTarget().Options.UnsafeFPMath &&
22689 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22691 Opcode = X86ISD::FMIN;
22694 // Converting this to a min would handle both negative zeros and NaNs
22695 // incorrectly, but we can swap the operands to fix both.
22696 std::swap(LHS, RHS);
22700 Opcode = X86ISD::FMIN;
22704 // Converting this to a max would handle comparisons between positive
22705 // and negative zero incorrectly.
22706 if (!DAG.getTarget().Options.UnsafeFPMath &&
22707 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22709 Opcode = X86ISD::FMAX;
22712 // Converting this to a max would handle NaNs incorrectly, and swapping
22713 // the operands would cause it to handle comparisons between positive
22714 // and negative zero incorrectly.
22715 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22716 if (!DAG.getTarget().Options.UnsafeFPMath &&
22717 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22719 std::swap(LHS, RHS);
22721 Opcode = X86ISD::FMAX;
22724 // Converting this to a max would handle both negative zeros and NaNs
22725 // incorrectly, but we can swap the operands to fix both.
22726 std::swap(LHS, RHS);
22730 Opcode = X86ISD::FMAX;
22733 // Check for x CC y ? y : x -- a min/max with reversed arms.
22734 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22735 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22739 // Converting this to a min would handle comparisons between positive
22740 // and negative zero incorrectly, and swapping the operands would
22741 // cause it to handle NaNs incorrectly.
22742 if (!DAG.getTarget().Options.UnsafeFPMath &&
22743 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22744 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22746 std::swap(LHS, RHS);
22748 Opcode = X86ISD::FMIN;
22751 // Converting this to a min would handle NaNs incorrectly.
22752 if (!DAG.getTarget().Options.UnsafeFPMath &&
22753 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22755 Opcode = X86ISD::FMIN;
22758 // Converting this to a min would handle both negative zeros and NaNs
22759 // incorrectly, but we can swap the operands to fix both.
22760 std::swap(LHS, RHS);
22764 Opcode = X86ISD::FMIN;
22768 // Converting this to a max would handle NaNs incorrectly.
22769 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22771 Opcode = X86ISD::FMAX;
22774 // Converting this to a max would handle comparisons between positive
22775 // and negative zero incorrectly, and swapping the operands would
22776 // cause it to handle NaNs incorrectly.
22777 if (!DAG.getTarget().Options.UnsafeFPMath &&
22778 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22779 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22781 std::swap(LHS, RHS);
22783 Opcode = X86ISD::FMAX;
22786 // Converting this to a max would handle both negative zeros and NaNs
22787 // incorrectly, but we can swap the operands to fix both.
22788 std::swap(LHS, RHS);
22792 Opcode = X86ISD::FMAX;
22798 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22801 EVT CondVT = Cond.getValueType();
22802 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22803 CondVT.getVectorElementType() == MVT::i1) {
22804 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22805 // lowering on KNL. In this case we convert it to
22806 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22807 // The same situation for all 128 and 256-bit vectors of i8 and i16.
22808 // Since SKX these selects have a proper lowering.
22809 EVT OpVT = LHS.getValueType();
22810 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22811 (OpVT.getVectorElementType() == MVT::i8 ||
22812 OpVT.getVectorElementType() == MVT::i16) &&
22813 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22814 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22815 DCI.AddToWorklist(Cond.getNode());
22816 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22819 // If this is a select between two integer constants, try to do some
22821 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22822 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22823 // Don't do this for crazy integer types.
22824 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22825 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22826 // so that TrueC (the true value) is larger than FalseC.
22827 bool NeedsCondInvert = false;
22829 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22830 // Efficiently invertible.
22831 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
22832 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
22833 isa<ConstantSDNode>(Cond.getOperand(1))))) {
22834 NeedsCondInvert = true;
22835 std::swap(TrueC, FalseC);
22838 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
22839 if (FalseC->getAPIntValue() == 0 &&
22840 TrueC->getAPIntValue().isPowerOf2()) {
22841 if (NeedsCondInvert) // Invert the condition if needed.
22842 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22843 DAG.getConstant(1, DL, Cond.getValueType()));
22845 // Zero extend the condition if needed.
22846 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22848 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22849 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22850 DAG.getConstant(ShAmt, DL, MVT::i8));
22853 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22854 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22855 if (NeedsCondInvert) // Invert the condition if needed.
22856 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22857 DAG.getConstant(1, DL, Cond.getValueType()));
22859 // Zero extend the condition if needed.
22860 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22861 FalseC->getValueType(0), Cond);
22862 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22863 SDValue(FalseC, 0));
22866 // Optimize cases that will turn into an LEA instruction. This requires
22867 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22868 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22869 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22870 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22872 bool isFastMultiplier = false;
22874 switch ((unsigned char)Diff) {
22876 case 1: // result = add base, cond
22877 case 2: // result = lea base( , cond*2)
22878 case 3: // result = lea base(cond, cond*2)
22879 case 4: // result = lea base( , cond*4)
22880 case 5: // result = lea base(cond, cond*4)
22881 case 8: // result = lea base( , cond*8)
22882 case 9: // result = lea base(cond, cond*8)
22883 isFastMultiplier = true;
22888 if (isFastMultiplier) {
22889 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22890 if (NeedsCondInvert) // Invert the condition if needed.
22891 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22892 DAG.getConstant(1, DL, Cond.getValueType()));
22894 // Zero extend the condition if needed.
22895 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22897 // Scale the condition by the difference.
22899 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22900 DAG.getConstant(Diff, DL,
22901 Cond.getValueType()));
22903 // Add the base if non-zero.
22904 if (FalseC->getAPIntValue() != 0)
22905 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22906 SDValue(FalseC, 0));
22913 // Canonicalize max and min:
22914 // (x > y) ? x : y -> (x >= y) ? x : y
22915 // (x < y) ? x : y -> (x <= y) ? x : y
22916 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22917 // the need for an extra compare
22918 // against zero. e.g.
22919 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22921 // testl %edi, %edi
22923 // cmovgl %edi, %eax
22927 // cmovsl %eax, %edi
22928 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22929 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22930 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22931 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22936 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22937 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22938 Cond.getOperand(0), Cond.getOperand(1), NewCC);
22939 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22944 // Early exit check
22945 if (!TLI.isTypeLegal(VT))
22948 // Match VSELECTs into subs with unsigned saturation.
22949 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22950 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22951 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22952 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22953 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22955 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22956 // left side invert the predicate to simplify logic below.
22958 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22960 CC = ISD::getSetCCInverse(CC, true);
22961 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22965 if (Other.getNode() && Other->getNumOperands() == 2 &&
22966 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22967 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22968 SDValue CondRHS = Cond->getOperand(1);
22970 // Look for a general sub with unsigned saturation first.
22971 // x >= y ? x-y : 0 --> subus x, y
22972 // x > y ? x-y : 0 --> subus x, y
22973 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22974 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22975 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22977 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22978 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22979 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22980 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22981 // If the RHS is a constant we have to reverse the const
22982 // canonicalization.
22983 // x > C-1 ? x+-C : 0 --> subus x, C
22984 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22985 CondRHSConst->getAPIntValue() ==
22986 (-OpRHSConst->getAPIntValue() - 1))
22987 return DAG.getNode(
22988 X86ISD::SUBUS, DL, VT, OpLHS,
22989 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22991 // Another special case: If C was a sign bit, the sub has been
22992 // canonicalized into a xor.
22993 // FIXME: Would it be better to use computeKnownBits to determine
22994 // whether it's safe to decanonicalize the xor?
22995 // x s< 0 ? x^C : 0 --> subus x, C
22996 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22997 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22998 OpRHSConst->getAPIntValue().isSignBit())
22999 // Note that we have to rebuild the RHS constant here to ensure we
23000 // don't rely on particular values of undef lanes.
23001 return DAG.getNode(
23002 X86ISD::SUBUS, DL, VT, OpLHS,
23003 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
23008 // Simplify vector selection if condition value type matches vselect
23010 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
23011 assert(Cond.getValueType().isVector() &&
23012 "vector select expects a vector selector!");
23014 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
23015 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
23017 // Try invert the condition if true value is not all 1s and false value
23019 if (!TValIsAllOnes && !FValIsAllZeros &&
23020 // Check if the selector will be produced by CMPP*/PCMP*
23021 Cond.getOpcode() == ISD::SETCC &&
23022 // Check if SETCC has already been promoted
23023 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
23025 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
23026 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
23028 if (TValIsAllZeros || FValIsAllOnes) {
23029 SDValue CC = Cond.getOperand(2);
23030 ISD::CondCode NewCC =
23031 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
23032 Cond.getOperand(0).getValueType().isInteger());
23033 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
23034 std::swap(LHS, RHS);
23035 TValIsAllOnes = FValIsAllOnes;
23036 FValIsAllZeros = TValIsAllZeros;
23040 if (TValIsAllOnes || FValIsAllZeros) {
23043 if (TValIsAllOnes && FValIsAllZeros)
23045 else if (TValIsAllOnes)
23047 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
23048 else if (FValIsAllZeros)
23049 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
23050 DAG.getBitcast(CondVT, LHS));
23052 return DAG.getBitcast(VT, Ret);
23056 // We should generate an X86ISD::BLENDI from a vselect if its argument
23057 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
23058 // constants. This specific pattern gets generated when we split a
23059 // selector for a 512 bit vector in a machine without AVX512 (but with
23060 // 256-bit vectors), during legalization:
23062 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
23064 // Iff we find this pattern and the build_vectors are built from
23065 // constants, we translate the vselect into a shuffle_vector that we
23066 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
23067 if ((N->getOpcode() == ISD::VSELECT ||
23068 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
23069 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
23070 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
23071 if (Shuffle.getNode())
23075 // If this is a *dynamic* select (non-constant condition) and we can match
23076 // this node with one of the variable blend instructions, restructure the
23077 // condition so that the blends can use the high bit of each element and use
23078 // SimplifyDemandedBits to simplify the condition operand.
23079 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
23080 !DCI.isBeforeLegalize() &&
23081 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
23082 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
23084 // Don't optimize vector selects that map to mask-registers.
23088 // We can only handle the cases where VSELECT is directly legal on the
23089 // subtarget. We custom lower VSELECT nodes with constant conditions and
23090 // this makes it hard to see whether a dynamic VSELECT will correctly
23091 // lower, so we both check the operation's status and explicitly handle the
23092 // cases where a *dynamic* blend will fail even though a constant-condition
23093 // blend could be custom lowered.
23094 // FIXME: We should find a better way to handle this class of problems.
23095 // Potentially, we should combine constant-condition vselect nodes
23096 // pre-legalization into shuffles and not mark as many types as custom
23098 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
23100 // FIXME: We don't support i16-element blends currently. We could and
23101 // should support them by making *all* the bits in the condition be set
23102 // rather than just the high bit and using an i8-element blend.
23103 if (VT.getScalarType() == MVT::i16)
23105 // Dynamic blending was only available from SSE4.1 onward.
23106 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
23108 // Byte blends are only available in AVX2
23109 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
23110 !Subtarget->hasAVX2())
23113 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
23114 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
23116 APInt KnownZero, KnownOne;
23117 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
23118 DCI.isBeforeLegalizeOps());
23119 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
23120 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
23122 // If we changed the computation somewhere in the DAG, this change
23123 // will affect all users of Cond.
23124 // Make sure it is fine and update all the nodes so that we do not
23125 // use the generic VSELECT anymore. Otherwise, we may perform
23126 // wrong optimizations as we messed up with the actual expectation
23127 // for the vector boolean values.
23128 if (Cond != TLO.Old) {
23129 // Check all uses of that condition operand to check whether it will be
23130 // consumed by non-BLEND instructions, which may depend on all bits are
23132 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23134 if (I->getOpcode() != ISD::VSELECT)
23135 // TODO: Add other opcodes eventually lowered into BLEND.
23138 // Update all the users of the condition, before committing the change,
23139 // so that the VSELECT optimizations that expect the correct vector
23140 // boolean value will not be triggered.
23141 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23143 DAG.ReplaceAllUsesOfValueWith(
23145 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23146 Cond, I->getOperand(1), I->getOperand(2)));
23147 DCI.CommitTargetLoweringOpt(TLO);
23150 // At this point, only Cond is changed. Change the condition
23151 // just for N to keep the opportunity to optimize all other
23152 // users their own way.
23153 DAG.ReplaceAllUsesOfValueWith(
23155 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23156 TLO.New, N->getOperand(1), N->getOperand(2)));
23164 // Check whether a boolean test is testing a boolean value generated by
23165 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23168 // Simplify the following patterns:
23169 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23170 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23171 // to (Op EFLAGS Cond)
23173 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23174 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23175 // to (Op EFLAGS !Cond)
23177 // where Op could be BRCOND or CMOV.
23179 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23180 // Quit if not CMP and SUB with its value result used.
23181 if (Cmp.getOpcode() != X86ISD::CMP &&
23182 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23185 // Quit if not used as a boolean value.
23186 if (CC != X86::COND_E && CC != X86::COND_NE)
23189 // Check CMP operands. One of them should be 0 or 1 and the other should be
23190 // an SetCC or extended from it.
23191 SDValue Op1 = Cmp.getOperand(0);
23192 SDValue Op2 = Cmp.getOperand(1);
23195 const ConstantSDNode* C = nullptr;
23196 bool needOppositeCond = (CC == X86::COND_E);
23197 bool checkAgainstTrue = false; // Is it a comparison against 1?
23199 if ((C = dyn_cast<ConstantSDNode>(Op1)))
23201 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23203 else // Quit if all operands are not constants.
23206 if (C->getZExtValue() == 1) {
23207 needOppositeCond = !needOppositeCond;
23208 checkAgainstTrue = true;
23209 } else if (C->getZExtValue() != 0)
23210 // Quit if the constant is neither 0 or 1.
23213 bool truncatedToBoolWithAnd = false;
23214 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23215 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23216 SetCC.getOpcode() == ISD::TRUNCATE ||
23217 SetCC.getOpcode() == ISD::AND) {
23218 if (SetCC.getOpcode() == ISD::AND) {
23220 ConstantSDNode *CS;
23221 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23222 CS->getZExtValue() == 1)
23224 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23225 CS->getZExtValue() == 1)
23229 SetCC = SetCC.getOperand(OpIdx);
23230 truncatedToBoolWithAnd = true;
23232 SetCC = SetCC.getOperand(0);
23235 switch (SetCC.getOpcode()) {
23236 case X86ISD::SETCC_CARRY:
23237 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23238 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23239 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23240 // truncated to i1 using 'and'.
23241 if (checkAgainstTrue && !truncatedToBoolWithAnd)
23243 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23244 "Invalid use of SETCC_CARRY!");
23246 case X86ISD::SETCC:
23247 // Set the condition code or opposite one if necessary.
23248 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23249 if (needOppositeCond)
23250 CC = X86::GetOppositeBranchCondition(CC);
23251 return SetCC.getOperand(1);
23252 case X86ISD::CMOV: {
23253 // Check whether false/true value has canonical one, i.e. 0 or 1.
23254 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23255 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23256 // Quit if true value is not a constant.
23259 // Quit if false value is not a constant.
23261 SDValue Op = SetCC.getOperand(0);
23262 // Skip 'zext' or 'trunc' node.
23263 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23264 Op.getOpcode() == ISD::TRUNCATE)
23265 Op = Op.getOperand(0);
23266 // A special case for rdrand/rdseed, where 0 is set if false cond is
23268 if ((Op.getOpcode() != X86ISD::RDRAND &&
23269 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23272 // Quit if false value is not the constant 0 or 1.
23273 bool FValIsFalse = true;
23274 if (FVal && FVal->getZExtValue() != 0) {
23275 if (FVal->getZExtValue() != 1)
23277 // If FVal is 1, opposite cond is needed.
23278 needOppositeCond = !needOppositeCond;
23279 FValIsFalse = false;
23281 // Quit if TVal is not the constant opposite of FVal.
23282 if (FValIsFalse && TVal->getZExtValue() != 1)
23284 if (!FValIsFalse && TVal->getZExtValue() != 0)
23286 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23287 if (needOppositeCond)
23288 CC = X86::GetOppositeBranchCondition(CC);
23289 return SetCC.getOperand(3);
23296 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23298 /// (X86or (X86setcc) (X86setcc))
23299 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
23300 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23301 X86::CondCode &CC1, SDValue &Flags,
23303 if (Cond->getOpcode() == X86ISD::CMP) {
23304 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23305 if (!CondOp1C || !CondOp1C->isNullValue())
23308 Cond = Cond->getOperand(0);
23313 SDValue SetCC0, SetCC1;
23314 switch (Cond->getOpcode()) {
23315 default: return false;
23322 SetCC0 = Cond->getOperand(0);
23323 SetCC1 = Cond->getOperand(1);
23327 // Make sure we have SETCC nodes, using the same flags value.
23328 if (SetCC0.getOpcode() != X86ISD::SETCC ||
23329 SetCC1.getOpcode() != X86ISD::SETCC ||
23330 SetCC0->getOperand(1) != SetCC1->getOperand(1))
23333 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23334 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23335 Flags = SetCC0->getOperand(1);
23339 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23340 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23341 TargetLowering::DAGCombinerInfo &DCI,
23342 const X86Subtarget *Subtarget) {
23345 // If the flag operand isn't dead, don't touch this CMOV.
23346 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23349 SDValue FalseOp = N->getOperand(0);
23350 SDValue TrueOp = N->getOperand(1);
23351 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23352 SDValue Cond = N->getOperand(3);
23354 if (CC == X86::COND_E || CC == X86::COND_NE) {
23355 switch (Cond.getOpcode()) {
23359 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23360 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23361 return (CC == X86::COND_E) ? FalseOp : TrueOp;
23367 Flags = checkBoolTestSetCCCombine(Cond, CC);
23368 if (Flags.getNode() &&
23369 // Extra check as FCMOV only supports a subset of X86 cond.
23370 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23371 SDValue Ops[] = { FalseOp, TrueOp,
23372 DAG.getConstant(CC, DL, MVT::i8), Flags };
23373 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23376 // If this is a select between two integer constants, try to do some
23377 // optimizations. Note that the operands are ordered the opposite of SELECT
23379 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23380 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23381 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23382 // larger than FalseC (the false value).
23383 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23384 CC = X86::GetOppositeBranchCondition(CC);
23385 std::swap(TrueC, FalseC);
23386 std::swap(TrueOp, FalseOp);
23389 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
23390 // This is efficient for any integer data type (including i8/i16) and
23392 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23393 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23394 DAG.getConstant(CC, DL, MVT::i8), Cond);
23396 // Zero extend the condition if needed.
23397 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23399 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23400 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23401 DAG.getConstant(ShAmt, DL, MVT::i8));
23402 if (N->getNumValues() == 2) // Dead flag value?
23403 return DCI.CombineTo(N, Cond, SDValue());
23407 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
23408 // for any integer data type, including i8/i16.
23409 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23410 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23411 DAG.getConstant(CC, DL, MVT::i8), Cond);
23413 // Zero extend the condition if needed.
23414 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23415 FalseC->getValueType(0), Cond);
23416 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23417 SDValue(FalseC, 0));
23419 if (N->getNumValues() == 2) // Dead flag value?
23420 return DCI.CombineTo(N, Cond, SDValue());
23424 // Optimize cases that will turn into an LEA instruction. This requires
23425 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23426 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23427 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23428 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23430 bool isFastMultiplier = false;
23432 switch ((unsigned char)Diff) {
23434 case 1: // result = add base, cond
23435 case 2: // result = lea base( , cond*2)
23436 case 3: // result = lea base(cond, cond*2)
23437 case 4: // result = lea base( , cond*4)
23438 case 5: // result = lea base(cond, cond*4)
23439 case 8: // result = lea base( , cond*8)
23440 case 9: // result = lea base(cond, cond*8)
23441 isFastMultiplier = true;
23446 if (isFastMultiplier) {
23447 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23448 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23449 DAG.getConstant(CC, DL, MVT::i8), Cond);
23450 // Zero extend the condition if needed.
23451 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23453 // Scale the condition by the difference.
23455 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23456 DAG.getConstant(Diff, DL, Cond.getValueType()));
23458 // Add the base if non-zero.
23459 if (FalseC->getAPIntValue() != 0)
23460 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23461 SDValue(FalseC, 0));
23462 if (N->getNumValues() == 2) // Dead flag value?
23463 return DCI.CombineTo(N, Cond, SDValue());
23470 // Handle these cases:
23471 // (select (x != c), e, c) -> select (x != c), e, x),
23472 // (select (x == c), c, e) -> select (x == c), x, e)
23473 // where the c is an integer constant, and the "select" is the combination
23474 // of CMOV and CMP.
23476 // The rationale for this change is that the conditional-move from a constant
23477 // needs two instructions, however, conditional-move from a register needs
23478 // only one instruction.
23480 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23481 // some instruction-combining opportunities. This opt needs to be
23482 // postponed as late as possible.
23484 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23485 // the DCI.xxxx conditions are provided to postpone the optimization as
23486 // late as possible.
23488 ConstantSDNode *CmpAgainst = nullptr;
23489 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23490 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23491 !isa<ConstantSDNode>(Cond.getOperand(0))) {
23493 if (CC == X86::COND_NE &&
23494 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23495 CC = X86::GetOppositeBranchCondition(CC);
23496 std::swap(TrueOp, FalseOp);
23499 if (CC == X86::COND_E &&
23500 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23501 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23502 DAG.getConstant(CC, DL, MVT::i8), Cond };
23503 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23508 // Fold and/or of setcc's to double CMOV:
23509 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23510 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23512 // This combine lets us generate:
23513 // cmovcc1 (jcc1 if we don't have CMOV)
23519 // cmovne (jne if we don't have CMOV)
23520 // When we can't use the CMOV instruction, it might increase branch
23522 // When we can use CMOV, or when there is no mispredict, this improves
23523 // throughput and reduces register pressure.
23525 if (CC == X86::COND_NE) {
23527 X86::CondCode CC0, CC1;
23529 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23531 std::swap(FalseOp, TrueOp);
23532 CC0 = X86::GetOppositeBranchCondition(CC0);
23533 CC1 = X86::GetOppositeBranchCondition(CC1);
23536 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23538 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23539 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23540 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23541 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23549 /// PerformMulCombine - Optimize a single multiply with constant into two
23550 /// in order to implement it with two cheaper instructions, e.g.
23551 /// LEA + SHL, LEA + LEA.
23552 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23553 TargetLowering::DAGCombinerInfo &DCI) {
23554 // An imul is usually smaller than the alternative sequence.
23555 if (DAG.getMachineFunction().getFunction()->optForMinSize())
23558 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23561 EVT VT = N->getValueType(0);
23562 if (VT != MVT::i64 && VT != MVT::i32)
23565 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23568 uint64_t MulAmt = C->getZExtValue();
23569 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23572 uint64_t MulAmt1 = 0;
23573 uint64_t MulAmt2 = 0;
23574 if ((MulAmt % 9) == 0) {
23576 MulAmt2 = MulAmt / 9;
23577 } else if ((MulAmt % 5) == 0) {
23579 MulAmt2 = MulAmt / 5;
23580 } else if ((MulAmt % 3) == 0) {
23582 MulAmt2 = MulAmt / 3;
23585 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23588 if (isPowerOf2_64(MulAmt2) &&
23589 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23590 // If second multiplifer is pow2, issue it first. We want the multiply by
23591 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23593 std::swap(MulAmt1, MulAmt2);
23596 if (isPowerOf2_64(MulAmt1))
23597 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23598 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23600 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23601 DAG.getConstant(MulAmt1, DL, VT));
23603 if (isPowerOf2_64(MulAmt2))
23604 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23605 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23607 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23608 DAG.getConstant(MulAmt2, DL, VT));
23610 // Do not add new nodes to DAG combiner worklist.
23611 DCI.CombineTo(N, NewMul, false);
23616 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23617 SDValue N0 = N->getOperand(0);
23618 SDValue N1 = N->getOperand(1);
23619 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23620 EVT VT = N0.getValueType();
23622 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23623 // since the result of setcc_c is all zero's or all ones.
23624 if (VT.isInteger() && !VT.isVector() &&
23625 N1C && N0.getOpcode() == ISD::AND &&
23626 N0.getOperand(1).getOpcode() == ISD::Constant) {
23627 SDValue N00 = N0.getOperand(0);
23628 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23629 APInt ShAmt = N1C->getAPIntValue();
23630 Mask = Mask.shl(ShAmt);
23631 bool MaskOK = false;
23632 // We can handle cases concerning bit-widening nodes containing setcc_c if
23633 // we carefully interrogate the mask to make sure we are semantics
23635 // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
23636 // of the underlying setcc_c operation if the setcc_c was zero extended.
23637 // Consider the following example:
23638 // zext(setcc_c) -> i32 0x0000FFFF
23639 // c1 -> i32 0x0000FFFF
23640 // c2 -> i32 0x00000001
23641 // (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
23642 // (and setcc_c, (c1 << c2)) -> i32 0x0000FFFE
23643 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23645 } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
23646 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23648 } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
23649 N00.getOpcode() == ISD::ANY_EXTEND) &&
23650 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
23651 MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
23653 if (MaskOK && Mask != 0) {
23655 return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
23659 // Hardware support for vector shifts is sparse which makes us scalarize the
23660 // vector operations in many cases. Also, on sandybridge ADD is faster than
23662 // (shl V, 1) -> add V,V
23663 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23664 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23665 assert(N0.getValueType().isVector() && "Invalid vector shift type");
23666 // We shift all of the values by one. In many cases we do not have
23667 // hardware support for this operation. This is better expressed as an ADD
23669 if (N1SplatC->getAPIntValue() == 1)
23670 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23676 /// \brief Returns a vector of 0s if the node in input is a vector logical
23677 /// shift by a constant amount which is known to be bigger than or equal
23678 /// to the vector element size in bits.
23679 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23680 const X86Subtarget *Subtarget) {
23681 EVT VT = N->getValueType(0);
23683 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23684 (!Subtarget->hasInt256() ||
23685 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23688 SDValue Amt = N->getOperand(1);
23690 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23691 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23692 APInt ShiftAmt = AmtSplat->getAPIntValue();
23693 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23695 // SSE2/AVX2 logical shifts always return a vector of 0s
23696 // if the shift amount is bigger than or equal to
23697 // the element size. The constant shift amount will be
23698 // encoded as a 8-bit immediate.
23699 if (ShiftAmt.trunc(8).uge(MaxAmount))
23700 return getZeroVector(VT, Subtarget, DAG, DL);
23706 /// PerformShiftCombine - Combine shifts.
23707 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23708 TargetLowering::DAGCombinerInfo &DCI,
23709 const X86Subtarget *Subtarget) {
23710 if (N->getOpcode() == ISD::SHL)
23711 if (SDValue V = PerformSHLCombine(N, DAG))
23714 // Try to fold this logical shift into a zero vector.
23715 if (N->getOpcode() != ISD::SRA)
23716 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23722 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
23723 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23724 // and friends. Likewise for OR -> CMPNEQSS.
23725 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23726 TargetLowering::DAGCombinerInfo &DCI,
23727 const X86Subtarget *Subtarget) {
23730 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23731 // we're requiring SSE2 for both.
23732 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23733 SDValue N0 = N->getOperand(0);
23734 SDValue N1 = N->getOperand(1);
23735 SDValue CMP0 = N0->getOperand(1);
23736 SDValue CMP1 = N1->getOperand(1);
23739 // The SETCCs should both refer to the same CMP.
23740 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23743 SDValue CMP00 = CMP0->getOperand(0);
23744 SDValue CMP01 = CMP0->getOperand(1);
23745 EVT VT = CMP00.getValueType();
23747 if (VT == MVT::f32 || VT == MVT::f64) {
23748 bool ExpectingFlags = false;
23749 // Check for any users that want flags:
23750 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23751 !ExpectingFlags && UI != UE; ++UI)
23752 switch (UI->getOpcode()) {
23757 ExpectingFlags = true;
23759 case ISD::CopyToReg:
23760 case ISD::SIGN_EXTEND:
23761 case ISD::ZERO_EXTEND:
23762 case ISD::ANY_EXTEND:
23766 if (!ExpectingFlags) {
23767 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23768 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23770 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23771 X86::CondCode tmp = cc0;
23776 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
23777 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23778 // FIXME: need symbolic constants for these magic numbers.
23779 // See X86ATTInstPrinter.cpp:printSSECC().
23780 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23781 if (Subtarget->hasAVX512()) {
23782 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23784 DAG.getConstant(x86cc, DL, MVT::i8));
23785 if (N->getValueType(0) != MVT::i1)
23786 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23790 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23791 CMP00.getValueType(), CMP00, CMP01,
23792 DAG.getConstant(x86cc, DL,
23795 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23796 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23798 if (is64BitFP && !Subtarget->is64Bit()) {
23799 // On a 32-bit target, we cannot bitcast the 64-bit float to a
23800 // 64-bit integer, since that's not a legal type. Since
23801 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23802 // bits, but can do this little dance to extract the lowest 32 bits
23803 // and work with those going forward.
23804 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23806 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23807 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23808 Vector32, DAG.getIntPtrConstant(0, DL));
23812 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23813 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23814 DAG.getConstant(1, DL, IntVT));
23815 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23817 return OneBitOfTruth;
23825 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23826 /// so it can be folded inside ANDNP.
23827 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23828 EVT VT = N->getValueType(0);
23830 // Match direct AllOnes for 128 and 256-bit vectors
23831 if (ISD::isBuildVectorAllOnes(N))
23834 // Look through a bit convert.
23835 if (N->getOpcode() == ISD::BITCAST)
23836 N = N->getOperand(0).getNode();
23838 // Sometimes the operand may come from a insert_subvector building a 256-bit
23840 if (VT.is256BitVector() &&
23841 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23842 SDValue V1 = N->getOperand(0);
23843 SDValue V2 = N->getOperand(1);
23845 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23846 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23847 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23848 ISD::isBuildVectorAllOnes(V2.getNode()))
23855 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23856 // register. In most cases we actually compare or select YMM-sized registers
23857 // and mixing the two types creates horrible code. This method optimizes
23858 // some of the transition sequences.
23859 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23860 TargetLowering::DAGCombinerInfo &DCI,
23861 const X86Subtarget *Subtarget) {
23862 EVT VT = N->getValueType(0);
23863 if (!VT.is256BitVector())
23866 assert((N->getOpcode() == ISD::ANY_EXTEND ||
23867 N->getOpcode() == ISD::ZERO_EXTEND ||
23868 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23870 SDValue Narrow = N->getOperand(0);
23871 EVT NarrowVT = Narrow->getValueType(0);
23872 if (!NarrowVT.is128BitVector())
23875 if (Narrow->getOpcode() != ISD::XOR &&
23876 Narrow->getOpcode() != ISD::AND &&
23877 Narrow->getOpcode() != ISD::OR)
23880 SDValue N0 = Narrow->getOperand(0);
23881 SDValue N1 = Narrow->getOperand(1);
23884 // The Left side has to be a trunc.
23885 if (N0.getOpcode() != ISD::TRUNCATE)
23888 // The type of the truncated inputs.
23889 EVT WideVT = N0->getOperand(0)->getValueType(0);
23893 // The right side has to be a 'trunc' or a constant vector.
23894 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23895 ConstantSDNode *RHSConstSplat = nullptr;
23896 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23897 RHSConstSplat = RHSBV->getConstantSplatNode();
23898 if (!RHSTrunc && !RHSConstSplat)
23901 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23903 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23906 // Set N0 and N1 to hold the inputs to the new wide operation.
23907 N0 = N0->getOperand(0);
23908 if (RHSConstSplat) {
23909 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23910 SDValue(RHSConstSplat, 0));
23911 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23912 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23913 } else if (RHSTrunc) {
23914 N1 = N1->getOperand(0);
23917 // Generate the wide operation.
23918 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23919 unsigned Opcode = N->getOpcode();
23921 case ISD::ANY_EXTEND:
23923 case ISD::ZERO_EXTEND: {
23924 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23925 APInt Mask = APInt::getAllOnesValue(InBits);
23926 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23927 return DAG.getNode(ISD::AND, DL, VT,
23928 Op, DAG.getConstant(Mask, DL, VT));
23930 case ISD::SIGN_EXTEND:
23931 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23932 Op, DAG.getValueType(NarrowVT));
23934 llvm_unreachable("Unexpected opcode");
23938 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23939 TargetLowering::DAGCombinerInfo &DCI,
23940 const X86Subtarget *Subtarget) {
23941 SDValue N0 = N->getOperand(0);
23942 SDValue N1 = N->getOperand(1);
23945 // A vector zext_in_reg may be represented as a shuffle,
23946 // feeding into a bitcast (this represents anyext) feeding into
23947 // an and with a mask.
23948 // We'd like to try to combine that into a shuffle with zero
23949 // plus a bitcast, removing the and.
23950 if (N0.getOpcode() != ISD::BITCAST ||
23951 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23954 // The other side of the AND should be a splat of 2^C, where C
23955 // is the number of bits in the source type.
23956 if (N1.getOpcode() == ISD::BITCAST)
23957 N1 = N1.getOperand(0);
23958 if (N1.getOpcode() != ISD::BUILD_VECTOR)
23960 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23962 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23963 EVT SrcType = Shuffle->getValueType(0);
23965 // We expect a single-source shuffle
23966 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23969 unsigned SrcSize = SrcType.getScalarSizeInBits();
23971 APInt SplatValue, SplatUndef;
23972 unsigned SplatBitSize;
23974 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23975 SplatBitSize, HasAnyUndefs))
23978 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23979 // Make sure the splat matches the mask we expect
23980 if (SplatBitSize > ResSize ||
23981 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23984 // Make sure the input and output size make sense
23985 if (SrcSize >= ResSize || ResSize % SrcSize)
23988 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23989 // The number of u's between each two values depends on the ratio between
23990 // the source and dest type.
23991 unsigned ZextRatio = ResSize / SrcSize;
23992 bool IsZext = true;
23993 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23994 if (i % ZextRatio) {
23995 if (Shuffle->getMaskElt(i) > 0) {
24001 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
24002 // Expected element number
24012 // Ok, perform the transformation - replace the shuffle with
24013 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
24014 // (instead of undef) where the k elements come from the zero vector.
24015 SmallVector<int, 8> Mask;
24016 unsigned NumElems = SrcType.getVectorNumElements();
24017 for (unsigned i = 0; i < NumElems; ++i)
24019 Mask.push_back(NumElems);
24021 Mask.push_back(i / ZextRatio);
24023 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
24024 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
24025 return DAG.getBitcast(N0.getValueType(), NewShuffle);
24028 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
24029 TargetLowering::DAGCombinerInfo &DCI,
24030 const X86Subtarget *Subtarget) {
24031 if (DCI.isBeforeLegalizeOps())
24034 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
24037 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24040 EVT VT = N->getValueType(0);
24041 SDValue N0 = N->getOperand(0);
24042 SDValue N1 = N->getOperand(1);
24045 // Create BEXTR instructions
24046 // BEXTR is ((X >> imm) & (2**size-1))
24047 if (VT == MVT::i32 || VT == MVT::i64) {
24048 // Check for BEXTR.
24049 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
24050 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
24051 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
24052 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24053 if (MaskNode && ShiftNode) {
24054 uint64_t Mask = MaskNode->getZExtValue();
24055 uint64_t Shift = ShiftNode->getZExtValue();
24056 if (isMask_64(Mask)) {
24057 uint64_t MaskSize = countPopulation(Mask);
24058 if (Shift + MaskSize <= VT.getSizeInBits())
24059 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24060 DAG.getConstant(Shift | (MaskSize << 8), DL,
24069 // Want to form ANDNP nodes:
24070 // 1) In the hopes of then easily combining them with OR and AND nodes
24071 // to form PBLEND/PSIGN.
24072 // 2) To match ANDN packed intrinsics
24073 if (VT != MVT::v2i64 && VT != MVT::v4i64)
24076 // Check LHS for vnot
24077 if (N0.getOpcode() == ISD::XOR &&
24078 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24079 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24080 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24082 // Check RHS for vnot
24083 if (N1.getOpcode() == ISD::XOR &&
24084 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24085 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24086 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24091 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24092 TargetLowering::DAGCombinerInfo &DCI,
24093 const X86Subtarget *Subtarget) {
24094 if (DCI.isBeforeLegalizeOps())
24097 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24100 SDValue N0 = N->getOperand(0);
24101 SDValue N1 = N->getOperand(1);
24102 EVT VT = N->getValueType(0);
24104 // look for psign/blend
24105 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24106 if (!Subtarget->hasSSSE3() ||
24107 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24110 // Canonicalize pandn to RHS
24111 if (N0.getOpcode() == X86ISD::ANDNP)
24113 // or (and (m, y), (pandn m, x))
24114 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24115 SDValue Mask = N1.getOperand(0);
24116 SDValue X = N1.getOperand(1);
24118 if (N0.getOperand(0) == Mask)
24119 Y = N0.getOperand(1);
24120 if (N0.getOperand(1) == Mask)
24121 Y = N0.getOperand(0);
24123 // Check to see if the mask appeared in both the AND and ANDNP and
24127 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24128 // Look through mask bitcast.
24129 if (Mask.getOpcode() == ISD::BITCAST)
24130 Mask = Mask.getOperand(0);
24131 if (X.getOpcode() == ISD::BITCAST)
24132 X = X.getOperand(0);
24133 if (Y.getOpcode() == ISD::BITCAST)
24134 Y = Y.getOperand(0);
24136 EVT MaskVT = Mask.getValueType();
24138 // Validate that the Mask operand is a vector sra node.
24139 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24140 // there is no psrai.b
24141 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24142 unsigned SraAmt = ~0;
24143 if (Mask.getOpcode() == ISD::SRA) {
24144 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24145 if (auto *AmtConst = AmtBV->getConstantSplatNode())
24146 SraAmt = AmtConst->getZExtValue();
24147 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24148 SDValue SraC = Mask.getOperand(1);
24149 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
24151 if ((SraAmt + 1) != EltBits)
24156 // Now we know we at least have a plendvb with the mask val. See if
24157 // we can form a psignb/w/d.
24158 // psign = x.type == y.type == mask.type && y = sub(0, x);
24159 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24160 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24161 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24162 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24163 "Unsupported VT for PSIGN");
24164 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24165 return DAG.getBitcast(VT, Mask);
24167 // PBLENDVB only available on SSE 4.1
24168 if (!Subtarget->hasSSE41())
24171 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24173 X = DAG.getBitcast(BlendVT, X);
24174 Y = DAG.getBitcast(BlendVT, Y);
24175 Mask = DAG.getBitcast(BlendVT, Mask);
24176 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24177 return DAG.getBitcast(VT, Mask);
24181 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24184 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24185 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
24187 // SHLD/SHRD instructions have lower register pressure, but on some
24188 // platforms they have higher latency than the equivalent
24189 // series of shifts/or that would otherwise be generated.
24190 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24191 // have higher latencies and we are not optimizing for size.
24192 if (!OptForSize && Subtarget->isSHLDSlow())
24195 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24197 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24199 if (!N0.hasOneUse() || !N1.hasOneUse())
24202 SDValue ShAmt0 = N0.getOperand(1);
24203 if (ShAmt0.getValueType() != MVT::i8)
24205 SDValue ShAmt1 = N1.getOperand(1);
24206 if (ShAmt1.getValueType() != MVT::i8)
24208 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24209 ShAmt0 = ShAmt0.getOperand(0);
24210 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24211 ShAmt1 = ShAmt1.getOperand(0);
24214 unsigned Opc = X86ISD::SHLD;
24215 SDValue Op0 = N0.getOperand(0);
24216 SDValue Op1 = N1.getOperand(0);
24217 if (ShAmt0.getOpcode() == ISD::SUB) {
24218 Opc = X86ISD::SHRD;
24219 std::swap(Op0, Op1);
24220 std::swap(ShAmt0, ShAmt1);
24223 unsigned Bits = VT.getSizeInBits();
24224 if (ShAmt1.getOpcode() == ISD::SUB) {
24225 SDValue Sum = ShAmt1.getOperand(0);
24226 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24227 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24228 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24229 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24230 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24231 return DAG.getNode(Opc, DL, VT,
24233 DAG.getNode(ISD::TRUNCATE, DL,
24236 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24237 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24239 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24240 return DAG.getNode(Opc, DL, VT,
24241 N0.getOperand(0), N1.getOperand(0),
24242 DAG.getNode(ISD::TRUNCATE, DL,
24249 // Generate NEG and CMOV for integer abs.
24250 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24251 EVT VT = N->getValueType(0);
24253 // Since X86 does not have CMOV for 8-bit integer, we don't convert
24254 // 8-bit integer abs to NEG and CMOV.
24255 if (VT.isInteger() && VT.getSizeInBits() == 8)
24258 SDValue N0 = N->getOperand(0);
24259 SDValue N1 = N->getOperand(1);
24262 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24263 // and change it to SUB and CMOV.
24264 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24265 N0.getOpcode() == ISD::ADD &&
24266 N0.getOperand(1) == N1 &&
24267 N1.getOpcode() == ISD::SRA &&
24268 N1.getOperand(0) == N0.getOperand(0))
24269 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24270 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24271 // Generate SUB & CMOV.
24272 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24273 DAG.getConstant(0, DL, VT), N0.getOperand(0));
24275 SDValue Ops[] = { N0.getOperand(0), Neg,
24276 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24277 SDValue(Neg.getNode(), 1) };
24278 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24283 // Try to turn tests against the signbit in the form of:
24284 // XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
24287 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
24288 // This is only worth doing if the output type is i8.
24289 if (N->getValueType(0) != MVT::i8)
24292 SDValue N0 = N->getOperand(0);
24293 SDValue N1 = N->getOperand(1);
24295 // We should be performing an xor against a truncated shift.
24296 if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
24299 // Make sure we are performing an xor against one.
24300 if (!isa<ConstantSDNode>(N1) || !cast<ConstantSDNode>(N1)->isOne())
24303 // SetCC on x86 zero extends so only act on this if it's a logical shift.
24304 SDValue Shift = N0.getOperand(0);
24305 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
24308 // Make sure we are truncating from one of i16, i32 or i64.
24309 EVT ShiftTy = Shift.getValueType();
24310 if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
24313 // Make sure the shift amount extracts the sign bit.
24314 if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
24315 Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
24318 // Create a greater-than comparison against -1.
24319 // N.B. Using SETGE against 0 works but we want a canonical looking
24320 // comparison, using SETGT matches up with what TranslateX86CC.
24322 SDValue ShiftOp = Shift.getOperand(0);
24323 EVT ShiftOpTy = ShiftOp.getValueType();
24324 SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
24325 DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
24329 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24330 TargetLowering::DAGCombinerInfo &DCI,
24331 const X86Subtarget *Subtarget) {
24332 if (DCI.isBeforeLegalizeOps())
24335 if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
24338 if (Subtarget->hasCMov())
24339 if (SDValue RV = performIntegerAbsCombine(N, DAG))
24345 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24346 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24347 TargetLowering::DAGCombinerInfo &DCI,
24348 const X86Subtarget *Subtarget) {
24349 LoadSDNode *Ld = cast<LoadSDNode>(N);
24350 EVT RegVT = Ld->getValueType(0);
24351 EVT MemVT = Ld->getMemoryVT();
24353 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24355 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24356 // into two 16-byte operations.
24357 ISD::LoadExtType Ext = Ld->getExtensionType();
24359 unsigned AddressSpace = Ld->getAddressSpace();
24360 unsigned Alignment = Ld->getAlignment();
24361 if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
24362 Ext == ISD::NON_EXTLOAD &&
24363 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
24364 AddressSpace, Alignment, &Fast) && !Fast) {
24365 unsigned NumElems = RegVT.getVectorNumElements();
24369 SDValue Ptr = Ld->getBasePtr();
24370 SDValue Increment =
24371 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24373 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24375 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24376 Ld->getPointerInfo(), Ld->isVolatile(),
24377 Ld->isNonTemporal(), Ld->isInvariant(),
24379 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24380 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24381 Ld->getPointerInfo(), Ld->isVolatile(),
24382 Ld->isNonTemporal(), Ld->isInvariant(),
24383 std::min(16U, Alignment));
24384 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24386 Load2.getValue(1));
24388 SDValue NewVec = DAG.getUNDEF(RegVT);
24389 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24390 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24391 return DCI.CombineTo(N, NewVec, TF, true);
24397 /// PerformMLOADCombine - Resolve extending loads
24398 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24399 TargetLowering::DAGCombinerInfo &DCI,
24400 const X86Subtarget *Subtarget) {
24401 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24402 if (Mld->getExtensionType() != ISD::SEXTLOAD)
24405 EVT VT = Mld->getValueType(0);
24406 unsigned NumElems = VT.getVectorNumElements();
24407 EVT LdVT = Mld->getMemoryVT();
24410 assert(LdVT != VT && "Cannot extend to the same type");
24411 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24412 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24413 // From, To sizes and ElemCount must be pow of two
24414 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24415 "Unexpected size for extending masked load");
24417 unsigned SizeRatio = ToSz / FromSz;
24418 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24420 // Create a type on which we perform the shuffle
24421 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24422 LdVT.getScalarType(), NumElems*SizeRatio);
24423 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24425 // Convert Src0 value
24426 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24427 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24428 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24429 for (unsigned i = 0; i != NumElems; ++i)
24430 ShuffleVec[i] = i * SizeRatio;
24432 // Can't shuffle using an illegal type.
24433 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24434 && "WideVecVT should be legal");
24435 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24436 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24438 // Prepare the new mask
24440 SDValue Mask = Mld->getMask();
24441 if (Mask.getValueType() == VT) {
24442 // Mask and original value have the same type
24443 NewMask = DAG.getBitcast(WideVecVT, Mask);
24444 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24445 for (unsigned i = 0; i != NumElems; ++i)
24446 ShuffleVec[i] = i * SizeRatio;
24447 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24448 ShuffleVec[i] = NumElems*SizeRatio;
24449 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24450 DAG.getConstant(0, dl, WideVecVT),
24454 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24455 unsigned WidenNumElts = NumElems*SizeRatio;
24456 unsigned MaskNumElts = VT.getVectorNumElements();
24457 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24460 unsigned NumConcat = WidenNumElts / MaskNumElts;
24461 SmallVector<SDValue, 16> Ops(NumConcat);
24462 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24464 for (unsigned i = 1; i != NumConcat; ++i)
24467 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24470 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24471 Mld->getBasePtr(), NewMask, WideSrc0,
24472 Mld->getMemoryVT(), Mld->getMemOperand(),
24474 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24475 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24478 /// PerformMSTORECombine - Resolve truncating stores
24479 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24480 const X86Subtarget *Subtarget) {
24481 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24482 if (!Mst->isTruncatingStore())
24485 EVT VT = Mst->getValue().getValueType();
24486 unsigned NumElems = VT.getVectorNumElements();
24487 EVT StVT = Mst->getMemoryVT();
24490 assert(StVT != VT && "Cannot truncate to the same type");
24491 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24492 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24494 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24496 // The truncating store is legal in some cases. For example
24497 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24498 // are designated for truncate store.
24499 // In this case we don't need any further transformations.
24500 if (TLI.isTruncStoreLegal(VT, StVT))
24503 // From, To sizes and ElemCount must be pow of two
24504 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24505 "Unexpected size for truncating masked store");
24506 // We are going to use the original vector elt for storing.
24507 // Accumulated smaller vector elements must be a multiple of the store size.
24508 assert (((NumElems * FromSz) % ToSz) == 0 &&
24509 "Unexpected ratio for truncating masked store");
24511 unsigned SizeRatio = FromSz / ToSz;
24512 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24514 // Create a type on which we perform the shuffle
24515 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24516 StVT.getScalarType(), NumElems*SizeRatio);
24518 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24520 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24521 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24522 for (unsigned i = 0; i != NumElems; ++i)
24523 ShuffleVec[i] = i * SizeRatio;
24525 // Can't shuffle using an illegal type.
24526 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24527 && "WideVecVT should be legal");
24529 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24530 DAG.getUNDEF(WideVecVT),
24534 SDValue Mask = Mst->getMask();
24535 if (Mask.getValueType() == VT) {
24536 // Mask and original value have the same type
24537 NewMask = DAG.getBitcast(WideVecVT, Mask);
24538 for (unsigned i = 0; i != NumElems; ++i)
24539 ShuffleVec[i] = i * SizeRatio;
24540 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24541 ShuffleVec[i] = NumElems*SizeRatio;
24542 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24543 DAG.getConstant(0, dl, WideVecVT),
24547 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24548 unsigned WidenNumElts = NumElems*SizeRatio;
24549 unsigned MaskNumElts = VT.getVectorNumElements();
24550 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24553 unsigned NumConcat = WidenNumElts / MaskNumElts;
24554 SmallVector<SDValue, 16> Ops(NumConcat);
24555 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24557 for (unsigned i = 1; i != NumConcat; ++i)
24560 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24563 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24564 NewMask, StVT, Mst->getMemOperand(), false);
24566 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24567 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24568 const X86Subtarget *Subtarget) {
24569 StoreSDNode *St = cast<StoreSDNode>(N);
24570 EVT VT = St->getValue().getValueType();
24571 EVT StVT = St->getMemoryVT();
24573 SDValue StoredVal = St->getOperand(1);
24574 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24576 // If we are saving a concatenation of two XMM registers and 32-byte stores
24577 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24579 unsigned AddressSpace = St->getAddressSpace();
24580 unsigned Alignment = St->getAlignment();
24581 if (VT.is256BitVector() && StVT == VT &&
24582 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
24583 AddressSpace, Alignment, &Fast) && !Fast) {
24584 unsigned NumElems = VT.getVectorNumElements();
24588 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24589 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24592 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24593 SDValue Ptr0 = St->getBasePtr();
24594 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24596 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24597 St->getPointerInfo(), St->isVolatile(),
24598 St->isNonTemporal(), Alignment);
24599 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24600 St->getPointerInfo(), St->isVolatile(),
24601 St->isNonTemporal(),
24602 std::min(16U, Alignment));
24603 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24606 // Optimize trunc store (of multiple scalars) to shuffle and store.
24607 // First, pack all of the elements in one place. Next, store to memory
24608 // in fewer chunks.
24609 if (St->isTruncatingStore() && VT.isVector()) {
24610 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24611 unsigned NumElems = VT.getVectorNumElements();
24612 assert(StVT != VT && "Cannot truncate to the same type");
24613 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24614 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24616 // The truncating store is legal in some cases. For example
24617 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24618 // are designated for truncate store.
24619 // In this case we don't need any further transformations.
24620 if (TLI.isTruncStoreLegal(VT, StVT))
24623 // From, To sizes and ElemCount must be pow of two
24624 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24625 // We are going to use the original vector elt for storing.
24626 // Accumulated smaller vector elements must be a multiple of the store size.
24627 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24629 unsigned SizeRatio = FromSz / ToSz;
24631 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24633 // Create a type on which we perform the shuffle
24634 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24635 StVT.getScalarType(), NumElems*SizeRatio);
24637 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24639 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24640 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24641 for (unsigned i = 0; i != NumElems; ++i)
24642 ShuffleVec[i] = i * SizeRatio;
24644 // Can't shuffle using an illegal type.
24645 if (!TLI.isTypeLegal(WideVecVT))
24648 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24649 DAG.getUNDEF(WideVecVT),
24651 // At this point all of the data is stored at the bottom of the
24652 // register. We now need to save it to mem.
24654 // Find the largest store unit
24655 MVT StoreType = MVT::i8;
24656 for (MVT Tp : MVT::integer_valuetypes()) {
24657 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24661 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24662 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24663 (64 <= NumElems * ToSz))
24664 StoreType = MVT::f64;
24666 // Bitcast the original vector into a vector of store-size units
24667 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24668 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24669 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24670 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24671 SmallVector<SDValue, 8> Chains;
24672 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24673 TLI.getPointerTy(DAG.getDataLayout()));
24674 SDValue Ptr = St->getBasePtr();
24676 // Perform one or more big stores into memory.
24677 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24678 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24679 StoreType, ShuffWide,
24680 DAG.getIntPtrConstant(i, dl));
24681 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24682 St->getPointerInfo(), St->isVolatile(),
24683 St->isNonTemporal(), St->getAlignment());
24684 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24685 Chains.push_back(Ch);
24688 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24691 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
24692 // the FP state in cases where an emms may be missing.
24693 // A preferable solution to the general problem is to figure out the right
24694 // places to insert EMMS. This qualifies as a quick hack.
24696 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24697 if (VT.getSizeInBits() != 64)
24700 const Function *F = DAG.getMachineFunction().getFunction();
24701 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24703 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24704 if ((VT.isVector() ||
24705 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24706 isa<LoadSDNode>(St->getValue()) &&
24707 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24708 St->getChain().hasOneUse() && !St->isVolatile()) {
24709 SDNode* LdVal = St->getValue().getNode();
24710 LoadSDNode *Ld = nullptr;
24711 int TokenFactorIndex = -1;
24712 SmallVector<SDValue, 8> Ops;
24713 SDNode* ChainVal = St->getChain().getNode();
24714 // Must be a store of a load. We currently handle two cases: the load
24715 // is a direct child, and it's under an intervening TokenFactor. It is
24716 // possible to dig deeper under nested TokenFactors.
24717 if (ChainVal == LdVal)
24718 Ld = cast<LoadSDNode>(St->getChain());
24719 else if (St->getValue().hasOneUse() &&
24720 ChainVal->getOpcode() == ISD::TokenFactor) {
24721 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24722 if (ChainVal->getOperand(i).getNode() == LdVal) {
24723 TokenFactorIndex = i;
24724 Ld = cast<LoadSDNode>(St->getValue());
24726 Ops.push_back(ChainVal->getOperand(i));
24730 if (!Ld || !ISD::isNormalLoad(Ld))
24733 // If this is not the MMX case, i.e. we are just turning i64 load/store
24734 // into f64 load/store, avoid the transformation if there are multiple
24735 // uses of the loaded value.
24736 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24741 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24742 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24744 if (Subtarget->is64Bit() || F64IsLegal) {
24745 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24746 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24747 Ld->getPointerInfo(), Ld->isVolatile(),
24748 Ld->isNonTemporal(), Ld->isInvariant(),
24749 Ld->getAlignment());
24750 SDValue NewChain = NewLd.getValue(1);
24751 if (TokenFactorIndex != -1) {
24752 Ops.push_back(NewChain);
24753 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24755 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24756 St->getPointerInfo(),
24757 St->isVolatile(), St->isNonTemporal(),
24758 St->getAlignment());
24761 // Otherwise, lower to two pairs of 32-bit loads / stores.
24762 SDValue LoAddr = Ld->getBasePtr();
24763 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24764 DAG.getConstant(4, LdDL, MVT::i32));
24766 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24767 Ld->getPointerInfo(),
24768 Ld->isVolatile(), Ld->isNonTemporal(),
24769 Ld->isInvariant(), Ld->getAlignment());
24770 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24771 Ld->getPointerInfo().getWithOffset(4),
24772 Ld->isVolatile(), Ld->isNonTemporal(),
24774 MinAlign(Ld->getAlignment(), 4));
24776 SDValue NewChain = LoLd.getValue(1);
24777 if (TokenFactorIndex != -1) {
24778 Ops.push_back(LoLd);
24779 Ops.push_back(HiLd);
24780 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24783 LoAddr = St->getBasePtr();
24784 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24785 DAG.getConstant(4, StDL, MVT::i32));
24787 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24788 St->getPointerInfo(),
24789 St->isVolatile(), St->isNonTemporal(),
24790 St->getAlignment());
24791 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24792 St->getPointerInfo().getWithOffset(4),
24794 St->isNonTemporal(),
24795 MinAlign(St->getAlignment(), 4));
24796 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24799 // This is similar to the above case, but here we handle a scalar 64-bit
24800 // integer store that is extracted from a vector on a 32-bit target.
24801 // If we have SSE2, then we can treat it like a floating-point double
24802 // to get past legalization. The execution dependencies fixup pass will
24803 // choose the optimal machine instruction for the store if this really is
24804 // an integer or v2f32 rather than an f64.
24805 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24806 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24807 SDValue OldExtract = St->getOperand(1);
24808 SDValue ExtOp0 = OldExtract.getOperand(0);
24809 unsigned VecSize = ExtOp0.getValueSizeInBits();
24810 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24811 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24812 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24813 BitCast, OldExtract.getOperand(1));
24814 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24815 St->getPointerInfo(), St->isVolatile(),
24816 St->isNonTemporal(), St->getAlignment());
24822 /// Return 'true' if this vector operation is "horizontal"
24823 /// and return the operands for the horizontal operation in LHS and RHS. A
24824 /// horizontal operation performs the binary operation on successive elements
24825 /// of its first operand, then on successive elements of its second operand,
24826 /// returning the resulting values in a vector. For example, if
24827 /// A = < float a0, float a1, float a2, float a3 >
24829 /// B = < float b0, float b1, float b2, float b3 >
24830 /// then the result of doing a horizontal operation on A and B is
24831 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24832 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24833 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24834 /// set to A, RHS to B, and the routine returns 'true'.
24835 /// Note that the binary operation should have the property that if one of the
24836 /// operands is UNDEF then the result is UNDEF.
24837 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24838 // Look for the following pattern: if
24839 // A = < float a0, float a1, float a2, float a3 >
24840 // B = < float b0, float b1, float b2, float b3 >
24842 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24843 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24844 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24845 // which is A horizontal-op B.
24847 // At least one of the operands should be a vector shuffle.
24848 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24849 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24852 MVT VT = LHS.getSimpleValueType();
24854 assert((VT.is128BitVector() || VT.is256BitVector()) &&
24855 "Unsupported vector type for horizontal add/sub");
24857 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24858 // operate independently on 128-bit lanes.
24859 unsigned NumElts = VT.getVectorNumElements();
24860 unsigned NumLanes = VT.getSizeInBits()/128;
24861 unsigned NumLaneElts = NumElts / NumLanes;
24862 assert((NumLaneElts % 2 == 0) &&
24863 "Vector type should have an even number of elements in each lane");
24864 unsigned HalfLaneElts = NumLaneElts/2;
24866 // View LHS in the form
24867 // LHS = VECTOR_SHUFFLE A, B, LMask
24868 // If LHS is not a shuffle then pretend it is the shuffle
24869 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24870 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24873 SmallVector<int, 16> LMask(NumElts);
24874 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24875 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24876 A = LHS.getOperand(0);
24877 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24878 B = LHS.getOperand(1);
24879 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24880 std::copy(Mask.begin(), Mask.end(), LMask.begin());
24882 if (LHS.getOpcode() != ISD::UNDEF)
24884 for (unsigned i = 0; i != NumElts; ++i)
24888 // Likewise, view RHS in the form
24889 // RHS = VECTOR_SHUFFLE C, D, RMask
24891 SmallVector<int, 16> RMask(NumElts);
24892 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24893 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24894 C = RHS.getOperand(0);
24895 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24896 D = RHS.getOperand(1);
24897 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24898 std::copy(Mask.begin(), Mask.end(), RMask.begin());
24900 if (RHS.getOpcode() != ISD::UNDEF)
24902 for (unsigned i = 0; i != NumElts; ++i)
24906 // Check that the shuffles are both shuffling the same vectors.
24907 if (!(A == C && B == D) && !(A == D && B == C))
24910 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24911 if (!A.getNode() && !B.getNode())
24914 // If A and B occur in reverse order in RHS, then "swap" them (which means
24915 // rewriting the mask).
24917 ShuffleVectorSDNode::commuteMask(RMask);
24919 // At this point LHS and RHS are equivalent to
24920 // LHS = VECTOR_SHUFFLE A, B, LMask
24921 // RHS = VECTOR_SHUFFLE A, B, RMask
24922 // Check that the masks correspond to performing a horizontal operation.
24923 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24924 for (unsigned i = 0; i != NumLaneElts; ++i) {
24925 int LIdx = LMask[i+l], RIdx = RMask[i+l];
24927 // Ignore any UNDEF components.
24928 if (LIdx < 0 || RIdx < 0 ||
24929 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24930 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24933 // Check that successive elements are being operated on. If not, this is
24934 // not a horizontal operation.
24935 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24936 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24937 if (!(LIdx == Index && RIdx == Index + 1) &&
24938 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24943 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24944 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24948 /// Do target-specific dag combines on floating point adds.
24949 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24950 const X86Subtarget *Subtarget) {
24951 EVT VT = N->getValueType(0);
24952 SDValue LHS = N->getOperand(0);
24953 SDValue RHS = N->getOperand(1);
24955 // Try to synthesize horizontal adds from adds of shuffles.
24956 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24957 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24958 isHorizontalBinOp(LHS, RHS, true))
24959 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24963 /// Do target-specific dag combines on floating point subs.
24964 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24965 const X86Subtarget *Subtarget) {
24966 EVT VT = N->getValueType(0);
24967 SDValue LHS = N->getOperand(0);
24968 SDValue RHS = N->getOperand(1);
24970 // Try to synthesize horizontal subs from subs of shuffles.
24971 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24972 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24973 isHorizontalBinOp(LHS, RHS, false))
24974 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24978 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24979 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24980 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24982 // F[X]OR(0.0, x) -> x
24983 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24984 if (C->getValueAPF().isPosZero())
24985 return N->getOperand(1);
24987 // F[X]OR(x, 0.0) -> x
24988 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24989 if (C->getValueAPF().isPosZero())
24990 return N->getOperand(0);
24994 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24995 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24996 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24998 // Only perform optimizations if UnsafeMath is used.
24999 if (!DAG.getTarget().Options.UnsafeFPMath)
25002 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
25003 // into FMINC and FMAXC, which are Commutative operations.
25004 unsigned NewOp = 0;
25005 switch (N->getOpcode()) {
25006 default: llvm_unreachable("unknown opcode");
25007 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
25008 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
25011 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
25012 N->getOperand(0), N->getOperand(1));
25015 /// Do target-specific dag combines on X86ISD::FAND nodes.
25016 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
25017 // FAND(0.0, x) -> 0.0
25018 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25019 if (C->getValueAPF().isPosZero())
25020 return N->getOperand(0);
25022 // FAND(x, 0.0) -> 0.0
25023 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25024 if (C->getValueAPF().isPosZero())
25025 return N->getOperand(1);
25030 /// Do target-specific dag combines on X86ISD::FANDN nodes
25031 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
25032 // FANDN(0.0, x) -> x
25033 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
25034 if (C->getValueAPF().isPosZero())
25035 return N->getOperand(1);
25037 // FANDN(x, 0.0) -> 0.0
25038 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
25039 if (C->getValueAPF().isPosZero())
25040 return N->getOperand(1);
25045 static SDValue PerformBTCombine(SDNode *N,
25047 TargetLowering::DAGCombinerInfo &DCI) {
25048 // BT ignores high bits in the bit index operand.
25049 SDValue Op1 = N->getOperand(1);
25050 if (Op1.hasOneUse()) {
25051 unsigned BitWidth = Op1.getValueSizeInBits();
25052 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
25053 APInt KnownZero, KnownOne;
25054 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
25055 !DCI.isBeforeLegalizeOps());
25056 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25057 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
25058 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
25059 DCI.CommitTargetLoweringOpt(TLO);
25064 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
25065 SDValue Op = N->getOperand(0);
25066 if (Op.getOpcode() == ISD::BITCAST)
25067 Op = Op.getOperand(0);
25068 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
25069 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
25070 VT.getVectorElementType().getSizeInBits() ==
25071 OpVT.getVectorElementType().getSizeInBits()) {
25072 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
25077 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
25078 const X86Subtarget *Subtarget) {
25079 EVT VT = N->getValueType(0);
25080 if (!VT.isVector())
25083 SDValue N0 = N->getOperand(0);
25084 SDValue N1 = N->getOperand(1);
25085 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
25088 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
25089 // both SSE and AVX2 since there is no sign-extended shift right
25090 // operation on a vector with 64-bit elements.
25091 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
25092 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
25093 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
25094 N0.getOpcode() == ISD::SIGN_EXTEND)) {
25095 SDValue N00 = N0.getOperand(0);
25097 // EXTLOAD has a better solution on AVX2,
25098 // it may be replaced with X86ISD::VSEXT node.
25099 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
25100 if (!ISD::isNormalLoad(N00.getNode()))
25103 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25104 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25106 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25112 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25113 TargetLowering::DAGCombinerInfo &DCI,
25114 const X86Subtarget *Subtarget) {
25115 SDValue N0 = N->getOperand(0);
25116 EVT VT = N->getValueType(0);
25117 EVT SVT = VT.getScalarType();
25118 EVT InVT = N0.getValueType();
25119 EVT InSVT = InVT.getScalarType();
25122 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25123 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25124 // This exposes the sext to the sdivrem lowering, so that it directly extends
25125 // from AH (which we otherwise need to do contortions to access).
25126 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25127 InVT == MVT::i8 && VT == MVT::i32) {
25128 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25129 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25130 N0.getOperand(0), N0.getOperand(1));
25131 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25132 return R.getValue(1);
25135 if (!DCI.isBeforeLegalizeOps()) {
25136 if (InVT == MVT::i1) {
25137 SDValue Zero = DAG.getConstant(0, DL, VT);
25139 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25140 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25145 if (VT.isVector() && Subtarget->hasSSE2()) {
25146 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25147 EVT InVT = N.getValueType();
25148 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25149 Size / InVT.getScalarSizeInBits());
25150 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25151 DAG.getUNDEF(InVT));
25153 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25156 // If target-size is less than 128-bits, extend to a type that would extend
25157 // to 128 bits, extend that and extract the original target vector.
25158 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25159 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25160 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25161 unsigned Scale = 128 / VT.getSizeInBits();
25163 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25164 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25165 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25166 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25167 DAG.getIntPtrConstant(0, DL));
25170 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25171 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25172 if (VT.getSizeInBits() == 128 &&
25173 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25174 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25175 SDValue ExOp = ExtendVecSize(DL, N0, 128);
25176 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25179 // On pre-AVX2 targets, split into 128-bit nodes of
25180 // ISD::SIGN_EXTEND_VECTOR_INREG.
25181 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25182 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25183 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25184 unsigned NumVecs = VT.getSizeInBits() / 128;
25185 unsigned NumSubElts = 128 / SVT.getSizeInBits();
25186 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25187 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25189 SmallVector<SDValue, 8> Opnds;
25190 for (unsigned i = 0, Offset = 0; i != NumVecs;
25191 ++i, Offset += NumSubElts) {
25192 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25193 DAG.getIntPtrConstant(Offset, DL));
25194 SrcVec = ExtendVecSize(DL, SrcVec, 128);
25195 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25196 Opnds.push_back(SrcVec);
25198 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25202 if (!Subtarget->hasFp256())
25205 if (VT.isVector() && VT.getSizeInBits() == 256)
25206 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25212 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25213 const X86Subtarget* Subtarget) {
25215 EVT VT = N->getValueType(0);
25217 // Let legalize expand this if it isn't a legal type yet.
25218 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25221 EVT ScalarVT = VT.getScalarType();
25222 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25223 (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25224 !Subtarget->hasAVX512()))
25227 SDValue A = N->getOperand(0);
25228 SDValue B = N->getOperand(1);
25229 SDValue C = N->getOperand(2);
25231 bool NegA = (A.getOpcode() == ISD::FNEG);
25232 bool NegB = (B.getOpcode() == ISD::FNEG);
25233 bool NegC = (C.getOpcode() == ISD::FNEG);
25235 // Negative multiplication when NegA xor NegB
25236 bool NegMul = (NegA != NegB);
25238 A = A.getOperand(0);
25240 B = B.getOperand(0);
25242 C = C.getOperand(0);
25246 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25248 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25250 return DAG.getNode(Opcode, dl, VT, A, B, C);
25253 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25254 TargetLowering::DAGCombinerInfo &DCI,
25255 const X86Subtarget *Subtarget) {
25256 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
25257 // (and (i32 x86isd::setcc_carry), 1)
25258 // This eliminates the zext. This transformation is necessary because
25259 // ISD::SETCC is always legalized to i8.
25261 SDValue N0 = N->getOperand(0);
25262 EVT VT = N->getValueType(0);
25264 if (N0.getOpcode() == ISD::AND &&
25266 N0.getOperand(0).hasOneUse()) {
25267 SDValue N00 = N0.getOperand(0);
25268 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25269 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25270 if (!C || C->getZExtValue() != 1)
25272 return DAG.getNode(ISD::AND, dl, VT,
25273 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25274 N00.getOperand(0), N00.getOperand(1)),
25275 DAG.getConstant(1, dl, VT));
25279 if (N0.getOpcode() == ISD::TRUNCATE &&
25281 N0.getOperand(0).hasOneUse()) {
25282 SDValue N00 = N0.getOperand(0);
25283 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25284 return DAG.getNode(ISD::AND, dl, VT,
25285 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25286 N00.getOperand(0), N00.getOperand(1)),
25287 DAG.getConstant(1, dl, VT));
25291 if (VT.is256BitVector())
25292 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25295 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25296 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25297 // This exposes the zext to the udivrem lowering, so that it directly extends
25298 // from AH (which we otherwise need to do contortions to access).
25299 if (N0.getOpcode() == ISD::UDIVREM &&
25300 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25301 (VT == MVT::i32 || VT == MVT::i64)) {
25302 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25303 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25304 N0.getOperand(0), N0.getOperand(1));
25305 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25306 return R.getValue(1);
25312 // Optimize x == -y --> x+y == 0
25313 // x != -y --> x+y != 0
25314 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25315 const X86Subtarget* Subtarget) {
25316 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25317 SDValue LHS = N->getOperand(0);
25318 SDValue RHS = N->getOperand(1);
25319 EVT VT = N->getValueType(0);
25322 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25323 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25324 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25325 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25326 LHS.getOperand(1));
25327 return DAG.getSetCC(DL, N->getValueType(0), addV,
25328 DAG.getConstant(0, DL, addV.getValueType()), CC);
25330 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25331 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25332 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25333 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25334 RHS.getOperand(1));
25335 return DAG.getSetCC(DL, N->getValueType(0), addV,
25336 DAG.getConstant(0, DL, addV.getValueType()), CC);
25339 if (VT.getScalarType() == MVT::i1 &&
25340 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25342 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25343 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25344 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25346 if (!IsSEXT0 || !IsVZero1) {
25347 // Swap the operands and update the condition code.
25348 std::swap(LHS, RHS);
25349 CC = ISD::getSetCCSwappedOperands(CC);
25351 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25352 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25353 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25356 if (IsSEXT0 && IsVZero1) {
25357 assert(VT == LHS.getOperand(0).getValueType() &&
25358 "Uexpected operand type");
25359 if (CC == ISD::SETGT)
25360 return DAG.getConstant(0, DL, VT);
25361 if (CC == ISD::SETLE)
25362 return DAG.getConstant(1, DL, VT);
25363 if (CC == ISD::SETEQ || CC == ISD::SETGE)
25364 return DAG.getNOT(DL, LHS.getOperand(0), VT);
25366 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25367 "Unexpected condition code!");
25368 return LHS.getOperand(0);
25375 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25376 SelectionDAG &DAG) {
25378 MVT VT = Load->getSimpleValueType(0);
25379 MVT EVT = VT.getVectorElementType();
25380 SDValue Addr = Load->getOperand(1);
25381 SDValue NewAddr = DAG.getNode(
25382 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25383 DAG.getConstant(Index * EVT.getStoreSize(), dl,
25384 Addr.getSimpleValueType()));
25387 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25388 DAG.getMachineFunction().getMachineMemOperand(
25389 Load->getMemOperand(), 0, EVT.getStoreSize()));
25393 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25394 const X86Subtarget *Subtarget) {
25396 MVT VT = N->getOperand(1)->getSimpleValueType(0);
25397 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25398 "X86insertps is only defined for v4x32");
25400 SDValue Ld = N->getOperand(1);
25401 if (MayFoldLoad(Ld)) {
25402 // Extract the countS bits from the immediate so we can get the proper
25403 // address when narrowing the vector load to a specific element.
25404 // When the second source op is a memory address, insertps doesn't use
25405 // countS and just gets an f32 from that address.
25406 unsigned DestIndex =
25407 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25409 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25411 // Create this as a scalar to vector to match the instruction pattern.
25412 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25413 // countS bits are ignored when loading from memory on insertps, which
25414 // means we don't need to explicitly set them to 0.
25415 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25416 LoadScalarToVector, N->getOperand(2));
25421 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25422 SDValue V0 = N->getOperand(0);
25423 SDValue V1 = N->getOperand(1);
25425 EVT VT = N->getValueType(0);
25427 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25428 // operands and changing the mask to 1. This saves us a bunch of
25429 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25430 // x86InstrInfo knows how to commute this back after instruction selection
25431 // if it would help register allocation.
25433 // TODO: If optimizing for size or a processor that doesn't suffer from
25434 // partial register update stalls, this should be transformed into a MOVSD
25435 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25437 if (VT == MVT::v2f64)
25438 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25439 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25440 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25441 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25447 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25448 // as "sbb reg,reg", since it can be extended without zext and produces
25449 // an all-ones bit which is more useful than 0/1 in some cases.
25450 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25453 return DAG.getNode(ISD::AND, DL, VT,
25454 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25455 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25457 DAG.getConstant(1, DL, VT));
25458 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25459 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25460 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25461 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25465 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25466 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25467 TargetLowering::DAGCombinerInfo &DCI,
25468 const X86Subtarget *Subtarget) {
25470 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25471 SDValue EFLAGS = N->getOperand(1);
25473 if (CC == X86::COND_A) {
25474 // Try to convert COND_A into COND_B in an attempt to facilitate
25475 // materializing "setb reg".
25477 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25478 // cannot take an immediate as its first operand.
25480 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25481 EFLAGS.getValueType().isInteger() &&
25482 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25483 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25484 EFLAGS.getNode()->getVTList(),
25485 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25486 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25487 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25491 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25492 // a zext and produces an all-ones bit which is more useful than 0/1 in some
25494 if (CC == X86::COND_B)
25495 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25497 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25498 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25499 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25505 // Optimize branch condition evaluation.
25507 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25508 TargetLowering::DAGCombinerInfo &DCI,
25509 const X86Subtarget *Subtarget) {
25511 SDValue Chain = N->getOperand(0);
25512 SDValue Dest = N->getOperand(1);
25513 SDValue EFLAGS = N->getOperand(3);
25514 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25516 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25517 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25518 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25525 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25526 SelectionDAG &DAG) {
25527 // Take advantage of vector comparisons producing 0 or -1 in each lane to
25528 // optimize away operation when it's from a constant.
25530 // The general transformation is:
25531 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25532 // AND(VECTOR_CMP(x,y), constant2)
25533 // constant2 = UNARYOP(constant)
25535 // Early exit if this isn't a vector operation, the operand of the
25536 // unary operation isn't a bitwise AND, or if the sizes of the operations
25537 // aren't the same.
25538 EVT VT = N->getValueType(0);
25539 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25540 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25541 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25544 // Now check that the other operand of the AND is a constant. We could
25545 // make the transformation for non-constant splats as well, but it's unclear
25546 // that would be a benefit as it would not eliminate any operations, just
25547 // perform one more step in scalar code before moving to the vector unit.
25548 if (BuildVectorSDNode *BV =
25549 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25550 // Bail out if the vector isn't a constant.
25551 if (!BV->isConstant())
25554 // Everything checks out. Build up the new and improved node.
25556 EVT IntVT = BV->getValueType(0);
25557 // Create a new constant of the appropriate type for the transformed
25559 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25560 // The AND node needs bitcasts to/from an integer vector type around it.
25561 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25562 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25563 N->getOperand(0)->getOperand(0), MaskConst);
25564 SDValue Res = DAG.getBitcast(VT, NewAnd);
25571 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25572 const X86Subtarget *Subtarget) {
25573 SDValue Op0 = N->getOperand(0);
25574 EVT VT = N->getValueType(0);
25575 EVT InVT = Op0.getValueType();
25576 EVT InSVT = InVT.getScalarType();
25577 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25579 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25580 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25581 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25583 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25584 InVT.getVectorNumElements());
25585 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25587 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25588 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25590 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25596 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25597 const X86Subtarget *Subtarget) {
25598 // First try to optimize away the conversion entirely when it's
25599 // conditionally from a constant. Vectors only.
25600 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25603 // Now move on to more general possibilities.
25604 SDValue Op0 = N->getOperand(0);
25605 EVT VT = N->getValueType(0);
25606 EVT InVT = Op0.getValueType();
25607 EVT InSVT = InVT.getScalarType();
25609 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25610 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25611 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25613 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25614 InVT.getVectorNumElements());
25615 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25616 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25619 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25620 // a 32-bit target where SSE doesn't support i64->FP operations.
25621 if (Op0.getOpcode() == ISD::LOAD) {
25622 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25623 EVT LdVT = Ld->getValueType(0);
25625 // This transformation is not supported if the result type is f16
25626 if (VT == MVT::f16)
25629 if (!Ld->isVolatile() && !VT.isVector() &&
25630 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25631 !Subtarget->is64Bit() && LdVT == MVT::i64) {
25632 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25633 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25634 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25641 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25642 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25643 X86TargetLowering::DAGCombinerInfo &DCI) {
25644 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25645 // the result is either zero or one (depending on the input carry bit).
25646 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25647 if (X86::isZeroNode(N->getOperand(0)) &&
25648 X86::isZeroNode(N->getOperand(1)) &&
25649 // We don't have a good way to replace an EFLAGS use, so only do this when
25651 SDValue(N, 1).use_empty()) {
25653 EVT VT = N->getValueType(0);
25654 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25655 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25656 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25657 DAG.getConstant(X86::COND_B, DL,
25660 DAG.getConstant(1, DL, VT));
25661 return DCI.CombineTo(N, Res1, CarryOut);
25667 // fold (add Y, (sete X, 0)) -> adc 0, Y
25668 // (add Y, (setne X, 0)) -> sbb -1, Y
25669 // (sub (sete X, 0), Y) -> sbb 0, Y
25670 // (sub (setne X, 0), Y) -> adc -1, Y
25671 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25674 // Look through ZExts.
25675 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25676 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25679 SDValue SetCC = Ext.getOperand(0);
25680 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25683 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25684 if (CC != X86::COND_E && CC != X86::COND_NE)
25687 SDValue Cmp = SetCC.getOperand(1);
25688 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25689 !X86::isZeroNode(Cmp.getOperand(1)) ||
25690 !Cmp.getOperand(0).getValueType().isInteger())
25693 SDValue CmpOp0 = Cmp.getOperand(0);
25694 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25695 DAG.getConstant(1, DL, CmpOp0.getValueType()));
25697 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25698 if (CC == X86::COND_NE)
25699 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25700 DL, OtherVal.getValueType(), OtherVal,
25701 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25703 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25704 DL, OtherVal.getValueType(), OtherVal,
25705 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25708 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25709 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25710 const X86Subtarget *Subtarget) {
25711 EVT VT = N->getValueType(0);
25712 SDValue Op0 = N->getOperand(0);
25713 SDValue Op1 = N->getOperand(1);
25715 // Try to synthesize horizontal adds from adds of shuffles.
25716 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25717 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25718 isHorizontalBinOp(Op0, Op1, true))
25719 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25721 return OptimizeConditionalInDecrement(N, DAG);
25724 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25725 const X86Subtarget *Subtarget) {
25726 SDValue Op0 = N->getOperand(0);
25727 SDValue Op1 = N->getOperand(1);
25729 // X86 can't encode an immediate LHS of a sub. See if we can push the
25730 // negation into a preceding instruction.
25731 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25732 // If the RHS of the sub is a XOR with one use and a constant, invert the
25733 // immediate. Then add one to the LHS of the sub so we can turn
25734 // X-Y -> X+~Y+1, saving one register.
25735 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25736 isa<ConstantSDNode>(Op1.getOperand(1))) {
25737 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25738 EVT VT = Op0.getValueType();
25739 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25741 DAG.getConstant(~XorC, SDLoc(Op1), VT));
25742 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25743 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25747 // Try to synthesize horizontal adds from adds of shuffles.
25748 EVT VT = N->getValueType(0);
25749 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25750 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25751 isHorizontalBinOp(Op0, Op1, true))
25752 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25754 return OptimizeConditionalInDecrement(N, DAG);
25757 /// performVZEXTCombine - Performs build vector combines
25758 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25759 TargetLowering::DAGCombinerInfo &DCI,
25760 const X86Subtarget *Subtarget) {
25762 MVT VT = N->getSimpleValueType(0);
25763 SDValue Op = N->getOperand(0);
25764 MVT OpVT = Op.getSimpleValueType();
25765 MVT OpEltVT = OpVT.getVectorElementType();
25766 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25768 // (vzext (bitcast (vzext (x)) -> (vzext x)
25770 while (V.getOpcode() == ISD::BITCAST)
25771 V = V.getOperand(0);
25773 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25774 MVT InnerVT = V.getSimpleValueType();
25775 MVT InnerEltVT = InnerVT.getVectorElementType();
25777 // If the element sizes match exactly, we can just do one larger vzext. This
25778 // is always an exact type match as vzext operates on integer types.
25779 if (OpEltVT == InnerEltVT) {
25780 assert(OpVT == InnerVT && "Types must match for vzext!");
25781 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25784 // The only other way we can combine them is if only a single element of the
25785 // inner vzext is used in the input to the outer vzext.
25786 if (InnerEltVT.getSizeInBits() < InputBits)
25789 // In this case, the inner vzext is completely dead because we're going to
25790 // only look at bits inside of the low element. Just do the outer vzext on
25791 // a bitcast of the input to the inner.
25792 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25795 // Check if we can bypass extracting and re-inserting an element of an input
25796 // vector. Essentially:
25797 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25798 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25799 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25800 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25801 SDValue ExtractedV = V.getOperand(0);
25802 SDValue OrigV = ExtractedV.getOperand(0);
25803 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25804 if (ExtractIdx->getZExtValue() == 0) {
25805 MVT OrigVT = OrigV.getSimpleValueType();
25806 // Extract a subvector if necessary...
25807 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25808 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25809 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25810 OrigVT.getVectorNumElements() / Ratio);
25811 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25812 DAG.getIntPtrConstant(0, DL));
25814 Op = DAG.getBitcast(OpVT, OrigV);
25815 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25822 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25823 DAGCombinerInfo &DCI) const {
25824 SelectionDAG &DAG = DCI.DAG;
25825 switch (N->getOpcode()) {
25827 case ISD::EXTRACT_VECTOR_ELT:
25828 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25831 case X86ISD::SHRUNKBLEND:
25832 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25833 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
25834 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25835 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
25836 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
25837 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
25838 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
25841 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
25842 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
25843 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
25844 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
25845 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
25846 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25847 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
25848 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
25849 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25850 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25851 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
25852 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
25854 case X86ISD::FOR: return PerformFORCombine(N, DAG);
25856 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
25857 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
25858 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
25859 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
25860 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
25861 case ISD::ANY_EXTEND:
25862 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
25863 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
25864 case ISD::SIGN_EXTEND_INREG:
25865 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25866 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
25867 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25868 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25869 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
25870 case X86ISD::SHUFP: // Handle all target specific shuffles
25871 case X86ISD::PALIGNR:
25872 case X86ISD::UNPCKH:
25873 case X86ISD::UNPCKL:
25874 case X86ISD::MOVHLPS:
25875 case X86ISD::MOVLHPS:
25876 case X86ISD::PSHUFB:
25877 case X86ISD::PSHUFD:
25878 case X86ISD::PSHUFHW:
25879 case X86ISD::PSHUFLW:
25880 case X86ISD::MOVSS:
25881 case X86ISD::MOVSD:
25882 case X86ISD::VPERMILPI:
25883 case X86ISD::VPERM2X128:
25884 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25885 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
25886 case X86ISD::INSERTPS: {
25887 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25888 return PerformINSERTPSCombine(N, DAG, Subtarget);
25891 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
25897 /// isTypeDesirableForOp - Return true if the target has native support for
25898 /// the specified value type and it is 'desirable' to use the type for the
25899 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25900 /// instruction encodings are longer and some i16 instructions are slow.
25901 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25902 if (!isTypeLegal(VT))
25904 if (VT != MVT::i16)
25911 case ISD::SIGN_EXTEND:
25912 case ISD::ZERO_EXTEND:
25913 case ISD::ANY_EXTEND:
25926 /// IsDesirableToPromoteOp - This method query the target whether it is
25927 /// beneficial for dag combiner to promote the specified node. If true, it
25928 /// should return the desired promotion type by reference.
25929 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25930 EVT VT = Op.getValueType();
25931 if (VT != MVT::i16)
25934 bool Promote = false;
25935 bool Commute = false;
25936 switch (Op.getOpcode()) {
25939 LoadSDNode *LD = cast<LoadSDNode>(Op);
25940 // If the non-extending load has a single use and it's not live out, then it
25941 // might be folded.
25942 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25943 Op.hasOneUse()*/) {
25944 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25945 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25946 // The only case where we'd want to promote LOAD (rather then it being
25947 // promoted as an operand is when it's only use is liveout.
25948 if (UI->getOpcode() != ISD::CopyToReg)
25955 case ISD::SIGN_EXTEND:
25956 case ISD::ZERO_EXTEND:
25957 case ISD::ANY_EXTEND:
25962 SDValue N0 = Op.getOperand(0);
25963 // Look out for (store (shl (load), x)).
25964 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25977 SDValue N0 = Op.getOperand(0);
25978 SDValue N1 = Op.getOperand(1);
25979 if (!Commute && MayFoldLoad(N1))
25981 // Avoid disabling potential load folding opportunities.
25982 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25984 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25994 //===----------------------------------------------------------------------===//
25995 // X86 Inline Assembly Support
25996 //===----------------------------------------------------------------------===//
25998 // Helper to match a string separated by whitespace.
25999 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
26000 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
26002 for (StringRef Piece : Pieces) {
26003 if (!S.startswith(Piece)) // Check if the piece matches.
26006 S = S.substr(Piece.size());
26007 StringRef::size_type Pos = S.find_first_not_of(" \t");
26008 if (Pos == 0) // We matched a prefix.
26017 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
26019 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
26020 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
26021 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
26022 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
26024 if (AsmPieces.size() == 3)
26026 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
26033 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
26034 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
26036 std::string AsmStr = IA->getAsmString();
26038 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
26039 if (!Ty || Ty->getBitWidth() % 16 != 0)
26042 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
26043 SmallVector<StringRef, 4> AsmPieces;
26044 SplitString(AsmStr, AsmPieces, ";\n");
26046 switch (AsmPieces.size()) {
26047 default: return false;
26049 // FIXME: this should verify that we are targeting a 486 or better. If not,
26050 // we will turn this bswap into something that will be lowered to logical
26051 // ops instead of emitting the bswap asm. For now, we don't support 486 or
26052 // lower so don't worry about this.
26054 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
26055 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
26056 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
26057 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
26058 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
26059 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
26060 // No need to check constraints, nothing other than the equivalent of
26061 // "=r,0" would be valid here.
26062 return IntrinsicLowering::LowerToByteSwap(CI);
26065 // rorw $$8, ${0:w} --> llvm.bswap.i16
26066 if (CI->getType()->isIntegerTy(16) &&
26067 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26068 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
26069 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
26071 StringRef ConstraintsStr = IA->getConstraintString();
26072 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26073 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26074 if (clobbersFlagRegisters(AsmPieces))
26075 return IntrinsicLowering::LowerToByteSwap(CI);
26079 if (CI->getType()->isIntegerTy(32) &&
26080 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
26081 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
26082 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
26083 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
26085 StringRef ConstraintsStr = IA->getConstraintString();
26086 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
26087 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
26088 if (clobbersFlagRegisters(AsmPieces))
26089 return IntrinsicLowering::LowerToByteSwap(CI);
26092 if (CI->getType()->isIntegerTy(64)) {
26093 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
26094 if (Constraints.size() >= 2 &&
26095 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
26096 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
26097 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
26098 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
26099 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
26100 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26101 return IntrinsicLowering::LowerToByteSwap(CI);
26109 /// getConstraintType - Given a constraint letter, return the type of
26110 /// constraint it is for this target.
26111 X86TargetLowering::ConstraintType
26112 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26113 if (Constraint.size() == 1) {
26114 switch (Constraint[0]) {
26125 return C_RegisterClass;
26149 return TargetLowering::getConstraintType(Constraint);
26152 /// Examine constraint type and operand type and determine a weight value.
26153 /// This object must already have been set up with the operand type
26154 /// and the current alternative constraint selected.
26155 TargetLowering::ConstraintWeight
26156 X86TargetLowering::getSingleConstraintMatchWeight(
26157 AsmOperandInfo &info, const char *constraint) const {
26158 ConstraintWeight weight = CW_Invalid;
26159 Value *CallOperandVal = info.CallOperandVal;
26160 // If we don't have a value, we can't do a match,
26161 // but allow it at the lowest weight.
26162 if (!CallOperandVal)
26164 Type *type = CallOperandVal->getType();
26165 // Look at the constraint type.
26166 switch (*constraint) {
26168 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26179 if (CallOperandVal->getType()->isIntegerTy())
26180 weight = CW_SpecificReg;
26185 if (type->isFloatingPointTy())
26186 weight = CW_SpecificReg;
26189 if (type->isX86_MMXTy() && Subtarget->hasMMX())
26190 weight = CW_SpecificReg;
26194 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26195 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26196 weight = CW_Register;
26199 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26200 if (C->getZExtValue() <= 31)
26201 weight = CW_Constant;
26205 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26206 if (C->getZExtValue() <= 63)
26207 weight = CW_Constant;
26211 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26212 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26213 weight = CW_Constant;
26217 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26218 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26219 weight = CW_Constant;
26223 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26224 if (C->getZExtValue() <= 3)
26225 weight = CW_Constant;
26229 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26230 if (C->getZExtValue() <= 0xff)
26231 weight = CW_Constant;
26236 if (isa<ConstantFP>(CallOperandVal)) {
26237 weight = CW_Constant;
26241 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26242 if ((C->getSExtValue() >= -0x80000000LL) &&
26243 (C->getSExtValue() <= 0x7fffffffLL))
26244 weight = CW_Constant;
26248 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26249 if (C->getZExtValue() <= 0xffffffff)
26250 weight = CW_Constant;
26257 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26258 /// with another that has more specific requirements based on the type of the
26259 /// corresponding operand.
26260 const char *X86TargetLowering::
26261 LowerXConstraint(EVT ConstraintVT) const {
26262 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26263 // 'f' like normal targets.
26264 if (ConstraintVT.isFloatingPoint()) {
26265 if (Subtarget->hasSSE2())
26267 if (Subtarget->hasSSE1())
26271 return TargetLowering::LowerXConstraint(ConstraintVT);
26274 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26275 /// vector. If it is invalid, don't add anything to Ops.
26276 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26277 std::string &Constraint,
26278 std::vector<SDValue>&Ops,
26279 SelectionDAG &DAG) const {
26282 // Only support length 1 constraints for now.
26283 if (Constraint.length() > 1) return;
26285 char ConstraintLetter = Constraint[0];
26286 switch (ConstraintLetter) {
26289 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26290 if (C->getZExtValue() <= 31) {
26291 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26292 Op.getValueType());
26298 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26299 if (C->getZExtValue() <= 63) {
26300 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26301 Op.getValueType());
26307 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26308 if (isInt<8>(C->getSExtValue())) {
26309 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26310 Op.getValueType());
26316 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26317 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26318 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26319 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26320 Op.getValueType());
26326 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26327 if (C->getZExtValue() <= 3) {
26328 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26329 Op.getValueType());
26335 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26336 if (C->getZExtValue() <= 255) {
26337 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26338 Op.getValueType());
26344 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26345 if (C->getZExtValue() <= 127) {
26346 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26347 Op.getValueType());
26353 // 32-bit signed value
26354 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26355 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26356 C->getSExtValue())) {
26357 // Widen to 64 bits here to get it sign extended.
26358 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26361 // FIXME gcc accepts some relocatable values here too, but only in certain
26362 // memory models; it's complicated.
26367 // 32-bit unsigned value
26368 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26369 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26370 C->getZExtValue())) {
26371 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26372 Op.getValueType());
26376 // FIXME gcc accepts some relocatable values here too, but only in certain
26377 // memory models; it's complicated.
26381 // Literal immediates are always ok.
26382 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26383 // Widen to 64 bits here to get it sign extended.
26384 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26388 // In any sort of PIC mode addresses need to be computed at runtime by
26389 // adding in a register or some sort of table lookup. These can't
26390 // be used as immediates.
26391 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26394 // If we are in non-pic codegen mode, we allow the address of a global (with
26395 // an optional displacement) to be used with 'i'.
26396 GlobalAddressSDNode *GA = nullptr;
26397 int64_t Offset = 0;
26399 // Match either (GA), (GA+C), (GA+C1+C2), etc.
26401 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26402 Offset += GA->getOffset();
26404 } else if (Op.getOpcode() == ISD::ADD) {
26405 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26406 Offset += C->getZExtValue();
26407 Op = Op.getOperand(0);
26410 } else if (Op.getOpcode() == ISD::SUB) {
26411 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26412 Offset += -C->getZExtValue();
26413 Op = Op.getOperand(0);
26418 // Otherwise, this isn't something we can handle, reject it.
26422 const GlobalValue *GV = GA->getGlobal();
26423 // If we require an extra load to get this address, as in PIC mode, we
26424 // can't accept it.
26425 if (isGlobalStubReference(
26426 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26429 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26430 GA->getValueType(0), Offset);
26435 if (Result.getNode()) {
26436 Ops.push_back(Result);
26439 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26442 std::pair<unsigned, const TargetRegisterClass *>
26443 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26444 StringRef Constraint,
26446 // First, see if this is a constraint that directly corresponds to an LLVM
26448 if (Constraint.size() == 1) {
26449 // GCC Constraint Letters
26450 switch (Constraint[0]) {
26452 // TODO: Slight differences here in allocation order and leaving
26453 // RIP in the class. Do they matter any more here than they do
26454 // in the normal allocation?
26455 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26456 if (Subtarget->is64Bit()) {
26457 if (VT == MVT::i32 || VT == MVT::f32)
26458 return std::make_pair(0U, &X86::GR32RegClass);
26459 if (VT == MVT::i16)
26460 return std::make_pair(0U, &X86::GR16RegClass);
26461 if (VT == MVT::i8 || VT == MVT::i1)
26462 return std::make_pair(0U, &X86::GR8RegClass);
26463 if (VT == MVT::i64 || VT == MVT::f64)
26464 return std::make_pair(0U, &X86::GR64RegClass);
26467 // 32-bit fallthrough
26468 case 'Q': // Q_REGS
26469 if (VT == MVT::i32 || VT == MVT::f32)
26470 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26471 if (VT == MVT::i16)
26472 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26473 if (VT == MVT::i8 || VT == MVT::i1)
26474 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26475 if (VT == MVT::i64)
26476 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26478 case 'r': // GENERAL_REGS
26479 case 'l': // INDEX_REGS
26480 if (VT == MVT::i8 || VT == MVT::i1)
26481 return std::make_pair(0U, &X86::GR8RegClass);
26482 if (VT == MVT::i16)
26483 return std::make_pair(0U, &X86::GR16RegClass);
26484 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26485 return std::make_pair(0U, &X86::GR32RegClass);
26486 return std::make_pair(0U, &X86::GR64RegClass);
26487 case 'R': // LEGACY_REGS
26488 if (VT == MVT::i8 || VT == MVT::i1)
26489 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26490 if (VT == MVT::i16)
26491 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26492 if (VT == MVT::i32 || !Subtarget->is64Bit())
26493 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26494 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26495 case 'f': // FP Stack registers.
26496 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26497 // value to the correct fpstack register class.
26498 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26499 return std::make_pair(0U, &X86::RFP32RegClass);
26500 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26501 return std::make_pair(0U, &X86::RFP64RegClass);
26502 return std::make_pair(0U, &X86::RFP80RegClass);
26503 case 'y': // MMX_REGS if MMX allowed.
26504 if (!Subtarget->hasMMX()) break;
26505 return std::make_pair(0U, &X86::VR64RegClass);
26506 case 'Y': // SSE_REGS if SSE2 allowed
26507 if (!Subtarget->hasSSE2()) break;
26509 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26510 if (!Subtarget->hasSSE1()) break;
26512 switch (VT.SimpleTy) {
26514 // Scalar SSE types.
26517 return std::make_pair(0U, &X86::FR32RegClass);
26520 return std::make_pair(0U, &X86::FR64RegClass);
26528 return std::make_pair(0U, &X86::VR128RegClass);
26536 return std::make_pair(0U, &X86::VR256RegClass);
26541 return std::make_pair(0U, &X86::VR512RegClass);
26547 // Use the default implementation in TargetLowering to convert the register
26548 // constraint into a member of a register class.
26549 std::pair<unsigned, const TargetRegisterClass*> Res;
26550 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26552 // Not found as a standard register?
26554 // Map st(0) -> st(7) -> ST0
26555 if (Constraint.size() == 7 && Constraint[0] == '{' &&
26556 tolower(Constraint[1]) == 's' &&
26557 tolower(Constraint[2]) == 't' &&
26558 Constraint[3] == '(' &&
26559 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26560 Constraint[5] == ')' &&
26561 Constraint[6] == '}') {
26563 Res.first = X86::FP0+Constraint[4]-'0';
26564 Res.second = &X86::RFP80RegClass;
26568 // GCC allows "st(0)" to be called just plain "st".
26569 if (StringRef("{st}").equals_lower(Constraint)) {
26570 Res.first = X86::FP0;
26571 Res.second = &X86::RFP80RegClass;
26576 if (StringRef("{flags}").equals_lower(Constraint)) {
26577 Res.first = X86::EFLAGS;
26578 Res.second = &X86::CCRRegClass;
26582 // 'A' means EAX + EDX.
26583 if (Constraint == "A") {
26584 Res.first = X86::EAX;
26585 Res.second = &X86::GR32_ADRegClass;
26591 // Otherwise, check to see if this is a register class of the wrong value
26592 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26593 // turn into {ax},{dx}.
26594 // MVT::Other is used to specify clobber names.
26595 if (Res.second->hasType(VT) || VT == MVT::Other)
26596 return Res; // Correct type already, nothing to do.
26598 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26599 // return "eax". This should even work for things like getting 64bit integer
26600 // registers when given an f64 type.
26601 const TargetRegisterClass *Class = Res.second;
26602 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26603 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26604 unsigned Size = VT.getSizeInBits();
26605 MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26606 : Size == 16 ? MVT::i16
26607 : Size == 32 ? MVT::i32
26608 : Size == 64 ? MVT::i64
26610 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26612 Res.first = DestReg;
26613 Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26614 : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26615 : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26616 : &X86::GR64RegClass;
26617 assert(Res.second->contains(Res.first) && "Register in register class");
26619 // No register found/type mismatch.
26621 Res.second = nullptr;
26623 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26624 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26625 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26626 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26627 Class == &X86::VR512RegClass) {
26628 // Handle references to XMM physical registers that got mapped into the
26629 // wrong class. This can happen with constraints like {xmm0} where the
26630 // target independent register mapper will just pick the first match it can
26631 // find, ignoring the required type.
26633 if (VT == MVT::f32 || VT == MVT::i32)
26634 Res.second = &X86::FR32RegClass;
26635 else if (VT == MVT::f64 || VT == MVT::i64)
26636 Res.second = &X86::FR64RegClass;
26637 else if (X86::VR128RegClass.hasType(VT))
26638 Res.second = &X86::VR128RegClass;
26639 else if (X86::VR256RegClass.hasType(VT))
26640 Res.second = &X86::VR256RegClass;
26641 else if (X86::VR512RegClass.hasType(VT))
26642 Res.second = &X86::VR512RegClass;
26644 // Type mismatch and not a clobber: Return an error;
26646 Res.second = nullptr;
26653 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26654 const AddrMode &AM, Type *Ty,
26655 unsigned AS) const {
26656 // Scaling factors are not free at all.
26657 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26658 // will take 2 allocations in the out of order engine instead of 1
26659 // for plain addressing mode, i.e. inst (reg1).
26661 // vaddps (%rsi,%drx), %ymm0, %ymm1
26662 // Requires two allocations (one for the load, one for the computation)
26664 // vaddps (%rsi), %ymm0, %ymm1
26665 // Requires just 1 allocation, i.e., freeing allocations for other operations
26666 // and having less micro operations to execute.
26668 // For some X86 architectures, this is even worse because for instance for
26669 // stores, the complex addressing mode forces the instruction to use the
26670 // "load" ports instead of the dedicated "store" port.
26671 // E.g., on Haswell:
26672 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26673 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26674 if (isLegalAddressingMode(DL, AM, Ty, AS))
26675 // Scale represents reg2 * scale, thus account for 1
26676 // as soon as we use a second register.
26677 return AM.Scale != 0;
26681 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
26682 // Integer division on x86 is expensive. However, when aggressively optimizing
26683 // for code size, we prefer to use a div instruction, as it is usually smaller
26684 // than the alternative sequence.
26685 // The exception to this is vector division. Since x86 doesn't have vector
26686 // integer division, leaving the division as-is is a loss even in terms of
26687 // size, because it will have to be scalarized, while the alternative code
26688 // sequence can be performed in vector form.
26689 bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
26690 Attribute::MinSize);
26691 return OptSize && !VT.isVector();