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/Analysis/EHPersonalities.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/WinEHFuncInfo.h"
37 #include "llvm/IR/CallSite.h"
38 #include "llvm/IR/CallingConv.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/GlobalAlias.h"
43 #include "llvm/IR/GlobalVariable.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/MC/MCAsmInfo.h"
47 #include "llvm/MC/MCContext.h"
48 #include "llvm/MC/MCExpr.h"
49 #include "llvm/MC/MCSymbol.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Target/TargetOptions.h"
55 #include "X86IntrinsicsInfo.h"
61 #define DEBUG_TYPE "x86-isel"
63 STATISTIC(NumTailCalls, "Number of tail calls");
65 static cl::opt<bool> ExperimentalVectorWideningLegalization(
66 "x86-experimental-vector-widening-legalization", cl::init(false),
67 cl::desc("Enable an experimental vector type legalization through widening "
68 "rather than promotion."),
71 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
72 const X86Subtarget &STI)
73 : TargetLowering(TM), Subtarget(&STI) {
74 X86ScalarSSEf64 = Subtarget->hasSSE2();
75 X86ScalarSSEf32 = Subtarget->hasSSE1();
76 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
78 // Set up the TargetLowering object.
80 // X86 is weird. It always uses i8 for shift amounts and setcc results.
81 setBooleanContents(ZeroOrOneBooleanContent);
82 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
83 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
85 // For 64-bit, since we have so many registers, use the ILP scheduler.
86 // For 32-bit, use the register pressure specific scheduling.
87 // For Atom, always use ILP scheduling.
88 if (Subtarget->isAtom())
89 setSchedulingPreference(Sched::ILP);
90 else if (Subtarget->is64Bit())
91 setSchedulingPreference(Sched::ILP);
93 setSchedulingPreference(Sched::RegPressure);
94 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
95 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
97 // Bypass expensive divides on Atom when compiling with O2.
98 if (TM.getOptLevel() >= CodeGenOpt::Default) {
99 if (Subtarget->hasSlowDivide32())
100 addBypassSlowDiv(32, 8);
101 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
102 addBypassSlowDiv(64, 16);
105 if (Subtarget->isTargetKnownWindowsMSVC()) {
106 // Setup Windows compiler runtime calls.
107 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
108 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
109 setLibcallName(RTLIB::SREM_I64, "_allrem");
110 setLibcallName(RTLIB::UREM_I64, "_aullrem");
111 setLibcallName(RTLIB::MUL_I64, "_allmul");
112 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
113 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
114 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
115 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
116 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
119 if (Subtarget->isTargetDarwin()) {
120 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
121 setUseUnderscoreSetJmp(false);
122 setUseUnderscoreLongJmp(false);
123 } else if (Subtarget->isTargetWindowsGNU()) {
124 // MS runtime is weird: it exports _setjmp, but longjmp!
125 setUseUnderscoreSetJmp(true);
126 setUseUnderscoreLongJmp(false);
128 setUseUnderscoreSetJmp(true);
129 setUseUnderscoreLongJmp(true);
132 // Set up the register classes.
133 addRegisterClass(MVT::i8, &X86::GR8RegClass);
134 addRegisterClass(MVT::i16, &X86::GR16RegClass);
135 addRegisterClass(MVT::i32, &X86::GR32RegClass);
136 if (Subtarget->is64Bit())
137 addRegisterClass(MVT::i64, &X86::GR64RegClass);
139 for (MVT VT : MVT::integer_valuetypes())
140 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
142 // We don't accept any truncstore of integer registers.
143 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
144 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
145 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
146 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
147 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
148 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
150 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
152 // SETOEQ and SETUNE require checking two conditions.
153 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
154 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
155 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
156 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
157 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
158 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
160 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
162 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
163 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
164 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
166 if (Subtarget->is64Bit()) {
167 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
168 // f32/f64 are legal, f80 is custom.
169 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
171 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
172 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
173 } else if (!Subtarget->useSoftFloat()) {
174 // We have an algorithm for SSE2->double, and we turn this into a
175 // 64-bit FILD followed by conditional FADD for other targets.
176 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
177 // We have an algorithm for SSE2, and we turn this into a 64-bit
178 // FILD or VCVTUSI2SS/SD for other targets.
179 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
182 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
184 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
185 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
187 if (!Subtarget->useSoftFloat()) {
188 // SSE has no i16 to fp conversion, only i32
189 if (X86ScalarSSEf32) {
190 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
191 // f32 and f64 cases are Legal, f80 case is not
192 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
194 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
195 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
198 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
199 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
202 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
204 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
205 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
207 if (!Subtarget->useSoftFloat()) {
208 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
209 // are Legal, f80 is custom lowered.
210 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
211 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
213 if (X86ScalarSSEf32) {
214 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
215 // f32 and f64 cases are Legal, f80 case is not
216 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
218 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
219 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
222 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
223 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Expand);
224 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Expand);
227 // Handle FP_TO_UINT by promoting the destination to a larger signed
229 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
230 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
231 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
233 if (Subtarget->is64Bit()) {
234 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
235 // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
236 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
237 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
239 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
240 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
242 } else if (!Subtarget->useSoftFloat()) {
243 // Since AVX is a superset of SSE3, only check for SSE here.
244 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
245 // Expand FP_TO_UINT into a select.
246 // FIXME: We would like to use a Custom expander here eventually to do
247 // the optimal thing for SSE vs. the default expansion in the legalizer.
248 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
250 // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
251 // With SSE3 we can use fisttpll to convert to a signed i64; without
252 // SSE, we're stuck with a fistpll.
253 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
255 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
258 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
259 if (!X86ScalarSSEf64) {
260 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
261 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
262 if (Subtarget->is64Bit()) {
263 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
264 // Without SSE, i64->f64 goes through memory.
265 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
269 // Scalar integer divide and remainder are lowered to use operations that
270 // produce two results, to match the available instructions. This exposes
271 // the two-result form to trivial CSE, which is able to combine x/y and x%y
272 // into a single instruction.
274 // Scalar integer multiply-high is also lowered to use two-result
275 // operations, to match the available instructions. However, plain multiply
276 // (low) operations are left as Legal, as there are single-result
277 // instructions for this in x86. Using the two-result multiply instructions
278 // when both high and low results are needed must be arranged by dagcombine.
279 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
280 setOperationAction(ISD::MULHS, VT, Expand);
281 setOperationAction(ISD::MULHU, VT, Expand);
282 setOperationAction(ISD::SDIV, VT, Expand);
283 setOperationAction(ISD::UDIV, VT, Expand);
284 setOperationAction(ISD::SREM, VT, Expand);
285 setOperationAction(ISD::UREM, VT, Expand);
287 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
288 setOperationAction(ISD::ADDC, VT, Custom);
289 setOperationAction(ISD::ADDE, VT, Custom);
290 setOperationAction(ISD::SUBC, VT, Custom);
291 setOperationAction(ISD::SUBE, VT, Custom);
294 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
295 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
296 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
297 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
298 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
299 setOperationAction(ISD::BR_CC , MVT::f128, Expand);
300 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
301 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
302 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
303 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
304 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
305 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
306 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
307 setOperationAction(ISD::SELECT_CC , MVT::f128, Expand);
308 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
309 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
310 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
311 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
312 if (Subtarget->is64Bit())
313 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
314 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
315 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
316 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
317 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
319 if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
320 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
321 // is. We should promote the value to 64-bits to solve this.
322 // This is what the CRT headers do - `fmodf` is an inline header
323 // function casting to f64 and calling `fmod`.
324 setOperationAction(ISD::FREM , MVT::f32 , Promote);
326 setOperationAction(ISD::FREM , MVT::f32 , Expand);
329 setOperationAction(ISD::FREM , MVT::f64 , Expand);
330 setOperationAction(ISD::FREM , MVT::f80 , Expand);
331 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
333 // Promote the i8 variants and force them on up to i32 which has a shorter
335 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
336 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
337 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
338 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
339 if (Subtarget->hasBMI()) {
340 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
341 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
342 if (Subtarget->is64Bit())
343 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
345 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
346 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
347 if (Subtarget->is64Bit())
348 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
351 if (Subtarget->hasLZCNT()) {
352 // When promoting the i8 variants, force them to i32 for a shorter
354 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
355 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
356 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
357 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
358 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
359 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
360 if (Subtarget->is64Bit())
361 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
363 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
364 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
365 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
366 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
367 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
368 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
369 if (Subtarget->is64Bit()) {
370 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
371 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
375 // Special handling for half-precision floating point conversions.
376 // If we don't have F16C support, then lower half float conversions
377 // into library calls.
378 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
379 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
380 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
383 // There's never any support for operations beyond MVT::f32.
384 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
385 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
386 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
387 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
389 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
390 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
391 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
392 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
393 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
394 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
396 if (Subtarget->hasPOPCNT()) {
397 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
399 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
400 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
401 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
402 if (Subtarget->is64Bit())
403 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
406 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
408 if (!Subtarget->hasMOVBE())
409 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
411 // These should be promoted to a larger select which is supported.
412 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
413 // X86 wants to expand cmov itself.
414 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
415 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
416 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
417 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
418 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
419 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
420 setOperationAction(ISD::SELECT , MVT::f128 , Custom);
421 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
422 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
423 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
424 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
425 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
426 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
427 setOperationAction(ISD::SETCC , MVT::f128 , Custom);
428 setOperationAction(ISD::SETCCE , MVT::i8 , Custom);
429 setOperationAction(ISD::SETCCE , MVT::i16 , Custom);
430 setOperationAction(ISD::SETCCE , MVT::i32 , Custom);
431 if (Subtarget->is64Bit()) {
432 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
433 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
434 setOperationAction(ISD::SETCCE , MVT::i64 , Custom);
436 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
437 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
438 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
439 // support continuation, user-level threading, and etc.. As a result, no
440 // other SjLj exception interfaces are implemented and please don't build
441 // your own exception handling based on them.
442 // LLVM/Clang supports zero-cost DWARF exception handling.
443 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
444 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
447 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
448 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
449 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
450 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
451 if (Subtarget->is64Bit())
452 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
453 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
454 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
455 if (Subtarget->is64Bit()) {
456 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
457 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
458 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
459 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
460 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
462 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
463 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
464 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
465 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
466 if (Subtarget->is64Bit()) {
467 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
468 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
469 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
472 if (Subtarget->hasSSE1())
473 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
475 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
477 // Expand certain atomics
478 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
479 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
480 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
481 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
484 if (Subtarget->hasCmpxchg16b()) {
485 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
488 // FIXME - use subtarget debug flags
489 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
490 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
491 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
494 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
495 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
497 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
498 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
500 setOperationAction(ISD::TRAP, MVT::Other, Legal);
501 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
503 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
504 setOperationAction(ISD::VASTART , MVT::Other, Custom);
505 setOperationAction(ISD::VAEND , MVT::Other, Expand);
506 if (Subtarget->is64Bit()) {
507 setOperationAction(ISD::VAARG , MVT::Other, Custom);
508 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
510 // TargetInfo::CharPtrBuiltinVaList
511 setOperationAction(ISD::VAARG , MVT::Other, Expand);
512 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
515 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
516 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
518 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
520 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
521 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
522 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
524 if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
525 // f32 and f64 use SSE.
526 // Set up the FP register classes.
527 addRegisterClass(MVT::f32, &X86::FR32RegClass);
528 addRegisterClass(MVT::f64, &X86::FR64RegClass);
530 // Use ANDPD to simulate FABS.
531 setOperationAction(ISD::FABS , MVT::f64, Custom);
532 setOperationAction(ISD::FABS , MVT::f32, Custom);
534 // Use XORP to simulate FNEG.
535 setOperationAction(ISD::FNEG , MVT::f64, Custom);
536 setOperationAction(ISD::FNEG , MVT::f32, Custom);
538 // Use ANDPD and ORPD to simulate FCOPYSIGN.
539 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
540 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
542 // Lower this to FGETSIGNx86 plus an AND.
543 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
544 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
546 // We don't support sin/cos/fmod
547 setOperationAction(ISD::FSIN , MVT::f64, Expand);
548 setOperationAction(ISD::FCOS , MVT::f64, Expand);
549 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
550 setOperationAction(ISD::FSIN , MVT::f32, Expand);
551 setOperationAction(ISD::FCOS , MVT::f32, Expand);
552 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
554 // Expand FP immediates into loads from the stack, except for the special
556 addLegalFPImmediate(APFloat(+0.0)); // xorpd
557 addLegalFPImmediate(APFloat(+0.0f)); // xorps
558 } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
559 // Use SSE for f32, x87 for f64.
560 // Set up the FP register classes.
561 addRegisterClass(MVT::f32, &X86::FR32RegClass);
562 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
564 // Use ANDPS to simulate FABS.
565 setOperationAction(ISD::FABS , MVT::f32, Custom);
567 // Use XORP to simulate FNEG.
568 setOperationAction(ISD::FNEG , MVT::f32, Custom);
570 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
572 // Use ANDPS and ORPS to simulate FCOPYSIGN.
573 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
574 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
576 // We don't support sin/cos/fmod
577 setOperationAction(ISD::FSIN , MVT::f32, Expand);
578 setOperationAction(ISD::FCOS , MVT::f32, Expand);
579 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
581 // Special cases we handle for FP constants.
582 addLegalFPImmediate(APFloat(+0.0f)); // xorps
583 addLegalFPImmediate(APFloat(+0.0)); // FLD0
584 addLegalFPImmediate(APFloat(+1.0)); // FLD1
585 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
586 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
588 if (!TM.Options.UnsafeFPMath) {
589 setOperationAction(ISD::FSIN , MVT::f64, Expand);
590 setOperationAction(ISD::FCOS , MVT::f64, Expand);
591 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
593 } else if (!Subtarget->useSoftFloat()) {
594 // f32 and f64 in x87.
595 // Set up the FP register classes.
596 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
597 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
599 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
600 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
601 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
602 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
604 if (!TM.Options.UnsafeFPMath) {
605 setOperationAction(ISD::FSIN , MVT::f64, Expand);
606 setOperationAction(ISD::FSIN , MVT::f32, Expand);
607 setOperationAction(ISD::FCOS , MVT::f64, Expand);
608 setOperationAction(ISD::FCOS , MVT::f32, Expand);
609 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
610 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
612 addLegalFPImmediate(APFloat(+0.0)); // FLD0
613 addLegalFPImmediate(APFloat(+1.0)); // FLD1
614 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
615 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
616 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
617 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
618 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
619 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
622 // We don't support FMA.
623 setOperationAction(ISD::FMA, MVT::f64, Expand);
624 setOperationAction(ISD::FMA, MVT::f32, Expand);
626 // Long double always uses X87, except f128 in MMX.
627 if (!Subtarget->useSoftFloat()) {
628 if (Subtarget->is64Bit() && Subtarget->hasMMX()) {
629 addRegisterClass(MVT::f128, &X86::FR128RegClass);
630 ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
631 setOperationAction(ISD::FABS , MVT::f128, Custom);
632 setOperationAction(ISD::FNEG , MVT::f128, Custom);
633 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
636 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
637 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
638 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
640 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
641 addLegalFPImmediate(TmpFlt); // FLD0
643 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
646 APFloat TmpFlt2(+1.0);
647 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
649 addLegalFPImmediate(TmpFlt2); // FLD1
650 TmpFlt2.changeSign();
651 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
654 if (!TM.Options.UnsafeFPMath) {
655 setOperationAction(ISD::FSIN , MVT::f80, Expand);
656 setOperationAction(ISD::FCOS , MVT::f80, Expand);
657 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
660 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
661 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
662 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
663 setOperationAction(ISD::FRINT, MVT::f80, Expand);
664 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
665 setOperationAction(ISD::FMA, MVT::f80, Expand);
668 // Always use a library call for pow.
669 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
670 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
671 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
673 setOperationAction(ISD::FLOG, MVT::f80, Expand);
674 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
675 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
676 setOperationAction(ISD::FEXP, MVT::f80, Expand);
677 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
678 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
679 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
681 // First set operation action for all vector types to either promote
682 // (for widening) or expand (for scalarization). Then we will selectively
683 // turn on ones that can be effectively codegen'd.
684 for (MVT VT : MVT::vector_valuetypes()) {
685 setOperationAction(ISD::ADD , VT, Expand);
686 setOperationAction(ISD::SUB , VT, Expand);
687 setOperationAction(ISD::FADD, VT, Expand);
688 setOperationAction(ISD::FNEG, VT, Expand);
689 setOperationAction(ISD::FSUB, VT, Expand);
690 setOperationAction(ISD::MUL , VT, Expand);
691 setOperationAction(ISD::FMUL, VT, Expand);
692 setOperationAction(ISD::SDIV, VT, Expand);
693 setOperationAction(ISD::UDIV, VT, Expand);
694 setOperationAction(ISD::FDIV, VT, Expand);
695 setOperationAction(ISD::SREM, VT, Expand);
696 setOperationAction(ISD::UREM, VT, Expand);
697 setOperationAction(ISD::LOAD, VT, Expand);
698 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
699 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
700 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
701 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
702 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
703 setOperationAction(ISD::FABS, VT, Expand);
704 setOperationAction(ISD::FSIN, VT, Expand);
705 setOperationAction(ISD::FSINCOS, VT, Expand);
706 setOperationAction(ISD::FCOS, VT, Expand);
707 setOperationAction(ISD::FSINCOS, VT, Expand);
708 setOperationAction(ISD::FREM, VT, Expand);
709 setOperationAction(ISD::FMA, VT, Expand);
710 setOperationAction(ISD::FPOWI, VT, Expand);
711 setOperationAction(ISD::FSQRT, VT, Expand);
712 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
713 setOperationAction(ISD::FFLOOR, VT, Expand);
714 setOperationAction(ISD::FCEIL, VT, Expand);
715 setOperationAction(ISD::FTRUNC, VT, Expand);
716 setOperationAction(ISD::FRINT, VT, Expand);
717 setOperationAction(ISD::FNEARBYINT, VT, Expand);
718 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
719 setOperationAction(ISD::MULHS, VT, Expand);
720 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
721 setOperationAction(ISD::MULHU, VT, Expand);
722 setOperationAction(ISD::SDIVREM, VT, Expand);
723 setOperationAction(ISD::UDIVREM, VT, Expand);
724 setOperationAction(ISD::FPOW, VT, Expand);
725 setOperationAction(ISD::CTPOP, VT, Expand);
726 setOperationAction(ISD::CTTZ, VT, Expand);
727 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
728 setOperationAction(ISD::CTLZ, VT, Expand);
729 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
730 setOperationAction(ISD::SHL, VT, Expand);
731 setOperationAction(ISD::SRA, VT, Expand);
732 setOperationAction(ISD::SRL, VT, Expand);
733 setOperationAction(ISD::ROTL, VT, Expand);
734 setOperationAction(ISD::ROTR, VT, Expand);
735 setOperationAction(ISD::BSWAP, VT, Expand);
736 setOperationAction(ISD::SETCC, VT, Expand);
737 setOperationAction(ISD::FLOG, VT, Expand);
738 setOperationAction(ISD::FLOG2, VT, Expand);
739 setOperationAction(ISD::FLOG10, VT, Expand);
740 setOperationAction(ISD::FEXP, VT, Expand);
741 setOperationAction(ISD::FEXP2, VT, Expand);
742 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
743 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
744 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
745 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
746 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
747 setOperationAction(ISD::TRUNCATE, VT, Expand);
748 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
749 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
750 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
751 setOperationAction(ISD::VSELECT, VT, Expand);
752 setOperationAction(ISD::SELECT_CC, VT, Expand);
753 for (MVT InnerVT : MVT::vector_valuetypes()) {
754 setTruncStoreAction(InnerVT, VT, Expand);
756 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
757 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
759 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
760 // types, we have to deal with them whether we ask for Expansion or not.
761 // Setting Expand causes its own optimisation problems though, so leave
763 if (VT.getVectorElementType() == MVT::i1)
764 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
766 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
767 // split/scalarized right now.
768 if (VT.getVectorElementType() == MVT::f16)
769 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
773 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
774 // with -msoft-float, disable use of MMX as well.
775 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
776 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
777 // No operations on x86mmx supported, everything uses intrinsics.
780 // MMX-sized vectors (other than x86mmx) are expected to be expanded
781 // into smaller operations.
782 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
783 setOperationAction(ISD::MULHS, MMXTy, Expand);
784 setOperationAction(ISD::AND, MMXTy, Expand);
785 setOperationAction(ISD::OR, MMXTy, Expand);
786 setOperationAction(ISD::XOR, MMXTy, Expand);
787 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
788 setOperationAction(ISD::SELECT, MMXTy, Expand);
789 setOperationAction(ISD::BITCAST, MMXTy, Expand);
791 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
793 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
794 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
796 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
797 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
798 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
799 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
800 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
801 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
802 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
803 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
804 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
805 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
806 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
807 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
808 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
809 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
812 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
813 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
815 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
816 // registers cannot be used even for integer operations.
817 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
818 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
819 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
820 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
822 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
823 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
824 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
825 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
826 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
827 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
828 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
829 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
830 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
831 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
832 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
833 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
834 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
835 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
836 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
837 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
838 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
839 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
840 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
841 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
842 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
843 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
844 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
846 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
847 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
848 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
849 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
851 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
852 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
853 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
854 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
856 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
857 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
858 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
859 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
860 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
862 setOperationAction(ISD::CTPOP, MVT::v16i8, Custom);
863 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
864 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
865 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
867 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
868 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
869 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
870 // ISD::CTTZ v2i64 - scalarization is faster.
871 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
872 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
873 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
874 // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
876 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
877 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
878 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
879 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
880 setOperationAction(ISD::VSELECT, VT, Custom);
881 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
884 // We support custom legalizing of sext and anyext loads for specific
885 // memory vector types which we can load as a scalar (or sequence of
886 // scalars) and extend in-register to a legal 128-bit vector type. For sext
887 // loads these must work with a single scalar load.
888 for (MVT VT : MVT::integer_vector_valuetypes()) {
889 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
890 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
891 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
892 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
893 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
894 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
895 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
896 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
897 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
900 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
901 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
902 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
903 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
904 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
905 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
906 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
907 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
909 if (Subtarget->is64Bit()) {
910 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
911 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
914 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
915 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
916 setOperationAction(ISD::AND, VT, Promote);
917 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
918 setOperationAction(ISD::OR, VT, Promote);
919 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
920 setOperationAction(ISD::XOR, VT, Promote);
921 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
922 setOperationAction(ISD::LOAD, VT, Promote);
923 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
924 setOperationAction(ISD::SELECT, VT, Promote);
925 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
928 // Custom lower v2i64 and v2f64 selects.
929 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
930 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
931 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
932 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
934 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
935 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
937 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
939 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
940 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
941 // As there is no 64-bit GPR available, we need build a special custom
942 // sequence to convert from v2i32 to v2f32.
943 if (!Subtarget->is64Bit())
944 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
946 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
947 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
949 for (MVT VT : MVT::fp_vector_valuetypes())
950 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
952 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
953 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
954 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
957 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
958 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
959 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
960 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
961 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
962 setOperationAction(ISD::FRINT, RoundedTy, Legal);
963 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
966 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
967 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
968 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
969 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
970 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
971 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
972 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
973 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
975 // FIXME: Do we need to handle scalar-to-vector here?
976 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
978 // We directly match byte blends in the backend as they match the VSELECT
980 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
982 // SSE41 brings specific instructions for doing vector sign extend even in
983 // cases where we don't have SRA.
984 for (MVT VT : MVT::integer_vector_valuetypes()) {
985 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
986 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
987 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
990 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
991 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
992 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
993 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
994 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
995 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
996 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
998 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
999 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1000 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1001 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1002 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1003 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1005 // i8 and i16 vectors are custom because the source register and source
1006 // source memory operand types are not the same width. f32 vectors are
1007 // custom since the immediate controlling the insert encodes additional
1009 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1010 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1011 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1012 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1014 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1015 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1016 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1017 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1019 // FIXME: these should be Legal, but that's only for the case where
1020 // the index is constant. For now custom expand to deal with that.
1021 if (Subtarget->is64Bit()) {
1022 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1023 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1027 if (Subtarget->hasSSE2()) {
1028 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1029 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1030 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1032 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1033 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1035 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1036 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1038 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1039 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1041 // In the customized shift lowering, the legal cases in AVX2 will be
1043 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1044 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1046 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1047 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1049 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1050 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1053 if (Subtarget->hasXOP()) {
1054 setOperationAction(ISD::ROTL, MVT::v16i8, Custom);
1055 setOperationAction(ISD::ROTL, MVT::v8i16, Custom);
1056 setOperationAction(ISD::ROTL, MVT::v4i32, Custom);
1057 setOperationAction(ISD::ROTL, MVT::v2i64, Custom);
1058 setOperationAction(ISD::ROTL, MVT::v32i8, Custom);
1059 setOperationAction(ISD::ROTL, MVT::v16i16, Custom);
1060 setOperationAction(ISD::ROTL, MVT::v8i32, Custom);
1061 setOperationAction(ISD::ROTL, MVT::v4i64, Custom);
1064 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1065 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1066 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1067 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1068 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1069 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1070 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1072 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1073 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1074 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1076 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1077 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1078 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1079 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1080 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1081 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1082 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1083 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1084 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1085 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1086 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1087 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1089 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1090 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1091 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1092 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1093 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1094 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1095 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1096 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1097 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1098 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1099 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1100 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1102 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1103 // even though v8i16 is a legal type.
1104 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1105 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1106 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1108 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1109 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1110 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1112 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1113 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1115 for (MVT VT : MVT::fp_vector_valuetypes())
1116 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1118 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1119 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1121 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1122 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1124 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1125 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1127 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1128 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1129 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1130 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1132 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1133 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1134 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1136 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1137 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1138 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1139 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1140 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1141 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1142 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1143 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1144 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1145 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1146 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1147 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1149 setOperationAction(ISD::CTPOP, MVT::v32i8, Custom);
1150 setOperationAction(ISD::CTPOP, MVT::v16i16, Custom);
1151 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1152 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1154 setOperationAction(ISD::CTTZ, MVT::v32i8, Custom);
1155 setOperationAction(ISD::CTTZ, MVT::v16i16, Custom);
1156 setOperationAction(ISD::CTTZ, MVT::v8i32, Custom);
1157 setOperationAction(ISD::CTTZ, MVT::v4i64, Custom);
1158 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v32i8, Custom);
1159 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i16, Custom);
1160 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i32, Custom);
1161 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i64, Custom);
1163 if (Subtarget->hasAnyFMA()) {
1164 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1165 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1166 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1167 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1168 setOperationAction(ISD::FMA, MVT::f32, Legal);
1169 setOperationAction(ISD::FMA, MVT::f64, Legal);
1172 if (Subtarget->hasInt256()) {
1173 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1174 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1175 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1176 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1178 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1179 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1180 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1181 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1183 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1184 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1185 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1186 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1188 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1189 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1190 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1191 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1193 setOperationAction(ISD::SMAX, MVT::v32i8, Legal);
1194 setOperationAction(ISD::SMAX, MVT::v16i16, Legal);
1195 setOperationAction(ISD::SMAX, MVT::v8i32, Legal);
1196 setOperationAction(ISD::UMAX, MVT::v32i8, Legal);
1197 setOperationAction(ISD::UMAX, MVT::v16i16, Legal);
1198 setOperationAction(ISD::UMAX, MVT::v8i32, Legal);
1199 setOperationAction(ISD::SMIN, MVT::v32i8, Legal);
1200 setOperationAction(ISD::SMIN, MVT::v16i16, Legal);
1201 setOperationAction(ISD::SMIN, MVT::v8i32, Legal);
1202 setOperationAction(ISD::UMIN, MVT::v32i8, Legal);
1203 setOperationAction(ISD::UMIN, MVT::v16i16, Legal);
1204 setOperationAction(ISD::UMIN, MVT::v8i32, Legal);
1206 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1207 // when we have a 256bit-wide blend with immediate.
1208 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1210 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1211 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1212 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1213 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1214 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1215 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1216 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1218 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1219 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1220 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1221 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1222 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1223 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1225 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1226 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1227 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1228 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1230 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1231 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1232 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1233 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1235 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1236 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1237 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1238 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1240 setOperationAction(ISD::SMAX, MVT::v32i8, Custom);
1241 setOperationAction(ISD::SMAX, MVT::v16i16, Custom);
1242 setOperationAction(ISD::SMAX, MVT::v8i32, Custom);
1243 setOperationAction(ISD::UMAX, MVT::v32i8, Custom);
1244 setOperationAction(ISD::UMAX, MVT::v16i16, Custom);
1245 setOperationAction(ISD::UMAX, MVT::v8i32, Custom);
1246 setOperationAction(ISD::SMIN, MVT::v32i8, Custom);
1247 setOperationAction(ISD::SMIN, MVT::v16i16, Custom);
1248 setOperationAction(ISD::SMIN, MVT::v8i32, Custom);
1249 setOperationAction(ISD::UMIN, MVT::v32i8, Custom);
1250 setOperationAction(ISD::UMIN, MVT::v16i16, Custom);
1251 setOperationAction(ISD::UMIN, MVT::v8i32, Custom);
1254 // In the customized shift lowering, the legal cases in AVX2 will be
1256 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1257 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1259 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1260 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1262 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1263 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1265 // Custom lower several nodes for 256-bit types.
1266 for (MVT VT : MVT::vector_valuetypes()) {
1267 if (VT.getScalarSizeInBits() >= 32) {
1268 setOperationAction(ISD::MLOAD, VT, Legal);
1269 setOperationAction(ISD::MSTORE, VT, Legal);
1271 // Extract subvector is special because the value type
1272 // (result) is 128-bit but the source is 256-bit wide.
1273 if (VT.is128BitVector()) {
1274 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1276 // Do not attempt to custom lower other non-256-bit vectors
1277 if (!VT.is256BitVector())
1280 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1281 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1282 setOperationAction(ISD::VSELECT, VT, Custom);
1283 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1284 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1285 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1286 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1287 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1290 if (Subtarget->hasInt256())
1291 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1293 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1294 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1295 setOperationAction(ISD::AND, VT, Promote);
1296 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1297 setOperationAction(ISD::OR, VT, Promote);
1298 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1299 setOperationAction(ISD::XOR, VT, Promote);
1300 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1301 setOperationAction(ISD::LOAD, VT, Promote);
1302 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1303 setOperationAction(ISD::SELECT, VT, Promote);
1304 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1308 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1309 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1310 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1311 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1312 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1314 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1315 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1316 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1318 for (MVT VT : MVT::fp_vector_valuetypes())
1319 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1321 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1322 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1323 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1324 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1325 setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1326 setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1327 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1328 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1329 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1330 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1331 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1332 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1334 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1335 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1336 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
1337 setOperationAction(ISD::XOR, MVT::i1, Legal);
1338 setOperationAction(ISD::OR, MVT::i1, Legal);
1339 setOperationAction(ISD::AND, MVT::i1, Legal);
1340 setOperationAction(ISD::SUB, MVT::i1, Custom);
1341 setOperationAction(ISD::ADD, MVT::i1, Custom);
1342 setOperationAction(ISD::MUL, MVT::i1, Custom);
1343 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1344 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1345 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1346 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1347 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1349 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1350 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1351 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1352 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1353 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1354 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1355 setOperationAction(ISD::FABS, MVT::v16f32, Custom);
1357 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1358 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1359 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1360 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1361 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1362 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1363 setOperationAction(ISD::FABS, MVT::v8f64, Custom);
1364 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1365 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1367 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1368 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1369 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1370 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1371 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1372 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1373 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1374 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1375 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1376 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1377 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1378 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1379 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1380 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1381 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1382 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1384 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1385 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1386 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1387 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1388 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1389 if (Subtarget->hasVLX()){
1390 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1391 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1392 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1393 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1394 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1396 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1397 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1398 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1399 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1400 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1402 setOperationAction(ISD::MLOAD, MVT::v8i32, Custom);
1403 setOperationAction(ISD::MLOAD, MVT::v8f32, Custom);
1404 setOperationAction(ISD::MSTORE, MVT::v8i32, Custom);
1405 setOperationAction(ISD::MSTORE, MVT::v8f32, Custom);
1407 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1408 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1409 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1410 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i1, Custom);
1411 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i1, Custom);
1412 if (Subtarget->hasDQI()) {
1413 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1414 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1416 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1417 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1418 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1419 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1420 if (Subtarget->hasVLX()) {
1421 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1422 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1423 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1424 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1425 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1426 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1427 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1428 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1431 if (Subtarget->hasVLX()) {
1432 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1433 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1434 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1435 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1436 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1437 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1438 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1439 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1441 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1442 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1443 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1444 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1445 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1446 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1447 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1448 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1449 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1450 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1451 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1452 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1453 if (Subtarget->hasDQI()) {
1454 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1455 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1457 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1458 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1459 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1460 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1461 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1462 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1463 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1464 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1465 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1466 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1468 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1469 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1470 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1471 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1472 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Custom);
1474 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1475 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1477 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1479 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1480 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1481 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v16i1, Custom);
1482 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1483 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1484 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1485 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1486 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1487 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1488 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1489 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1490 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1492 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1493 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1494 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1495 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1496 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1497 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1498 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1499 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1501 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1502 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1504 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1505 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1507 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1509 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1510 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1512 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1513 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1515 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1516 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1518 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1519 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1520 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1521 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1522 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1523 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1525 if (Subtarget->hasCDI()) {
1526 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1527 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1528 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i64, Legal);
1529 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i32, Legal);
1531 setOperationAction(ISD::CTLZ, MVT::v8i16, Custom);
1532 setOperationAction(ISD::CTLZ, MVT::v16i8, Custom);
1533 setOperationAction(ISD::CTLZ, MVT::v16i16, Custom);
1534 setOperationAction(ISD::CTLZ, MVT::v32i8, Custom);
1535 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i16, Custom);
1536 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i8, Custom);
1537 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i16, Custom);
1538 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i8, Custom);
1540 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i64, Custom);
1541 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i32, Custom);
1543 if (Subtarget->hasVLX()) {
1544 setOperationAction(ISD::CTLZ, MVT::v4i64, Legal);
1545 setOperationAction(ISD::CTLZ, MVT::v8i32, Legal);
1546 setOperationAction(ISD::CTLZ, MVT::v2i64, Legal);
1547 setOperationAction(ISD::CTLZ, MVT::v4i32, Legal);
1548 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i64, Legal);
1549 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i32, Legal);
1550 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v2i64, Legal);
1551 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i32, Legal);
1553 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i64, Custom);
1554 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i32, Custom);
1555 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
1556 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
1558 setOperationAction(ISD::CTLZ, MVT::v4i64, Custom);
1559 setOperationAction(ISD::CTLZ, MVT::v8i32, Custom);
1560 setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
1561 setOperationAction(ISD::CTLZ, MVT::v4i32, Custom);
1562 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i64, Custom);
1563 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i32, Custom);
1564 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v2i64, Custom);
1565 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i32, Custom);
1567 } // Subtarget->hasCDI()
1569 if (Subtarget->hasDQI()) {
1570 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1571 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1572 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1574 // Custom lower several nodes.
1575 for (MVT VT : MVT::vector_valuetypes()) {
1576 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1578 setOperationAction(ISD::AND, VT, Legal);
1579 setOperationAction(ISD::OR, VT, Legal);
1580 setOperationAction(ISD::XOR, VT, Legal);
1582 if ((VT.is128BitVector() || VT.is256BitVector()) && EltSize >= 32) {
1583 setOperationAction(ISD::MGATHER, VT, Custom);
1584 setOperationAction(ISD::MSCATTER, VT, Custom);
1586 // Extract subvector is special because the value type
1587 // (result) is 256/128-bit but the source is 512-bit wide.
1588 if (VT.is128BitVector() || VT.is256BitVector()) {
1589 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1591 if (VT.getVectorElementType() == MVT::i1)
1592 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1594 // Do not attempt to custom lower other non-512-bit vectors
1595 if (!VT.is512BitVector())
1598 if (EltSize >= 32) {
1599 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1600 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1601 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1602 setOperationAction(ISD::VSELECT, VT, Legal);
1603 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1604 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1605 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1606 setOperationAction(ISD::MLOAD, VT, Legal);
1607 setOperationAction(ISD::MSTORE, VT, Legal);
1608 setOperationAction(ISD::MGATHER, VT, Legal);
1609 setOperationAction(ISD::MSCATTER, VT, Custom);
1612 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1613 setOperationAction(ISD::SELECT, VT, Promote);
1614 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1618 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1619 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1620 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1622 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1623 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1625 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1626 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1627 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1628 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1629 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1630 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1631 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1632 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1633 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1634 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1635 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1636 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1637 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1638 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i16, Custom);
1639 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i8, Custom);
1640 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1641 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1642 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i16, Custom);
1643 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i8, Custom);
1644 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1645 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1646 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1647 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1648 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1649 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1650 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1651 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1652 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i16, Custom);
1653 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i8, Custom);
1654 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1655 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1656 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1657 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1658 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i16, Custom);
1659 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i8, Custom);
1660 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1661 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1662 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1663 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1664 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1665 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i1, Custom);
1666 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i1, Custom);
1668 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1669 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1670 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1671 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1672 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1673 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1674 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1675 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1677 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1678 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1679 if (Subtarget->hasVLX())
1680 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1682 if (Subtarget->hasCDI()) {
1683 setOperationAction(ISD::CTLZ, MVT::v32i16, Custom);
1684 setOperationAction(ISD::CTLZ, MVT::v64i8, Custom);
1685 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Custom);
1686 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8, Custom);
1689 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1690 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1691 setOperationAction(ISD::VSELECT, VT, Legal);
1692 setOperationAction(ISD::SRL, VT, Custom);
1693 setOperationAction(ISD::SHL, VT, Custom);
1694 setOperationAction(ISD::SRA, VT, Custom);
1696 setOperationAction(ISD::AND, VT, Promote);
1697 AddPromotedToType (ISD::AND, VT, MVT::v8i64);
1698 setOperationAction(ISD::OR, VT, Promote);
1699 AddPromotedToType (ISD::OR, VT, MVT::v8i64);
1700 setOperationAction(ISD::XOR, VT, Promote);
1701 AddPromotedToType (ISD::XOR, VT, MVT::v8i64);
1705 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1706 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1707 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1709 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1710 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1711 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1712 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1713 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1714 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1715 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1716 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1717 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1718 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1719 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i1, Custom);
1720 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i1, Custom);
1722 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1723 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1724 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1725 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1726 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1727 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1728 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1729 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1731 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1732 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1733 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1734 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1735 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1736 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1737 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1738 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1741 // We want to custom lower some of our intrinsics.
1742 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1743 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1744 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1745 if (!Subtarget->is64Bit()) {
1746 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1747 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1750 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1751 // handle type legalization for these operations here.
1753 // FIXME: We really should do custom legalization for addition and
1754 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1755 // than generic legalization for 64-bit multiplication-with-overflow, though.
1756 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1757 if (VT == MVT::i64 && !Subtarget->is64Bit())
1759 // Add/Sub/Mul with overflow operations are custom lowered.
1760 setOperationAction(ISD::SADDO, VT, Custom);
1761 setOperationAction(ISD::UADDO, VT, Custom);
1762 setOperationAction(ISD::SSUBO, VT, Custom);
1763 setOperationAction(ISD::USUBO, VT, Custom);
1764 setOperationAction(ISD::SMULO, VT, Custom);
1765 setOperationAction(ISD::UMULO, VT, Custom);
1768 if (!Subtarget->is64Bit()) {
1769 // These libcalls are not available in 32-bit.
1770 setLibcallName(RTLIB::SHL_I128, nullptr);
1771 setLibcallName(RTLIB::SRL_I128, nullptr);
1772 setLibcallName(RTLIB::SRA_I128, nullptr);
1775 // Combine sin / cos into one node or libcall if possible.
1776 if (Subtarget->hasSinCos()) {
1777 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1778 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1779 if (Subtarget->isTargetDarwin()) {
1780 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1781 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1782 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1783 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1787 if (Subtarget->isTargetWin64()) {
1788 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1789 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1790 setOperationAction(ISD::SREM, MVT::i128, Custom);
1791 setOperationAction(ISD::UREM, MVT::i128, Custom);
1792 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1793 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1796 // We have target-specific dag combine patterns for the following nodes:
1797 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1798 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1799 setTargetDAGCombine(ISD::BITCAST);
1800 setTargetDAGCombine(ISD::VSELECT);
1801 setTargetDAGCombine(ISD::SELECT);
1802 setTargetDAGCombine(ISD::SHL);
1803 setTargetDAGCombine(ISD::SRA);
1804 setTargetDAGCombine(ISD::SRL);
1805 setTargetDAGCombine(ISD::OR);
1806 setTargetDAGCombine(ISD::AND);
1807 setTargetDAGCombine(ISD::ADD);
1808 setTargetDAGCombine(ISD::FADD);
1809 setTargetDAGCombine(ISD::FSUB);
1810 setTargetDAGCombine(ISD::FNEG);
1811 setTargetDAGCombine(ISD::FMA);
1812 setTargetDAGCombine(ISD::FMAXNUM);
1813 setTargetDAGCombine(ISD::SUB);
1814 setTargetDAGCombine(ISD::LOAD);
1815 setTargetDAGCombine(ISD::MLOAD);
1816 setTargetDAGCombine(ISD::STORE);
1817 setTargetDAGCombine(ISD::MSTORE);
1818 setTargetDAGCombine(ISD::TRUNCATE);
1819 setTargetDAGCombine(ISD::ZERO_EXTEND);
1820 setTargetDAGCombine(ISD::ANY_EXTEND);
1821 setTargetDAGCombine(ISD::SIGN_EXTEND);
1822 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1823 setTargetDAGCombine(ISD::SINT_TO_FP);
1824 setTargetDAGCombine(ISD::UINT_TO_FP);
1825 setTargetDAGCombine(ISD::SETCC);
1826 setTargetDAGCombine(ISD::BUILD_VECTOR);
1827 setTargetDAGCombine(ISD::MUL);
1828 setTargetDAGCombine(ISD::XOR);
1829 setTargetDAGCombine(ISD::MSCATTER);
1830 setTargetDAGCombine(ISD::MGATHER);
1832 computeRegisterProperties(Subtarget->getRegisterInfo());
1834 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1835 MaxStoresPerMemsetOptSize = 8;
1836 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1837 MaxStoresPerMemcpyOptSize = 4;
1838 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1839 MaxStoresPerMemmoveOptSize = 4;
1840 setPrefLoopAlignment(4); // 2^4 bytes.
1842 // A predictable cmov does not hurt on an in-order CPU.
1843 // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1844 PredictableSelectIsExpensive = !Subtarget->isAtom();
1845 EnableExtLdPromotion = true;
1846 setPrefFunctionAlignment(4); // 2^4 bytes.
1848 verifyIntrinsicTables();
1851 // This has so far only been implemented for 64-bit MachO.
1852 bool X86TargetLowering::useLoadStackGuardNode() const {
1853 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1856 TargetLoweringBase::LegalizeTypeAction
1857 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1858 if (ExperimentalVectorWideningLegalization &&
1859 VT.getVectorNumElements() != 1 &&
1860 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1861 return TypeWidenVector;
1863 return TargetLoweringBase::getPreferredVectorAction(VT);
1866 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1869 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1871 if (VT.isSimple()) {
1872 MVT VVT = VT.getSimpleVT();
1873 const unsigned NumElts = VVT.getVectorNumElements();
1874 const MVT EltVT = VVT.getVectorElementType();
1875 if (VVT.is512BitVector()) {
1876 if (Subtarget->hasAVX512())
1877 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1878 EltVT == MVT::f32 || EltVT == MVT::f64)
1880 case 8: return MVT::v8i1;
1881 case 16: return MVT::v16i1;
1883 if (Subtarget->hasBWI())
1884 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1886 case 32: return MVT::v32i1;
1887 case 64: return MVT::v64i1;
1891 if (VVT.is256BitVector() || VVT.is128BitVector()) {
1892 if (Subtarget->hasVLX())
1893 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1894 EltVT == MVT::f32 || EltVT == MVT::f64)
1896 case 2: return MVT::v2i1;
1897 case 4: return MVT::v4i1;
1898 case 8: return MVT::v8i1;
1900 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1901 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1903 case 8: return MVT::v8i1;
1904 case 16: return MVT::v16i1;
1905 case 32: return MVT::v32i1;
1910 return VT.changeVectorElementTypeToInteger();
1913 /// Helper for getByValTypeAlignment to determine
1914 /// the desired ByVal argument alignment.
1915 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1918 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1919 if (VTy->getBitWidth() == 128)
1921 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1922 unsigned EltAlign = 0;
1923 getMaxByValAlign(ATy->getElementType(), EltAlign);
1924 if (EltAlign > MaxAlign)
1925 MaxAlign = EltAlign;
1926 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1927 for (auto *EltTy : STy->elements()) {
1928 unsigned EltAlign = 0;
1929 getMaxByValAlign(EltTy, EltAlign);
1930 if (EltAlign > MaxAlign)
1931 MaxAlign = EltAlign;
1938 /// Return the desired alignment for ByVal aggregate
1939 /// function arguments in the caller parameter area. For X86, aggregates
1940 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1941 /// are at 4-byte boundaries.
1942 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1943 const DataLayout &DL) const {
1944 if (Subtarget->is64Bit()) {
1945 // Max of 8 and alignment of type.
1946 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1953 if (Subtarget->hasSSE1())
1954 getMaxByValAlign(Ty, Align);
1958 /// Returns the target specific optimal type for load
1959 /// and store operations as a result of memset, memcpy, and memmove
1960 /// lowering. If DstAlign is zero that means it's safe to destination
1961 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1962 /// means there isn't a need to check it against alignment requirement,
1963 /// probably because the source does not need to be loaded. If 'IsMemset' is
1964 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1965 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1966 /// source is constant so it does not need to be loaded.
1967 /// It returns EVT::Other if the type should be determined using generic
1968 /// target-independent logic.
1970 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1971 unsigned DstAlign, unsigned SrcAlign,
1972 bool IsMemset, bool ZeroMemset,
1974 MachineFunction &MF) const {
1975 const Function *F = MF.getFunction();
1976 if ((!IsMemset || ZeroMemset) &&
1977 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1979 (!Subtarget->isUnalignedMem16Slow() ||
1980 ((DstAlign == 0 || DstAlign >= 16) &&
1981 (SrcAlign == 0 || SrcAlign >= 16)))) {
1983 // FIXME: Check if unaligned 32-byte accesses are slow.
1984 if (Subtarget->hasInt256())
1986 if (Subtarget->hasFp256())
1989 if (Subtarget->hasSSE2())
1991 if (Subtarget->hasSSE1())
1993 } else if (!MemcpyStrSrc && Size >= 8 &&
1994 !Subtarget->is64Bit() &&
1995 Subtarget->hasSSE2()) {
1996 // Do not use f64 to lower memcpy if source is string constant. It's
1997 // better to use i32 to avoid the loads.
2001 // This is a compromise. If we reach here, unaligned accesses may be slow on
2002 // this target. However, creating smaller, aligned accesses could be even
2003 // slower and would certainly be a lot more code.
2004 if (Subtarget->is64Bit() && Size >= 8)
2009 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2011 return X86ScalarSSEf32;
2012 else if (VT == MVT::f64)
2013 return X86ScalarSSEf64;
2018 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
2023 switch (VT.getSizeInBits()) {
2025 // 8-byte and under are always assumed to be fast.
2029 *Fast = !Subtarget->isUnalignedMem16Slow();
2032 *Fast = !Subtarget->isUnalignedMem32Slow();
2034 // TODO: What about AVX-512 (512-bit) accesses?
2037 // Misaligned accesses of any size are always allowed.
2041 /// Return the entry encoding for a jump table in the
2042 /// current function. The returned value is a member of the
2043 /// MachineJumpTableInfo::JTEntryKind enum.
2044 unsigned X86TargetLowering::getJumpTableEncoding() const {
2045 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2047 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2048 Subtarget->isPICStyleGOT())
2049 return MachineJumpTableInfo::EK_Custom32;
2051 // Otherwise, use the normal jump table encoding heuristics.
2052 return TargetLowering::getJumpTableEncoding();
2055 bool X86TargetLowering::useSoftFloat() const {
2056 return Subtarget->useSoftFloat();
2060 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2061 const MachineBasicBlock *MBB,
2062 unsigned uid,MCContext &Ctx) const{
2063 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2064 Subtarget->isPICStyleGOT());
2065 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2067 return MCSymbolRefExpr::create(MBB->getSymbol(),
2068 MCSymbolRefExpr::VK_GOTOFF, Ctx);
2071 /// Returns relocation base for the given PIC jumptable.
2072 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2073 SelectionDAG &DAG) const {
2074 if (!Subtarget->is64Bit())
2075 // This doesn't have SDLoc associated with it, but is not really the
2076 // same as a Register.
2077 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2078 getPointerTy(DAG.getDataLayout()));
2082 /// This returns the relocation base for the given PIC jumptable,
2083 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2084 const MCExpr *X86TargetLowering::
2085 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2086 MCContext &Ctx) const {
2087 // X86-64 uses RIP relative addressing based on the jump table label.
2088 if (Subtarget->isPICStyleRIPRel())
2089 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2091 // Otherwise, the reference is relative to the PIC base.
2092 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2095 std::pair<const TargetRegisterClass *, uint8_t>
2096 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2098 const TargetRegisterClass *RRC = nullptr;
2100 switch (VT.SimpleTy) {
2102 return TargetLowering::findRepresentativeClass(TRI, VT);
2103 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2104 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2107 RRC = &X86::VR64RegClass;
2109 case MVT::f32: case MVT::f64:
2110 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2111 case MVT::v4f32: case MVT::v2f64:
2112 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2114 RRC = &X86::VR128RegClass;
2117 return std::make_pair(RRC, Cost);
2120 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2121 unsigned &Offset) const {
2122 if (!Subtarget->isTargetLinux())
2125 if (Subtarget->is64Bit()) {
2126 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2128 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2140 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2141 if (!Subtarget->isTargetAndroid())
2142 return TargetLowering::getSafeStackPointerLocation(IRB);
2144 // Android provides a fixed TLS slot for the SafeStack pointer. See the
2145 // definition of TLS_SLOT_SAFESTACK in
2146 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2147 unsigned AddressSpace, Offset;
2148 if (Subtarget->is64Bit()) {
2149 // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2151 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2161 return ConstantExpr::getIntToPtr(
2162 ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2163 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2166 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2167 unsigned DestAS) const {
2168 assert(SrcAS != DestAS && "Expected different address spaces!");
2170 return SrcAS < 256 && DestAS < 256;
2173 //===----------------------------------------------------------------------===//
2174 // Return Value Calling Convention Implementation
2175 //===----------------------------------------------------------------------===//
2177 #include "X86GenCallingConv.inc"
2179 bool X86TargetLowering::CanLowerReturn(
2180 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2181 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2182 SmallVector<CCValAssign, 16> RVLocs;
2183 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2184 return CCInfo.CheckReturn(Outs, RetCC_X86);
2187 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2188 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2193 X86TargetLowering::LowerReturn(SDValue Chain,
2194 CallingConv::ID CallConv, bool isVarArg,
2195 const SmallVectorImpl<ISD::OutputArg> &Outs,
2196 const SmallVectorImpl<SDValue> &OutVals,
2197 SDLoc dl, SelectionDAG &DAG) const {
2198 MachineFunction &MF = DAG.getMachineFunction();
2199 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2201 if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2202 report_fatal_error("X86 interrupts may not return any value");
2204 SmallVector<CCValAssign, 16> RVLocs;
2205 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2206 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2209 SmallVector<SDValue, 6> RetOps;
2210 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2211 // Operand #1 = Bytes To Pop
2212 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2215 // Copy the result values into the output registers.
2216 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2217 CCValAssign &VA = RVLocs[i];
2218 assert(VA.isRegLoc() && "Can only return in registers!");
2219 SDValue ValToCopy = OutVals[i];
2220 EVT ValVT = ValToCopy.getValueType();
2222 // Promote values to the appropriate types.
2223 if (VA.getLocInfo() == CCValAssign::SExt)
2224 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2225 else if (VA.getLocInfo() == CCValAssign::ZExt)
2226 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2227 else if (VA.getLocInfo() == CCValAssign::AExt) {
2228 if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2229 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2231 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2233 else if (VA.getLocInfo() == CCValAssign::BCvt)
2234 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2236 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2237 "Unexpected FP-extend for return value.");
2239 // If this is x86-64, and we disabled SSE, we can't return FP values,
2240 // or SSE or MMX vectors.
2241 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2242 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2243 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2244 report_fatal_error("SSE register return with SSE disabled");
2246 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2247 // llvm-gcc has never done it right and no one has noticed, so this
2248 // should be OK for now.
2249 if (ValVT == MVT::f64 &&
2250 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2251 report_fatal_error("SSE2 register return with SSE2 disabled");
2253 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2254 // the RET instruction and handled by the FP Stackifier.
2255 if (VA.getLocReg() == X86::FP0 ||
2256 VA.getLocReg() == X86::FP1) {
2257 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2258 // change the value to the FP stack register class.
2259 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2260 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2261 RetOps.push_back(ValToCopy);
2262 // Don't emit a copytoreg.
2266 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2267 // which is returned in RAX / RDX.
2268 if (Subtarget->is64Bit()) {
2269 if (ValVT == MVT::x86mmx) {
2270 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2271 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2272 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2274 // If we don't have SSE2 available, convert to v4f32 so the generated
2275 // register is legal.
2276 if (!Subtarget->hasSSE2())
2277 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2282 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2283 Flag = Chain.getValue(1);
2284 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2287 // All x86 ABIs require that for returning structs by value we copy
2288 // the sret argument into %rax/%eax (depending on ABI) for the return.
2289 // We saved the argument into a virtual register in the entry block,
2290 // so now we copy the value out and into %rax/%eax.
2292 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2293 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2294 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2295 // either case FuncInfo->setSRetReturnReg() will have been called.
2296 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2297 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2298 getPointerTy(MF.getDataLayout()));
2301 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2302 X86::RAX : X86::EAX;
2303 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2304 Flag = Chain.getValue(1);
2306 // RAX/EAX now acts like a return value.
2308 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2311 RetOps[0] = Chain; // Update chain.
2313 // Add the flag if we have it.
2315 RetOps.push_back(Flag);
2317 X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2318 if (CallConv == CallingConv::X86_INTR)
2319 opcode = X86ISD::IRET;
2320 return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2323 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2324 if (N->getNumValues() != 1)
2326 if (!N->hasNUsesOfValue(1, 0))
2329 SDValue TCChain = Chain;
2330 SDNode *Copy = *N->use_begin();
2331 if (Copy->getOpcode() == ISD::CopyToReg) {
2332 // If the copy has a glue operand, we conservatively assume it isn't safe to
2333 // perform a tail call.
2334 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2336 TCChain = Copy->getOperand(0);
2337 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2340 bool HasRet = false;
2341 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2343 if (UI->getOpcode() != X86ISD::RET_FLAG)
2345 // If we are returning more than one value, we can definitely
2346 // not make a tail call see PR19530
2347 if (UI->getNumOperands() > 4)
2349 if (UI->getNumOperands() == 4 &&
2350 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2363 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2364 ISD::NodeType ExtendKind) const {
2366 // TODO: Is this also valid on 32-bit?
2367 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2368 ReturnMVT = MVT::i8;
2370 ReturnMVT = MVT::i32;
2372 EVT MinVT = getRegisterType(Context, ReturnMVT);
2373 return VT.bitsLT(MinVT) ? MinVT : VT;
2376 /// Lower the result values of a call into the
2377 /// appropriate copies out of appropriate physical registers.
2380 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2381 CallingConv::ID CallConv, bool isVarArg,
2382 const SmallVectorImpl<ISD::InputArg> &Ins,
2383 SDLoc dl, SelectionDAG &DAG,
2384 SmallVectorImpl<SDValue> &InVals) const {
2386 // Assign locations to each value returned by this call.
2387 SmallVector<CCValAssign, 16> RVLocs;
2388 bool Is64Bit = Subtarget->is64Bit();
2389 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2391 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2393 // Copy all of the result registers out of their specified physreg.
2394 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2395 CCValAssign &VA = RVLocs[i];
2396 EVT CopyVT = VA.getLocVT();
2398 // If this is x86-64, and we disabled SSE, we can't return FP values
2399 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2400 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2401 report_fatal_error("SSE register return with SSE disabled");
2404 // If we prefer to use the value in xmm registers, copy it out as f80 and
2405 // use a truncate to move it from fp stack reg to xmm reg.
2406 bool RoundAfterCopy = false;
2407 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2408 isScalarFPTypeInSSEReg(VA.getValVT())) {
2410 RoundAfterCopy = (CopyVT != VA.getLocVT());
2413 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2414 CopyVT, InFlag).getValue(1);
2415 SDValue Val = Chain.getValue(0);
2418 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2419 // This truncation won't change the value.
2420 DAG.getIntPtrConstant(1, dl));
2422 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2423 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2425 InFlag = Chain.getValue(2);
2426 InVals.push_back(Val);
2432 //===----------------------------------------------------------------------===//
2433 // C & StdCall & Fast Calling Convention implementation
2434 //===----------------------------------------------------------------------===//
2435 // StdCall calling convention seems to be standard for many Windows' API
2436 // routines and around. It differs from C calling convention just a little:
2437 // callee should clean up the stack, not caller. Symbols should be also
2438 // decorated in some fancy way :) It doesn't support any vector arguments.
2439 // For info on fast calling convention see Fast Calling Convention (tail call)
2440 // implementation LowerX86_32FastCCCallTo.
2442 /// CallIsStructReturn - Determines whether a call uses struct return
2444 enum StructReturnType {
2449 static StructReturnType
2450 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2452 return NotStructReturn;
2454 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2455 if (!Flags.isSRet())
2456 return NotStructReturn;
2457 if (Flags.isInReg())
2458 return RegStructReturn;
2459 return StackStructReturn;
2462 /// Determines whether a function uses struct return semantics.
2463 static StructReturnType
2464 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2466 return NotStructReturn;
2468 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2469 if (!Flags.isSRet())
2470 return NotStructReturn;
2471 if (Flags.isInReg())
2472 return RegStructReturn;
2473 return StackStructReturn;
2476 /// Make a copy of an aggregate at address specified by "Src" to address
2477 /// "Dst" with size and alignment information specified by the specific
2478 /// parameter attribute. The copy will be passed as a byval function parameter.
2480 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2481 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2483 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2485 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2486 /*isVolatile*/false, /*AlwaysInline=*/true,
2487 /*isTailCall*/false,
2488 MachinePointerInfo(), MachinePointerInfo());
2491 /// Return true if the calling convention is one that we can guarantee TCO for.
2492 static bool canGuaranteeTCO(CallingConv::ID CC) {
2493 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2494 CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2497 /// Return true if we might ever do TCO for calls with this calling convention.
2498 static bool mayTailCallThisCC(CallingConv::ID CC) {
2500 // C calling conventions:
2501 case CallingConv::C:
2502 case CallingConv::X86_64_Win64:
2503 case CallingConv::X86_64_SysV:
2504 // Callee pop conventions:
2505 case CallingConv::X86_ThisCall:
2506 case CallingConv::X86_StdCall:
2507 case CallingConv::X86_VectorCall:
2508 case CallingConv::X86_FastCall:
2511 return canGuaranteeTCO(CC);
2515 /// Return true if the function is being made into a tailcall target by
2516 /// changing its ABI.
2517 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2518 return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2521 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2523 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2524 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2528 CallingConv::ID CalleeCC = CS.getCallingConv();
2529 if (!mayTailCallThisCC(CalleeCC))
2536 X86TargetLowering::LowerMemArgument(SDValue Chain,
2537 CallingConv::ID CallConv,
2538 const SmallVectorImpl<ISD::InputArg> &Ins,
2539 SDLoc dl, SelectionDAG &DAG,
2540 const CCValAssign &VA,
2541 MachineFrameInfo *MFI,
2543 // Create the nodes corresponding to a load from this parameter slot.
2544 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2545 bool AlwaysUseMutable = shouldGuaranteeTCO(
2546 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2547 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2550 // If value is passed by pointer we have address passed instead of the value
2552 bool ExtendedInMem = VA.isExtInLoc() &&
2553 VA.getValVT().getScalarType() == MVT::i1;
2555 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2556 ValVT = VA.getLocVT();
2558 ValVT = VA.getValVT();
2560 // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2561 // taken by a return address.
2563 if (CallConv == CallingConv::X86_INTR) {
2564 const X86Subtarget& Subtarget =
2565 static_cast<const X86Subtarget&>(DAG.getSubtarget());
2566 // X86 interrupts may take one or two arguments.
2567 // On the stack there will be no return address as in regular call.
2568 // Offset of last argument need to be set to -4/-8 bytes.
2569 // Where offset of the first argument out of two, should be set to 0 bytes.
2570 Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2573 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2574 // changed with more analysis.
2575 // In case of tail call optimization mark all arguments mutable. Since they
2576 // could be overwritten by lowering of arguments in case of a tail call.
2577 if (Flags.isByVal()) {
2578 unsigned Bytes = Flags.getByValSize();
2579 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2580 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2581 // Adjust SP offset of interrupt parameter.
2582 if (CallConv == CallingConv::X86_INTR) {
2583 MFI->setObjectOffset(FI, Offset);
2585 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2587 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2588 VA.getLocMemOffset(), isImmutable);
2589 // Adjust SP offset of interrupt parameter.
2590 if (CallConv == CallingConv::X86_INTR) {
2591 MFI->setObjectOffset(FI, Offset);
2594 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2595 SDValue Val = DAG.getLoad(
2596 ValVT, dl, Chain, FIN,
2597 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2599 return ExtendedInMem ?
2600 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2604 // FIXME: Get this from tablegen.
2605 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2606 const X86Subtarget *Subtarget) {
2607 assert(Subtarget->is64Bit());
2609 if (Subtarget->isCallingConvWin64(CallConv)) {
2610 static const MCPhysReg GPR64ArgRegsWin64[] = {
2611 X86::RCX, X86::RDX, X86::R8, X86::R9
2613 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2616 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2617 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2619 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2622 // FIXME: Get this from tablegen.
2623 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2624 CallingConv::ID CallConv,
2625 const X86Subtarget *Subtarget) {
2626 assert(Subtarget->is64Bit());
2627 if (Subtarget->isCallingConvWin64(CallConv)) {
2628 // The XMM registers which might contain var arg parameters are shadowed
2629 // in their paired GPR. So we only need to save the GPR to their home
2631 // TODO: __vectorcall will change this.
2635 const Function *Fn = MF.getFunction();
2636 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2637 bool isSoftFloat = Subtarget->useSoftFloat();
2638 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2639 "SSE register cannot be used when SSE is disabled!");
2640 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2641 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2645 static const MCPhysReg XMMArgRegs64Bit[] = {
2646 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2647 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2649 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2652 SDValue X86TargetLowering::LowerFormalArguments(
2653 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2654 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2655 SmallVectorImpl<SDValue> &InVals) const {
2656 MachineFunction &MF = DAG.getMachineFunction();
2657 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2658 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2660 const Function* Fn = MF.getFunction();
2661 if (Fn->hasExternalLinkage() &&
2662 Subtarget->isTargetCygMing() &&
2663 Fn->getName() == "main")
2664 FuncInfo->setForceFramePointer(true);
2666 MachineFrameInfo *MFI = MF.getFrameInfo();
2667 bool Is64Bit = Subtarget->is64Bit();
2668 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2670 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2671 "Var args not supported with calling convention fastcc, ghc or hipe");
2673 if (CallConv == CallingConv::X86_INTR) {
2674 bool isLegal = Ins.size() == 1 ||
2675 (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
2676 (!Is64Bit && Ins[1].VT == MVT::i32)));
2678 report_fatal_error("X86 interrupts may take one or two arguments");
2681 // Assign locations to all of the incoming arguments.
2682 SmallVector<CCValAssign, 16> ArgLocs;
2683 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2685 // Allocate shadow area for Win64
2687 CCInfo.AllocateStack(32, 8);
2689 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2691 unsigned LastVal = ~0U;
2693 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2694 CCValAssign &VA = ArgLocs[i];
2695 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2697 assert(VA.getValNo() != LastVal &&
2698 "Don't support value assigned to multiple locs yet");
2700 LastVal = VA.getValNo();
2702 if (VA.isRegLoc()) {
2703 EVT RegVT = VA.getLocVT();
2704 const TargetRegisterClass *RC;
2705 if (RegVT == MVT::i32)
2706 RC = &X86::GR32RegClass;
2707 else if (Is64Bit && RegVT == MVT::i64)
2708 RC = &X86::GR64RegClass;
2709 else if (RegVT == MVT::f32)
2710 RC = &X86::FR32RegClass;
2711 else if (RegVT == MVT::f64)
2712 RC = &X86::FR64RegClass;
2713 else if (RegVT == MVT::f128)
2714 RC = &X86::FR128RegClass;
2715 else if (RegVT.is512BitVector())
2716 RC = &X86::VR512RegClass;
2717 else if (RegVT.is256BitVector())
2718 RC = &X86::VR256RegClass;
2719 else if (RegVT.is128BitVector())
2720 RC = &X86::VR128RegClass;
2721 else if (RegVT == MVT::x86mmx)
2722 RC = &X86::VR64RegClass;
2723 else if (RegVT == MVT::i1)
2724 RC = &X86::VK1RegClass;
2725 else if (RegVT == MVT::v8i1)
2726 RC = &X86::VK8RegClass;
2727 else if (RegVT == MVT::v16i1)
2728 RC = &X86::VK16RegClass;
2729 else if (RegVT == MVT::v32i1)
2730 RC = &X86::VK32RegClass;
2731 else if (RegVT == MVT::v64i1)
2732 RC = &X86::VK64RegClass;
2734 llvm_unreachable("Unknown argument type!");
2736 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2737 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2739 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2740 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2742 if (VA.getLocInfo() == CCValAssign::SExt)
2743 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2744 DAG.getValueType(VA.getValVT()));
2745 else if (VA.getLocInfo() == CCValAssign::ZExt)
2746 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2747 DAG.getValueType(VA.getValVT()));
2748 else if (VA.getLocInfo() == CCValAssign::BCvt)
2749 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2751 if (VA.isExtInLoc()) {
2752 // Handle MMX values passed in XMM regs.
2753 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2754 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2756 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2759 assert(VA.isMemLoc());
2760 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2763 // If value is passed via pointer - do a load.
2764 if (VA.getLocInfo() == CCValAssign::Indirect)
2765 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2766 MachinePointerInfo(), false, false, false, 0);
2768 InVals.push_back(ArgValue);
2771 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2772 // All x86 ABIs require that for returning structs by value we copy the
2773 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2774 // the argument into a virtual register so that we can access it from the
2776 if (Ins[i].Flags.isSRet()) {
2777 unsigned Reg = FuncInfo->getSRetReturnReg();
2779 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2780 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2781 FuncInfo->setSRetReturnReg(Reg);
2783 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2784 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2789 unsigned StackSize = CCInfo.getNextStackOffset();
2790 // Align stack specially for tail calls.
2791 if (shouldGuaranteeTCO(CallConv,
2792 MF.getTarget().Options.GuaranteedTailCallOpt))
2793 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2795 // If the function takes variable number of arguments, make a frame index for
2796 // the start of the first vararg value... for expansion of llvm.va_start. We
2797 // can skip this if there are no va_start calls.
2798 if (MFI->hasVAStart() &&
2799 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2800 CallConv != CallingConv::X86_ThisCall))) {
2801 FuncInfo->setVarArgsFrameIndex(
2802 MFI->CreateFixedObject(1, StackSize, true));
2805 // Figure out if XMM registers are in use.
2806 assert(!(Subtarget->useSoftFloat() &&
2807 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2808 "SSE register cannot be used when SSE is disabled!");
2810 // 64-bit calling conventions support varargs and register parameters, so we
2811 // have to do extra work to spill them in the prologue.
2812 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2813 // Find the first unallocated argument registers.
2814 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2815 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2816 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2817 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2818 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2819 "SSE register cannot be used when SSE is disabled!");
2821 // Gather all the live in physical registers.
2822 SmallVector<SDValue, 6> LiveGPRs;
2823 SmallVector<SDValue, 8> LiveXMMRegs;
2825 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2826 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2828 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2830 if (!ArgXMMs.empty()) {
2831 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2832 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2833 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2834 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2835 LiveXMMRegs.push_back(
2836 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2841 // Get to the caller-allocated home save location. Add 8 to account
2842 // for the return address.
2843 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2844 FuncInfo->setRegSaveFrameIndex(
2845 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2846 // Fixup to set vararg frame on shadow area (4 x i64).
2848 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2850 // For X86-64, if there are vararg parameters that are passed via
2851 // registers, then we must store them to their spots on the stack so
2852 // they may be loaded by deferencing the result of va_next.
2853 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2854 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2855 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2856 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2859 // Store the integer parameter registers.
2860 SmallVector<SDValue, 8> MemOps;
2861 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2862 getPointerTy(DAG.getDataLayout()));
2863 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2864 for (SDValue Val : LiveGPRs) {
2865 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2866 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2868 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2869 MachinePointerInfo::getFixedStack(
2870 DAG.getMachineFunction(),
2871 FuncInfo->getRegSaveFrameIndex(), Offset),
2873 MemOps.push_back(Store);
2877 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2878 // Now store the XMM (fp + vector) parameter registers.
2879 SmallVector<SDValue, 12> SaveXMMOps;
2880 SaveXMMOps.push_back(Chain);
2881 SaveXMMOps.push_back(ALVal);
2882 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2883 FuncInfo->getRegSaveFrameIndex(), dl));
2884 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2885 FuncInfo->getVarArgsFPOffset(), dl));
2886 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2888 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2889 MVT::Other, SaveXMMOps));
2892 if (!MemOps.empty())
2893 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2896 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2897 // Find the largest legal vector type.
2898 MVT VecVT = MVT::Other;
2899 // FIXME: Only some x86_32 calling conventions support AVX512.
2900 if (Subtarget->hasAVX512() &&
2901 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2902 CallConv == CallingConv::Intel_OCL_BI)))
2903 VecVT = MVT::v16f32;
2904 else if (Subtarget->hasAVX())
2906 else if (Subtarget->hasSSE2())
2909 // We forward some GPRs and some vector types.
2910 SmallVector<MVT, 2> RegParmTypes;
2911 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2912 RegParmTypes.push_back(IntVT);
2913 if (VecVT != MVT::Other)
2914 RegParmTypes.push_back(VecVT);
2916 // Compute the set of forwarded registers. The rest are scratch.
2917 SmallVectorImpl<ForwardedRegister> &Forwards =
2918 FuncInfo->getForwardedMustTailRegParms();
2919 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2921 // Conservatively forward AL on x86_64, since it might be used for varargs.
2922 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2923 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2924 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2927 // Copy all forwards from physical to virtual registers.
2928 for (ForwardedRegister &F : Forwards) {
2929 // FIXME: Can we use a less constrained schedule?
2930 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2931 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2932 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2936 // Some CCs need callee pop.
2937 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2938 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2939 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2940 } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
2941 // X86 interrupts must pop the error code if present
2942 FuncInfo->setBytesToPopOnReturn(Is64Bit ? 8 : 4);
2944 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2945 // If this is an sret function, the return should pop the hidden pointer.
2946 if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2947 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2948 argsAreStructReturn(Ins) == StackStructReturn)
2949 FuncInfo->setBytesToPopOnReturn(4);
2953 // RegSaveFrameIndex is X86-64 only.
2954 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2955 if (CallConv == CallingConv::X86_FastCall ||
2956 CallConv == CallingConv::X86_ThisCall)
2957 // fastcc functions can't have varargs.
2958 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2961 FuncInfo->setArgumentStackSize(StackSize);
2963 if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
2964 EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
2965 if (Personality == EHPersonality::CoreCLR) {
2967 // TODO: Add a mechanism to frame lowering that will allow us to indicate
2968 // that we'd prefer this slot be allocated towards the bottom of the frame
2969 // (i.e. near the stack pointer after allocating the frame). Every
2970 // funclet needs a copy of this slot in its (mostly empty) frame, and the
2971 // offset from the bottom of this and each funclet's frame must be the
2972 // same, so the size of funclets' (mostly empty) frames is dictated by
2973 // how far this slot is from the bottom (since they allocate just enough
2974 // space to accomodate holding this slot at the correct offset).
2975 int PSPSymFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2976 EHInfo->PSPSymFrameIdx = PSPSymFI;
2984 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2985 SDValue StackPtr, SDValue Arg,
2986 SDLoc dl, SelectionDAG &DAG,
2987 const CCValAssign &VA,
2988 ISD::ArgFlagsTy Flags) const {
2989 unsigned LocMemOffset = VA.getLocMemOffset();
2990 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2991 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2993 if (Flags.isByVal())
2994 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2996 return DAG.getStore(
2997 Chain, dl, Arg, PtrOff,
2998 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
3002 /// Emit a load of return address if tail call
3003 /// optimization is performed and it is required.
3005 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
3006 SDValue &OutRetAddr, SDValue Chain,
3007 bool IsTailCall, bool Is64Bit,
3008 int FPDiff, SDLoc dl) const {
3009 // Adjust the Return address stack slot.
3010 EVT VT = getPointerTy(DAG.getDataLayout());
3011 OutRetAddr = getReturnAddressFrameIndex(DAG);
3013 // Load the "old" Return address.
3014 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
3015 false, false, false, 0);
3016 return SDValue(OutRetAddr.getNode(), 1);
3019 /// Emit a store of the return address if tail call
3020 /// optimization is performed and it is required (FPDiff!=0).
3021 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3022 SDValue Chain, SDValue RetAddrFrIdx,
3023 EVT PtrVT, unsigned SlotSize,
3024 int FPDiff, SDLoc dl) {
3025 // Store the return address to the appropriate stack slot.
3026 if (!FPDiff) return Chain;
3027 // Calculate the new stack slot for the return address.
3028 int NewReturnAddrFI =
3029 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3031 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3032 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3033 MachinePointerInfo::getFixedStack(
3034 DAG.getMachineFunction(), NewReturnAddrFI),
3039 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3040 /// operation of specified width.
3041 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
3043 unsigned NumElems = VT.getVectorNumElements();
3044 SmallVector<int, 8> Mask;
3045 Mask.push_back(NumElems);
3046 for (unsigned i = 1; i != NumElems; ++i)
3048 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3052 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3053 SmallVectorImpl<SDValue> &InVals) const {
3054 SelectionDAG &DAG = CLI.DAG;
3056 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3057 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3058 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3059 SDValue Chain = CLI.Chain;
3060 SDValue Callee = CLI.Callee;
3061 CallingConv::ID CallConv = CLI.CallConv;
3062 bool &isTailCall = CLI.IsTailCall;
3063 bool isVarArg = CLI.IsVarArg;
3065 MachineFunction &MF = DAG.getMachineFunction();
3066 bool Is64Bit = Subtarget->is64Bit();
3067 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
3068 StructReturnType SR = callIsStructReturn(Outs);
3069 bool IsSibcall = false;
3070 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3071 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3073 if (CallConv == CallingConv::X86_INTR)
3074 report_fatal_error("X86 interrupts may not be called directly");
3076 if (Attr.getValueAsString() == "true")
3079 if (Subtarget->isPICStyleGOT() &&
3080 !MF.getTarget().Options.GuaranteedTailCallOpt) {
3081 // If we are using a GOT, disable tail calls to external symbols with
3082 // default visibility. Tail calling such a symbol requires using a GOT
3083 // relocation, which forces early binding of the symbol. This breaks code
3084 // that require lazy function symbol resolution. Using musttail or
3085 // GuaranteedTailCallOpt will override this.
3086 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3087 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3088 G->getGlobal()->hasDefaultVisibility()))
3092 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3094 // Force this to be a tail call. The verifier rules are enough to ensure
3095 // that we can lower this successfully without moving the return address
3098 } else if (isTailCall) {
3099 // Check if it's really possible to do a tail call.
3100 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3101 isVarArg, SR != NotStructReturn,
3102 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3103 Outs, OutVals, Ins, DAG);
3105 // Sibcalls are automatically detected tailcalls which do not require
3107 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3114 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3115 "Var args not supported with calling convention fastcc, ghc or hipe");
3117 // Analyze operands of the call, assigning locations to each operand.
3118 SmallVector<CCValAssign, 16> ArgLocs;
3119 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3121 // Allocate shadow area for Win64
3123 CCInfo.AllocateStack(32, 8);
3125 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3127 // Get a count of how many bytes are to be pushed on the stack.
3128 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3130 // This is a sibcall. The memory operands are available in caller's
3131 // own caller's stack.
3133 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3134 canGuaranteeTCO(CallConv))
3135 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3138 if (isTailCall && !IsSibcall && !IsMustTail) {
3139 // Lower arguments at fp - stackoffset + fpdiff.
3140 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3142 FPDiff = NumBytesCallerPushed - NumBytes;
3144 // Set the delta of movement of the returnaddr stackslot.
3145 // But only set if delta is greater than previous delta.
3146 if (FPDiff < X86Info->getTCReturnAddrDelta())
3147 X86Info->setTCReturnAddrDelta(FPDiff);
3150 unsigned NumBytesToPush = NumBytes;
3151 unsigned NumBytesToPop = NumBytes;
3153 // If we have an inalloca argument, all stack space has already been allocated
3154 // for us and be right at the top of the stack. We don't support multiple
3155 // arguments passed in memory when using inalloca.
3156 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3158 if (!ArgLocs.back().isMemLoc())
3159 report_fatal_error("cannot use inalloca attribute on a register "
3161 if (ArgLocs.back().getLocMemOffset() != 0)
3162 report_fatal_error("any parameter with the inalloca attribute must be "
3163 "the only memory argument");
3167 Chain = DAG.getCALLSEQ_START(
3168 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3170 SDValue RetAddrFrIdx;
3171 // Load return address for tail calls.
3172 if (isTailCall && FPDiff)
3173 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3174 Is64Bit, FPDiff, dl);
3176 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3177 SmallVector<SDValue, 8> MemOpChains;
3180 // Walk the register/memloc assignments, inserting copies/loads. In the case
3181 // of tail call optimization arguments are handle later.
3182 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3183 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3184 // Skip inalloca arguments, they have already been written.
3185 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3186 if (Flags.isInAlloca())
3189 CCValAssign &VA = ArgLocs[i];
3190 EVT RegVT = VA.getLocVT();
3191 SDValue Arg = OutVals[i];
3192 bool isByVal = Flags.isByVal();
3194 // Promote the value if needed.
3195 switch (VA.getLocInfo()) {
3196 default: llvm_unreachable("Unknown loc info!");
3197 case CCValAssign::Full: break;
3198 case CCValAssign::SExt:
3199 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3201 case CCValAssign::ZExt:
3202 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3204 case CCValAssign::AExt:
3205 if (Arg.getValueType().isVector() &&
3206 Arg.getValueType().getVectorElementType() == MVT::i1)
3207 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3208 else if (RegVT.is128BitVector()) {
3209 // Special case: passing MMX values in XMM registers.
3210 Arg = DAG.getBitcast(MVT::i64, Arg);
3211 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3212 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3214 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3216 case CCValAssign::BCvt:
3217 Arg = DAG.getBitcast(RegVT, Arg);
3219 case CCValAssign::Indirect: {
3220 // Store the argument.
3221 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3222 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3223 Chain = DAG.getStore(
3224 Chain, dl, Arg, SpillSlot,
3225 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3232 if (VA.isRegLoc()) {
3233 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3234 if (isVarArg && IsWin64) {
3235 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3236 // shadow reg if callee is a varargs function.
3237 unsigned ShadowReg = 0;
3238 switch (VA.getLocReg()) {
3239 case X86::XMM0: ShadowReg = X86::RCX; break;
3240 case X86::XMM1: ShadowReg = X86::RDX; break;
3241 case X86::XMM2: ShadowReg = X86::R8; break;
3242 case X86::XMM3: ShadowReg = X86::R9; break;
3245 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3247 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3248 assert(VA.isMemLoc());
3249 if (!StackPtr.getNode())
3250 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3251 getPointerTy(DAG.getDataLayout()));
3252 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3253 dl, DAG, VA, Flags));
3257 if (!MemOpChains.empty())
3258 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3260 if (Subtarget->isPICStyleGOT()) {
3261 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3264 RegsToPass.push_back(std::make_pair(
3265 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3266 getPointerTy(DAG.getDataLayout()))));
3268 // If we are tail calling and generating PIC/GOT style code load the
3269 // address of the callee into ECX. The value in ecx is used as target of
3270 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3271 // for tail calls on PIC/GOT architectures. Normally we would just put the
3272 // address of GOT into ebx and then call target@PLT. But for tail calls
3273 // ebx would be restored (since ebx is callee saved) before jumping to the
3276 // Note: The actual moving to ECX is done further down.
3277 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3278 if (G && !G->getGlobal()->hasLocalLinkage() &&
3279 G->getGlobal()->hasDefaultVisibility())
3280 Callee = LowerGlobalAddress(Callee, DAG);
3281 else if (isa<ExternalSymbolSDNode>(Callee))
3282 Callee = LowerExternalSymbol(Callee, DAG);
3286 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3287 // From AMD64 ABI document:
3288 // For calls that may call functions that use varargs or stdargs
3289 // (prototype-less calls or calls to functions containing ellipsis (...) in
3290 // the declaration) %al is used as hidden argument to specify the number
3291 // of SSE registers used. The contents of %al do not need to match exactly
3292 // the number of registers, but must be an ubound on the number of SSE
3293 // registers used and is in the range 0 - 8 inclusive.
3295 // Count the number of XMM registers allocated.
3296 static const MCPhysReg XMMArgRegs[] = {
3297 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3298 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3300 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3301 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3302 && "SSE registers cannot be used when SSE is disabled");
3304 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3305 DAG.getConstant(NumXMMRegs, dl,
3309 if (isVarArg && IsMustTail) {
3310 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3311 for (const auto &F : Forwards) {
3312 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3313 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3317 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3318 // don't need this because the eligibility check rejects calls that require
3319 // shuffling arguments passed in memory.
3320 if (!IsSibcall && isTailCall) {
3321 // Force all the incoming stack arguments to be loaded from the stack
3322 // before any new outgoing arguments are stored to the stack, because the
3323 // outgoing stack slots may alias the incoming argument stack slots, and
3324 // the alias isn't otherwise explicit. This is slightly more conservative
3325 // than necessary, because it means that each store effectively depends
3326 // on every argument instead of just those arguments it would clobber.
3327 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3329 SmallVector<SDValue, 8> MemOpChains2;
3332 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3333 CCValAssign &VA = ArgLocs[i];
3336 assert(VA.isMemLoc());
3337 SDValue Arg = OutVals[i];
3338 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3339 // Skip inalloca arguments. They don't require any work.
3340 if (Flags.isInAlloca())
3342 // Create frame index.
3343 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3344 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3345 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3346 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3348 if (Flags.isByVal()) {
3349 // Copy relative to framepointer.
3350 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3351 if (!StackPtr.getNode())
3352 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3353 getPointerTy(DAG.getDataLayout()));
3354 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3357 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3361 // Store relative to framepointer.
3362 MemOpChains2.push_back(DAG.getStore(
3363 ArgChain, dl, Arg, FIN,
3364 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3369 if (!MemOpChains2.empty())
3370 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3372 // Store the return address to the appropriate stack slot.
3373 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3374 getPointerTy(DAG.getDataLayout()),
3375 RegInfo->getSlotSize(), FPDiff, dl);
3378 // Build a sequence of copy-to-reg nodes chained together with token chain
3379 // and flag operands which copy the outgoing args into registers.
3381 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3382 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3383 RegsToPass[i].second, InFlag);
3384 InFlag = Chain.getValue(1);
3387 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3388 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3389 // In the 64-bit large code model, we have to make all calls
3390 // through a register, since the call instruction's 32-bit
3391 // pc-relative offset may not be large enough to hold the whole
3393 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3394 // If the callee is a GlobalAddress node (quite common, every direct call
3395 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3397 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3399 // We should use extra load for direct calls to dllimported functions in
3401 const GlobalValue *GV = G->getGlobal();
3402 if (!GV->hasDLLImportStorageClass()) {
3403 unsigned char OpFlags = 0;
3404 bool ExtraLoad = false;
3405 unsigned WrapperKind = ISD::DELETED_NODE;
3407 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3408 // external symbols most go through the PLT in PIC mode. If the symbol
3409 // has hidden or protected visibility, or if it is static or local, then
3410 // we don't need to use the PLT - we can directly call it.
3411 if (Subtarget->isTargetELF() &&
3412 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3413 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3414 OpFlags = X86II::MO_PLT;
3415 } else if (Subtarget->isPICStyleStubAny() &&
3416 !GV->isStrongDefinitionForLinker() &&
3417 (!Subtarget->getTargetTriple().isMacOSX() ||
3418 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3419 // PC-relative references to external symbols should go through $stub,
3420 // unless we're building with the leopard linker or later, which
3421 // automatically synthesizes these stubs.
3422 OpFlags = X86II::MO_DARWIN_STUB;
3423 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3424 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3425 // If the function is marked as non-lazy, generate an indirect call
3426 // which loads from the GOT directly. This avoids runtime overhead
3427 // at the cost of eager binding (and one extra byte of encoding).
3428 OpFlags = X86II::MO_GOTPCREL;
3429 WrapperKind = X86ISD::WrapperRIP;
3433 Callee = DAG.getTargetGlobalAddress(
3434 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3436 // Add a wrapper if needed.
3437 if (WrapperKind != ISD::DELETED_NODE)
3438 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3439 getPointerTy(DAG.getDataLayout()), Callee);
3440 // Add extra indirection if needed.
3442 Callee = DAG.getLoad(
3443 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3444 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3447 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3448 unsigned char OpFlags = 0;
3450 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3451 // external symbols should go through the PLT.
3452 if (Subtarget->isTargetELF() &&
3453 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3454 OpFlags = X86II::MO_PLT;
3455 } else if (Subtarget->isPICStyleStubAny() &&
3456 (!Subtarget->getTargetTriple().isMacOSX() ||
3457 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3458 // PC-relative references to external symbols should go through $stub,
3459 // unless we're building with the leopard linker or later, which
3460 // automatically synthesizes these stubs.
3461 OpFlags = X86II::MO_DARWIN_STUB;
3464 Callee = DAG.getTargetExternalSymbol(
3465 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3466 } else if (Subtarget->isTarget64BitILP32() &&
3467 Callee->getValueType(0) == MVT::i32) {
3468 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3469 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3472 // Returns a chain & a flag for retval copy to use.
3473 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3474 SmallVector<SDValue, 8> Ops;
3476 if (!IsSibcall && isTailCall) {
3477 Chain = DAG.getCALLSEQ_END(Chain,
3478 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3479 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3480 InFlag = Chain.getValue(1);
3483 Ops.push_back(Chain);
3484 Ops.push_back(Callee);
3487 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3489 // Add argument registers to the end of the list so that they are known live
3491 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3492 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3493 RegsToPass[i].second.getValueType()));
3495 // Add a register mask operand representing the call-preserved registers.
3496 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3497 assert(Mask && "Missing call preserved mask for calling convention");
3499 // If this is an invoke in a 32-bit function using a funclet-based
3500 // personality, assume the function clobbers all registers. If an exception
3501 // is thrown, the runtime will not restore CSRs.
3502 // FIXME: Model this more precisely so that we can register allocate across
3503 // the normal edge and spill and fill across the exceptional edge.
3504 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3505 const Function *CallerFn = MF.getFunction();
3506 EHPersonality Pers =
3507 CallerFn->hasPersonalityFn()
3508 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3509 : EHPersonality::Unknown;
3510 if (isFuncletEHPersonality(Pers))
3511 Mask = RegInfo->getNoPreservedMask();
3514 Ops.push_back(DAG.getRegisterMask(Mask));
3516 if (InFlag.getNode())
3517 Ops.push_back(InFlag);
3521 //// If this is the first return lowered for this function, add the regs
3522 //// to the liveout set for the function.
3523 // This isn't right, although it's probably harmless on x86; liveouts
3524 // should be computed from returns not tail calls. Consider a void
3525 // function making a tail call to a function returning int.
3526 MF.getFrameInfo()->setHasTailCall();
3527 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3530 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3531 InFlag = Chain.getValue(1);
3533 // Create the CALLSEQ_END node.
3534 unsigned NumBytesForCalleeToPop;
3535 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3536 DAG.getTarget().Options.GuaranteedTailCallOpt))
3537 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3538 else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3539 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3540 SR == StackStructReturn)
3541 // If this is a call to a struct-return function, the callee
3542 // pops the hidden struct pointer, so we have to push it back.
3543 // This is common for Darwin/X86, Linux & Mingw32 targets.
3544 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3545 NumBytesForCalleeToPop = 4;
3547 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3549 // Returns a flag for retval copy to use.
3551 Chain = DAG.getCALLSEQ_END(Chain,
3552 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3553 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3556 InFlag = Chain.getValue(1);
3559 // Handle result values, copying them out of physregs into vregs that we
3561 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3562 Ins, dl, DAG, InVals);
3565 //===----------------------------------------------------------------------===//
3566 // Fast Calling Convention (tail call) implementation
3567 //===----------------------------------------------------------------------===//
3569 // Like std call, callee cleans arguments, convention except that ECX is
3570 // reserved for storing the tail called function address. Only 2 registers are
3571 // free for argument passing (inreg). Tail call optimization is performed
3573 // * tailcallopt is enabled
3574 // * caller/callee are fastcc
3575 // On X86_64 architecture with GOT-style position independent code only local
3576 // (within module) calls are supported at the moment.
3577 // To keep the stack aligned according to platform abi the function
3578 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3579 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3580 // If a tail called function callee has more arguments than the caller the
3581 // caller needs to make sure that there is room to move the RETADDR to. This is
3582 // achieved by reserving an area the size of the argument delta right after the
3583 // original RETADDR, but before the saved framepointer or the spilled registers
3584 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3596 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3599 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3600 SelectionDAG& DAG) const {
3601 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3602 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3603 unsigned StackAlignment = TFI.getStackAlignment();
3604 uint64_t AlignMask = StackAlignment - 1;
3605 int64_t Offset = StackSize;
3606 unsigned SlotSize = RegInfo->getSlotSize();
3607 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3608 // Number smaller than 12 so just add the difference.
3609 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3611 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3612 Offset = ((~AlignMask) & Offset) + StackAlignment +
3613 (StackAlignment-SlotSize);
3618 /// Return true if the given stack call argument is already available in the
3619 /// same position (relatively) of the caller's incoming argument stack.
3621 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3622 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3623 const X86InstrInfo *TII) {
3624 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3626 if (Arg.getOpcode() == ISD::CopyFromReg) {
3627 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3628 if (!TargetRegisterInfo::isVirtualRegister(VR))
3630 MachineInstr *Def = MRI->getVRegDef(VR);
3633 if (!Flags.isByVal()) {
3634 if (!TII->isLoadFromStackSlot(Def, FI))
3637 unsigned Opcode = Def->getOpcode();
3638 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3639 Opcode == X86::LEA64_32r) &&
3640 Def->getOperand(1).isFI()) {
3641 FI = Def->getOperand(1).getIndex();
3642 Bytes = Flags.getByValSize();
3646 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3647 if (Flags.isByVal())
3648 // ByVal argument is passed in as a pointer but it's now being
3649 // dereferenced. e.g.
3650 // define @foo(%struct.X* %A) {
3651 // tail call @bar(%struct.X* byval %A)
3654 SDValue Ptr = Ld->getBasePtr();
3655 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3658 FI = FINode->getIndex();
3659 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3660 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3661 FI = FINode->getIndex();
3662 Bytes = Flags.getByValSize();
3666 assert(FI != INT_MAX);
3667 if (!MFI->isFixedObjectIndex(FI))
3669 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3672 /// Check whether the call is eligible for tail call optimization. Targets
3673 /// that want to do tail call optimization should implement this function.
3674 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3675 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3676 bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3677 const SmallVectorImpl<ISD::OutputArg> &Outs,
3678 const SmallVectorImpl<SDValue> &OutVals,
3679 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3680 if (!mayTailCallThisCC(CalleeCC))
3683 // If -tailcallopt is specified, make fastcc functions tail-callable.
3684 MachineFunction &MF = DAG.getMachineFunction();
3685 const Function *CallerF = MF.getFunction();
3687 // If the function return type is x86_fp80 and the callee return type is not,
3688 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3689 // perform a tailcall optimization here.
3690 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3693 CallingConv::ID CallerCC = CallerF->getCallingConv();
3694 bool CCMatch = CallerCC == CalleeCC;
3695 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3696 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3698 // Win64 functions have extra shadow space for argument homing. Don't do the
3699 // sibcall if the caller and callee have mismatched expectations for this
3701 if (IsCalleeWin64 != IsCallerWin64)
3704 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3705 if (canGuaranteeTCO(CalleeCC) && CCMatch)
3710 // Look for obvious safe cases to perform tail call optimization that do not
3711 // require ABI changes. This is what gcc calls sibcall.
3713 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3714 // emit a special epilogue.
3715 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3716 if (RegInfo->needsStackRealignment(MF))
3719 // Also avoid sibcall optimization if either caller or callee uses struct
3720 // return semantics.
3721 if (isCalleeStructRet || isCallerStructRet)
3724 // Do not sibcall optimize vararg calls unless all arguments are passed via
3726 if (isVarArg && !Outs.empty()) {
3727 // Optimizing for varargs on Win64 is unlikely to be safe without
3728 // additional testing.
3729 if (IsCalleeWin64 || IsCallerWin64)
3732 SmallVector<CCValAssign, 16> ArgLocs;
3733 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3736 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3737 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3738 if (!ArgLocs[i].isRegLoc())
3742 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3743 // stack. Therefore, if it's not used by the call it is not safe to optimize
3744 // this into a sibcall.
3745 bool Unused = false;
3746 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3753 SmallVector<CCValAssign, 16> RVLocs;
3754 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3756 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3757 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3758 CCValAssign &VA = RVLocs[i];
3759 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3764 // If the calling conventions do not match, then we'd better make sure the
3765 // results are returned in the same way as what the caller expects.
3767 SmallVector<CCValAssign, 16> RVLocs1;
3768 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3770 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3772 SmallVector<CCValAssign, 16> RVLocs2;
3773 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3775 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3777 if (RVLocs1.size() != RVLocs2.size())
3779 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3780 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3782 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3784 if (RVLocs1[i].isRegLoc()) {
3785 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3788 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3794 unsigned StackArgsSize = 0;
3796 // If the callee takes no arguments then go on to check the results of the
3798 if (!Outs.empty()) {
3799 // Check if stack adjustment is needed. For now, do not do this if any
3800 // argument is passed on the stack.
3801 SmallVector<CCValAssign, 16> ArgLocs;
3802 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3805 // Allocate shadow area for Win64
3807 CCInfo.AllocateStack(32, 8);
3809 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3810 StackArgsSize = CCInfo.getNextStackOffset();
3812 if (CCInfo.getNextStackOffset()) {
3813 // Check if the arguments are already laid out in the right way as
3814 // the caller's fixed stack objects.
3815 MachineFrameInfo *MFI = MF.getFrameInfo();
3816 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3817 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3818 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3819 CCValAssign &VA = ArgLocs[i];
3820 SDValue Arg = OutVals[i];
3821 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3822 if (VA.getLocInfo() == CCValAssign::Indirect)
3824 if (!VA.isRegLoc()) {
3825 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3832 // If the tailcall address may be in a register, then make sure it's
3833 // possible to register allocate for it. In 32-bit, the call address can
3834 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3835 // callee-saved registers are restored. These happen to be the same
3836 // registers used to pass 'inreg' arguments so watch out for those.
3837 if (!Subtarget->is64Bit() &&
3838 ((!isa<GlobalAddressSDNode>(Callee) &&
3839 !isa<ExternalSymbolSDNode>(Callee)) ||
3840 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3841 unsigned NumInRegs = 0;
3842 // In PIC we need an extra register to formulate the address computation
3844 unsigned MaxInRegs =
3845 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3847 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3848 CCValAssign &VA = ArgLocs[i];
3851 unsigned Reg = VA.getLocReg();
3854 case X86::EAX: case X86::EDX: case X86::ECX:
3855 if (++NumInRegs == MaxInRegs)
3863 bool CalleeWillPop =
3864 X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3865 MF.getTarget().Options.GuaranteedTailCallOpt);
3867 if (unsigned BytesToPop =
3868 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3869 // If we have bytes to pop, the callee must pop them.
3870 bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3871 if (!CalleePopMatches)
3873 } else if (CalleeWillPop && StackArgsSize > 0) {
3874 // If we don't have bytes to pop, make sure the callee doesn't pop any.
3882 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3883 const TargetLibraryInfo *libInfo) const {
3884 return X86::createFastISel(funcInfo, libInfo);
3887 //===----------------------------------------------------------------------===//
3888 // Other Lowering Hooks
3889 //===----------------------------------------------------------------------===//
3891 static bool MayFoldLoad(SDValue Op) {
3892 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3895 static bool MayFoldIntoStore(SDValue Op) {
3896 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3899 static bool isTargetShuffle(unsigned Opcode) {
3901 default: return false;
3902 case X86ISD::BLENDI:
3903 case X86ISD::PSHUFB:
3904 case X86ISD::PSHUFD:
3905 case X86ISD::PSHUFHW:
3906 case X86ISD::PSHUFLW:
3908 case X86ISD::PALIGNR:
3909 case X86ISD::MOVLHPS:
3910 case X86ISD::MOVLHPD:
3911 case X86ISD::MOVHLPS:
3912 case X86ISD::MOVLPS:
3913 case X86ISD::MOVLPD:
3914 case X86ISD::MOVSHDUP:
3915 case X86ISD::MOVSLDUP:
3916 case X86ISD::MOVDDUP:
3919 case X86ISD::UNPCKL:
3920 case X86ISD::UNPCKH:
3921 case X86ISD::VPERMILPI:
3922 case X86ISD::VPERM2X128:
3923 case X86ISD::VPERMI:
3924 case X86ISD::VPERMV:
3925 case X86ISD::VPERMV3:
3930 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3931 SDValue V1, unsigned TargetMask,
3932 SelectionDAG &DAG) {
3934 default: llvm_unreachable("Unknown x86 shuffle node");
3935 case X86ISD::PSHUFD:
3936 case X86ISD::PSHUFHW:
3937 case X86ISD::PSHUFLW:
3938 case X86ISD::VPERMILPI:
3939 case X86ISD::VPERMI:
3940 return DAG.getNode(Opc, dl, VT, V1,
3941 DAG.getConstant(TargetMask, dl, MVT::i8));
3945 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3946 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3948 default: llvm_unreachable("Unknown x86 shuffle node");
3949 case X86ISD::MOVLHPS:
3950 case X86ISD::MOVLHPD:
3951 case X86ISD::MOVHLPS:
3952 case X86ISD::MOVLPS:
3953 case X86ISD::MOVLPD:
3956 case X86ISD::UNPCKL:
3957 case X86ISD::UNPCKH:
3958 return DAG.getNode(Opc, dl, VT, V1, V2);
3962 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3963 MachineFunction &MF = DAG.getMachineFunction();
3964 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3965 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3966 int ReturnAddrIndex = FuncInfo->getRAIndex();
3968 if (ReturnAddrIndex == 0) {
3969 // Set up a frame object for the return address.
3970 unsigned SlotSize = RegInfo->getSlotSize();
3971 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3974 FuncInfo->setRAIndex(ReturnAddrIndex);
3977 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3980 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3981 bool hasSymbolicDisplacement) {
3982 // Offset should fit into 32 bit immediate field.
3983 if (!isInt<32>(Offset))
3986 // If we don't have a symbolic displacement - we don't have any extra
3988 if (!hasSymbolicDisplacement)
3991 // FIXME: Some tweaks might be needed for medium code model.
3992 if (M != CodeModel::Small && M != CodeModel::Kernel)
3995 // For small code model we assume that latest object is 16MB before end of 31
3996 // bits boundary. We may also accept pretty large negative constants knowing
3997 // that all objects are in the positive half of address space.
3998 if (M == CodeModel::Small && Offset < 16*1024*1024)
4001 // For kernel code model we know that all object resist in the negative half
4002 // of 32bits address space. We may not accept negative offsets, since they may
4003 // be just off and we may accept pretty large positive ones.
4004 if (M == CodeModel::Kernel && Offset >= 0)
4010 /// Determines whether the callee is required to pop its own arguments.
4011 /// Callee pop is necessary to support tail calls.
4012 bool X86::isCalleePop(CallingConv::ID CallingConv,
4013 bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4014 // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4015 // can guarantee TCO.
4016 if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4019 switch (CallingConv) {
4022 case CallingConv::X86_StdCall:
4023 case CallingConv::X86_FastCall:
4024 case CallingConv::X86_ThisCall:
4025 case CallingConv::X86_VectorCall:
4030 /// \brief Return true if the condition is an unsigned comparison operation.
4031 static bool isX86CCUnsigned(unsigned X86CC) {
4033 default: llvm_unreachable("Invalid integer condition!");
4034 case X86::COND_E: return true;
4035 case X86::COND_G: return false;
4036 case X86::COND_GE: return false;
4037 case X86::COND_L: return false;
4038 case X86::COND_LE: return false;
4039 case X86::COND_NE: return true;
4040 case X86::COND_B: return true;
4041 case X86::COND_A: return true;
4042 case X86::COND_BE: return true;
4043 case X86::COND_AE: return true;
4047 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4048 switch (SetCCOpcode) {
4049 default: llvm_unreachable("Invalid integer condition!");
4050 case ISD::SETEQ: return X86::COND_E;
4051 case ISD::SETGT: return X86::COND_G;
4052 case ISD::SETGE: return X86::COND_GE;
4053 case ISD::SETLT: return X86::COND_L;
4054 case ISD::SETLE: return X86::COND_LE;
4055 case ISD::SETNE: return X86::COND_NE;
4056 case ISD::SETULT: return X86::COND_B;
4057 case ISD::SETUGT: return X86::COND_A;
4058 case ISD::SETULE: return X86::COND_BE;
4059 case ISD::SETUGE: return X86::COND_AE;
4063 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4064 /// condition code, returning the condition code and the LHS/RHS of the
4065 /// comparison to make.
4066 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
4067 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
4069 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4070 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4071 // X > -1 -> X == 0, jump !sign.
4072 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4073 return X86::COND_NS;
4075 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4076 // X < 0 -> X == 0, jump on sign.
4079 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4081 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4082 return X86::COND_LE;
4086 return TranslateIntegerX86CC(SetCCOpcode);
4089 // First determine if it is required or is profitable to flip the operands.
4091 // If LHS is a foldable load, but RHS is not, flip the condition.
4092 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4093 !ISD::isNON_EXTLoad(RHS.getNode())) {
4094 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4095 std::swap(LHS, RHS);
4098 switch (SetCCOpcode) {
4104 std::swap(LHS, RHS);
4108 // On a floating point condition, the flags are set as follows:
4110 // 0 | 0 | 0 | X > Y
4111 // 0 | 0 | 1 | X < Y
4112 // 1 | 0 | 0 | X == Y
4113 // 1 | 1 | 1 | unordered
4114 switch (SetCCOpcode) {
4115 default: llvm_unreachable("Condcode should be pre-legalized away");
4117 case ISD::SETEQ: return X86::COND_E;
4118 case ISD::SETOLT: // flipped
4120 case ISD::SETGT: return X86::COND_A;
4121 case ISD::SETOLE: // flipped
4123 case ISD::SETGE: return X86::COND_AE;
4124 case ISD::SETUGT: // flipped
4126 case ISD::SETLT: return X86::COND_B;
4127 case ISD::SETUGE: // flipped
4129 case ISD::SETLE: return X86::COND_BE;
4131 case ISD::SETNE: return X86::COND_NE;
4132 case ISD::SETUO: return X86::COND_P;
4133 case ISD::SETO: return X86::COND_NP;
4135 case ISD::SETUNE: return X86::COND_INVALID;
4139 /// Is there a floating point cmov for the specific X86 condition code?
4140 /// Current x86 isa includes the following FP cmov instructions:
4141 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4142 static bool hasFPCMov(unsigned X86CC) {
4158 /// Returns true if the target can instruction select the
4159 /// specified FP immediate natively. If false, the legalizer will
4160 /// materialize the FP immediate as a load from a constant pool.
4161 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4162 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4163 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4169 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4170 ISD::LoadExtType ExtTy,
4172 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4173 // relocation target a movq or addq instruction: don't let the load shrink.
4174 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4175 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4176 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4177 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4181 /// \brief Returns true if it is beneficial to convert a load of a constant
4182 /// to just the constant itself.
4183 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4185 assert(Ty->isIntegerTy());
4187 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4188 if (BitSize == 0 || BitSize > 64)
4193 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4194 unsigned Index) const {
4195 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4198 return (Index == 0 || Index == ResVT.getVectorNumElements());
4201 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4202 // Speculate cttz only if we can directly use TZCNT.
4203 return Subtarget->hasBMI();
4206 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4207 // Speculate ctlz only if we can directly use LZCNT.
4208 return Subtarget->hasLZCNT();
4211 /// Return true if every element in Mask, beginning
4212 /// from position Pos and ending in Pos+Size is undef.
4213 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4214 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4220 /// Return true if Val is undef or if its value falls within the
4221 /// specified range (L, H].
4222 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4223 return (Val < 0) || (Val >= Low && Val < Hi);
4226 /// Val is either less than zero (undef) or equal to the specified value.
4227 static bool isUndefOrEqual(int Val, int CmpVal) {
4228 return (Val < 0 || Val == CmpVal);
4231 /// Return true if every element in Mask, beginning
4232 /// from position Pos and ending in Pos+Size, falls within the specified
4233 /// sequential range (Low, Low+Size]. or is undef.
4234 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4235 unsigned Pos, unsigned Size, int Low) {
4236 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4237 if (!isUndefOrEqual(Mask[i], Low))
4242 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4243 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4244 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4245 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4246 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4249 // The index should be aligned on a vecWidth-bit boundary.
4251 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4253 MVT VT = N->getSimpleValueType(0);
4254 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4255 bool Result = (Index * ElSize) % vecWidth == 0;
4260 /// Return true if the specified INSERT_SUBVECTOR
4261 /// operand specifies a subvector insert that is suitable for input to
4262 /// insertion of 128 or 256-bit subvectors
4263 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4264 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4265 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4267 // The index should be aligned on a vecWidth-bit boundary.
4269 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4271 MVT VT = N->getSimpleValueType(0);
4272 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4273 bool Result = (Index * ElSize) % vecWidth == 0;
4278 bool X86::isVINSERT128Index(SDNode *N) {
4279 return isVINSERTIndex(N, 128);
4282 bool X86::isVINSERT256Index(SDNode *N) {
4283 return isVINSERTIndex(N, 256);
4286 bool X86::isVEXTRACT128Index(SDNode *N) {
4287 return isVEXTRACTIndex(N, 128);
4290 bool X86::isVEXTRACT256Index(SDNode *N) {
4291 return isVEXTRACTIndex(N, 256);
4294 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4295 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4296 assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4297 "Illegal extract subvector for VEXTRACT");
4300 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4302 MVT VecVT = N->getOperand(0).getSimpleValueType();
4303 MVT ElVT = VecVT.getVectorElementType();
4305 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4306 return Index / NumElemsPerChunk;
4309 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4310 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4311 assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4312 "Illegal insert subvector for VINSERT");
4315 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4317 MVT VecVT = N->getSimpleValueType(0);
4318 MVT ElVT = VecVT.getVectorElementType();
4320 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4321 return Index / NumElemsPerChunk;
4324 /// Return the appropriate immediate to extract the specified
4325 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4326 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4327 return getExtractVEXTRACTImmediate(N, 128);
4330 /// Return the appropriate immediate to extract the specified
4331 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4332 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4333 return getExtractVEXTRACTImmediate(N, 256);
4336 /// Return the appropriate immediate to insert at the specified
4337 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4338 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4339 return getInsertVINSERTImmediate(N, 128);
4342 /// Return the appropriate immediate to insert at the specified
4343 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4344 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4345 return getInsertVINSERTImmediate(N, 256);
4348 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4349 bool X86::isZeroNode(SDValue Elt) {
4350 return isNullConstant(Elt) || isNullFPConstant(Elt);
4353 // Build a vector of constants
4354 // Use an UNDEF node if MaskElt == -1.
4355 // Spilt 64-bit constants in the 32-bit mode.
4356 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4358 SDLoc dl, bool IsMask = false) {
4360 SmallVector<SDValue, 32> Ops;
4363 MVT ConstVecVT = VT;
4364 unsigned NumElts = VT.getVectorNumElements();
4365 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4366 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4367 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4371 MVT EltVT = ConstVecVT.getVectorElementType();
4372 for (unsigned i = 0; i < NumElts; ++i) {
4373 bool IsUndef = Values[i] < 0 && IsMask;
4374 SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4375 DAG.getConstant(Values[i], dl, EltVT);
4376 Ops.push_back(OpNode);
4378 Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4379 DAG.getConstant(0, dl, EltVT));
4381 SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4383 ConstsNode = DAG.getBitcast(VT, ConstsNode);
4387 /// Returns a vector of specified type with all zero elements.
4388 static SDValue getZeroVector(MVT VT, const X86Subtarget *Subtarget,
4389 SelectionDAG &DAG, SDLoc dl) {
4390 assert(VT.isVector() && "Expected a vector type");
4392 // Always build SSE zero vectors as <4 x i32> bitcasted
4393 // to their dest type. This ensures they get CSE'd.
4395 if (VT.is128BitVector()) { // SSE
4396 if (Subtarget->hasSSE2()) { // SSE2
4397 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4398 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4400 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4401 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4403 } else if (VT.is256BitVector()) { // AVX
4404 if (Subtarget->hasInt256()) { // AVX2
4405 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4406 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4407 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4409 // 256-bit logic and arithmetic instructions in AVX are all
4410 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4411 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4412 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4413 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4415 } else if (VT.is512BitVector()) { // AVX-512
4416 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4417 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4418 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4419 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4420 } else if (VT.getVectorElementType() == MVT::i1) {
4422 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4423 && "Unexpected vector type");
4424 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4425 && "Unexpected vector type");
4426 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4427 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4428 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4430 llvm_unreachable("Unexpected vector type");
4432 return DAG.getBitcast(VT, Vec);
4435 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4436 SelectionDAG &DAG, SDLoc dl,
4437 unsigned vectorWidth) {
4438 assert((vectorWidth == 128 || vectorWidth == 256) &&
4439 "Unsupported vector width");
4440 EVT VT = Vec.getValueType();
4441 EVT ElVT = VT.getVectorElementType();
4442 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4443 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4444 VT.getVectorNumElements()/Factor);
4446 // Extract from UNDEF is UNDEF.
4447 if (Vec.getOpcode() == ISD::UNDEF)
4448 return DAG.getUNDEF(ResultVT);
4450 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4451 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4452 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4454 // This is the index of the first element of the vectorWidth-bit chunk
4455 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4456 IdxVal &= ~(ElemsPerChunk - 1);
4458 // If the input is a buildvector just emit a smaller one.
4459 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4460 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4461 makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4463 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4464 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4467 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4468 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4469 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4470 /// instructions or a simple subregister reference. Idx is an index in the
4471 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4472 /// lowering EXTRACT_VECTOR_ELT operations easier.
4473 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4474 SelectionDAG &DAG, SDLoc dl) {
4475 assert((Vec.getValueType().is256BitVector() ||
4476 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4477 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4480 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4481 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4482 SelectionDAG &DAG, SDLoc dl) {
4483 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4484 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4487 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4488 unsigned IdxVal, SelectionDAG &DAG,
4489 SDLoc dl, unsigned vectorWidth) {
4490 assert((vectorWidth == 128 || vectorWidth == 256) &&
4491 "Unsupported vector width");
4492 // Inserting UNDEF is Result
4493 if (Vec.getOpcode() == ISD::UNDEF)
4495 EVT VT = Vec.getValueType();
4496 EVT ElVT = VT.getVectorElementType();
4497 EVT ResultVT = Result.getValueType();
4499 // Insert the relevant vectorWidth bits.
4500 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4501 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4503 // This is the index of the first element of the vectorWidth-bit chunk
4504 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4505 IdxVal &= ~(ElemsPerChunk - 1);
4507 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4508 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4511 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4512 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4513 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4514 /// simple superregister reference. Idx is an index in the 128 bits
4515 /// we want. It need not be aligned to a 128-bit boundary. That makes
4516 /// lowering INSERT_VECTOR_ELT operations easier.
4517 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4518 SelectionDAG &DAG, SDLoc dl) {
4519 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4521 // For insertion into the zero index (low half) of a 256-bit vector, it is
4522 // more efficient to generate a blend with immediate instead of an insert*128.
4523 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4524 // extend the subvector to the size of the result vector. Make sure that
4525 // we are not recursing on that node by checking for undef here.
4526 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4527 Result.getOpcode() != ISD::UNDEF) {
4528 EVT ResultVT = Result.getValueType();
4529 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4530 SDValue Undef = DAG.getUNDEF(ResultVT);
4531 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4534 // The blend instruction, and therefore its mask, depend on the data type.
4535 MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4536 if (ScalarType.isFloatingPoint()) {
4537 // Choose either vblendps (float) or vblendpd (double).
4538 unsigned ScalarSize = ScalarType.getSizeInBits();
4539 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4540 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4541 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4542 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4545 const X86Subtarget &Subtarget =
4546 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4548 // AVX2 is needed for 256-bit integer blend support.
4549 // Integers must be cast to 32-bit because there is only vpblendd;
4550 // vpblendw can't be used for this because it has a handicapped mask.
4552 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4553 // is still more efficient than using the wrong domain vinsertf128 that
4554 // will be created by InsertSubVector().
4555 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4557 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4558 Vec256 = DAG.getBitcast(CastVT, Vec256);
4559 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4560 return DAG.getBitcast(ResultVT, Vec256);
4563 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4566 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4567 SelectionDAG &DAG, SDLoc dl) {
4568 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4569 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4572 /// Insert i1-subvector to i1-vector.
4573 static SDValue Insert1BitVector(SDValue Op, SelectionDAG &DAG) {
4576 SDValue Vec = Op.getOperand(0);
4577 SDValue SubVec = Op.getOperand(1);
4578 SDValue Idx = Op.getOperand(2);
4580 if (!isa<ConstantSDNode>(Idx))
4583 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4584 if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
4587 MVT OpVT = Op.getSimpleValueType();
4588 MVT SubVecVT = SubVec.getSimpleValueType();
4589 unsigned NumElems = OpVT.getVectorNumElements();
4590 unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4592 assert(IdxVal + SubVecNumElems <= NumElems &&
4593 IdxVal % SubVecVT.getSizeInBits() == 0 &&
4594 "Unexpected index value in INSERT_SUBVECTOR");
4596 // There are 3 possible cases:
4597 // 1. Subvector should be inserted in the lower part (IdxVal == 0)
4598 // 2. Subvector should be inserted in the upper part
4599 // (IdxVal + SubVecNumElems == NumElems)
4600 // 3. Subvector should be inserted in the middle (for example v2i1
4601 // to v16i1, index 2)
4603 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
4604 SDValue Undef = DAG.getUNDEF(OpVT);
4605 SDValue WideSubVec =
4606 DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef, SubVec, ZeroIdx);
4608 return DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4609 DAG.getConstant(IdxVal, dl, MVT::i8));
4611 if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
4612 unsigned ShiftLeft = NumElems - SubVecNumElems;
4613 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4614 WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4615 DAG.getConstant(ShiftLeft, dl, MVT::i8));
4616 return ShiftRight ? DAG.getNode(X86ISD::VSRLI, dl, OpVT, WideSubVec,
4617 DAG.getConstant(ShiftRight, dl, MVT::i8)) : WideSubVec;
4621 // Zero lower bits of the Vec
4622 SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4623 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4624 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4625 // Merge them together
4626 return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4629 // Simple case when we put subvector in the upper part
4630 if (IdxVal + SubVecNumElems == NumElems) {
4631 // Zero upper bits of the Vec
4632 WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec,
4633 DAG.getConstant(IdxVal, dl, MVT::i8));
4634 SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4635 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4636 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4637 return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4639 // Subvector should be inserted in the middle - use shuffle
4640 SmallVector<int, 64> Mask;
4641 for (unsigned i = 0; i < NumElems; ++i)
4642 Mask.push_back(i >= IdxVal && i < IdxVal + SubVecNumElems ?
4644 return DAG.getVectorShuffle(OpVT, dl, WideSubVec, Vec, Mask);
4647 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4648 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4649 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4650 /// large BUILD_VECTORS.
4651 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4652 unsigned NumElems, SelectionDAG &DAG,
4654 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4655 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4658 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4659 unsigned NumElems, SelectionDAG &DAG,
4661 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4662 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4665 /// Returns a vector of specified type with all bits set.
4666 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4667 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4668 /// Then bitcast to their original type, ensuring they get CSE'd.
4669 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4670 SelectionDAG &DAG, SDLoc dl) {
4671 assert(VT.isVector() && "Expected a vector type");
4673 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4675 if (VT.is512BitVector()) {
4676 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4677 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4678 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4679 } else if (VT.is256BitVector()) {
4680 if (Subtarget->hasInt256()) { // AVX2
4681 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4682 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4684 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4685 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4687 } else if (VT.is128BitVector()) {
4688 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4690 llvm_unreachable("Unexpected vector type");
4692 return DAG.getBitcast(VT, Vec);
4695 /// Returns a vector_shuffle node for an unpackl operation.
4696 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4698 unsigned NumElems = VT.getVectorNumElements();
4699 SmallVector<int, 8> Mask;
4700 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4702 Mask.push_back(i + NumElems);
4704 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4707 /// Returns a vector_shuffle node for an unpackh operation.
4708 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4710 unsigned NumElems = VT.getVectorNumElements();
4711 SmallVector<int, 8> Mask;
4712 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4713 Mask.push_back(i + Half);
4714 Mask.push_back(i + NumElems + Half);
4716 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4719 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4720 /// This produces a shuffle where the low element of V2 is swizzled into the
4721 /// zero/undef vector, landing at element Idx.
4722 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4723 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4725 const X86Subtarget *Subtarget,
4726 SelectionDAG &DAG) {
4727 MVT VT = V2.getSimpleValueType();
4729 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4730 unsigned NumElems = VT.getVectorNumElements();
4731 SmallVector<int, 16> MaskVec;
4732 for (unsigned i = 0; i != NumElems; ++i)
4733 // If this is the insertion idx, put the low elt of V2 here.
4734 MaskVec.push_back(i == Idx ? NumElems : i);
4735 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4738 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4739 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4740 /// uses one source. Note that this will set IsUnary for shuffles which use a
4741 /// single input multiple times, and in those cases it will
4742 /// adjust the mask to only have indices within that single input.
4743 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4744 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4745 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4746 unsigned NumElems = VT.getVectorNumElements();
4750 bool IsFakeUnary = false;
4751 switch(N->getOpcode()) {
4752 case X86ISD::BLENDI:
4753 ImmN = N->getOperand(N->getNumOperands()-1);
4754 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4757 ImmN = N->getOperand(N->getNumOperands()-1);
4758 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4759 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4761 case X86ISD::UNPCKH:
4762 DecodeUNPCKHMask(VT, Mask);
4763 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4765 case X86ISD::UNPCKL:
4766 DecodeUNPCKLMask(VT, Mask);
4767 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4769 case X86ISD::MOVHLPS:
4770 DecodeMOVHLPSMask(NumElems, Mask);
4771 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4773 case X86ISD::MOVLHPS:
4774 DecodeMOVLHPSMask(NumElems, Mask);
4775 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4777 case X86ISD::PALIGNR:
4778 ImmN = N->getOperand(N->getNumOperands()-1);
4779 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4781 case X86ISD::PSHUFD:
4782 case X86ISD::VPERMILPI:
4783 ImmN = N->getOperand(N->getNumOperands()-1);
4784 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4787 case X86ISD::PSHUFHW:
4788 ImmN = N->getOperand(N->getNumOperands()-1);
4789 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4792 case X86ISD::PSHUFLW:
4793 ImmN = N->getOperand(N->getNumOperands()-1);
4794 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4797 case X86ISD::PSHUFB: {
4799 SDValue MaskNode = N->getOperand(1);
4800 while (MaskNode->getOpcode() == ISD::BITCAST)
4801 MaskNode = MaskNode->getOperand(0);
4803 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4804 // If we have a build-vector, then things are easy.
4805 MVT VT = MaskNode.getSimpleValueType();
4806 assert(VT.isVector() &&
4807 "Can't produce a non-vector with a build_vector!");
4808 if (!VT.isInteger())
4811 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4813 SmallVector<uint64_t, 32> RawMask;
4814 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4815 SDValue Op = MaskNode->getOperand(i);
4816 if (Op->getOpcode() == ISD::UNDEF) {
4817 RawMask.push_back((uint64_t)SM_SentinelUndef);
4820 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4823 APInt MaskElement = CN->getAPIntValue();
4825 // We now have to decode the element which could be any integer size and
4826 // extract each byte of it.
4827 for (int j = 0; j < NumBytesPerElement; ++j) {
4828 // Note that this is x86 and so always little endian: the low byte is
4829 // the first byte of the mask.
4830 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4831 MaskElement = MaskElement.lshr(8);
4834 DecodePSHUFBMask(RawMask, Mask);
4838 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4842 SDValue Ptr = MaskLoad->getBasePtr();
4843 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4844 Ptr->getOpcode() == X86ISD::WrapperRIP)
4845 Ptr = Ptr->getOperand(0);
4847 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4848 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4851 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4852 DecodePSHUFBMask(C, Mask);
4860 case X86ISD::VPERMI:
4861 ImmN = N->getOperand(N->getNumOperands()-1);
4862 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4867 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4869 case X86ISD::VPERM2X128:
4870 ImmN = N->getOperand(N->getNumOperands()-1);
4871 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4872 if (Mask.empty()) return false;
4873 // Mask only contains negative index if an element is zero.
4874 if (std::any_of(Mask.begin(), Mask.end(),
4875 [](int M){ return M == SM_SentinelZero; }))
4878 case X86ISD::MOVSLDUP:
4879 DecodeMOVSLDUPMask(VT, Mask);
4882 case X86ISD::MOVSHDUP:
4883 DecodeMOVSHDUPMask(VT, Mask);
4886 case X86ISD::MOVDDUP:
4887 DecodeMOVDDUPMask(VT, Mask);
4890 case X86ISD::MOVLHPD:
4891 case X86ISD::MOVLPD:
4892 case X86ISD::MOVLPS:
4893 // Not yet implemented
4895 case X86ISD::VPERMV: {
4897 SDValue MaskNode = N->getOperand(0);
4898 while (MaskNode->getOpcode() == ISD::BITCAST)
4899 MaskNode = MaskNode->getOperand(0);
4901 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4902 SmallVector<uint64_t, 32> RawMask;
4903 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4904 // If we have a build-vector, then things are easy.
4905 assert(MaskNode.getSimpleValueType().isInteger() &&
4906 MaskNode.getSimpleValueType().getVectorNumElements() ==
4907 VT.getVectorNumElements());
4909 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4910 SDValue Op = MaskNode->getOperand(i);
4911 if (Op->getOpcode() == ISD::UNDEF)
4912 RawMask.push_back((uint64_t)SM_SentinelUndef);
4913 else if (isa<ConstantSDNode>(Op)) {
4914 APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4915 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4919 DecodeVPERMVMask(RawMask, Mask);
4922 if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4923 unsigned NumEltsInMask = MaskNode->getNumOperands();
4924 MaskNode = MaskNode->getOperand(0);
4925 auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4927 APInt MaskEltValue = CN->getAPIntValue();
4928 for (unsigned i = 0; i < NumEltsInMask; ++i)
4929 RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4930 DecodeVPERMVMask(RawMask, Mask);
4933 // It may be a scalar load
4936 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4940 SDValue Ptr = MaskLoad->getBasePtr();
4941 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4942 Ptr->getOpcode() == X86ISD::WrapperRIP)
4943 Ptr = Ptr->getOperand(0);
4945 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4946 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4949 auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4951 DecodeVPERMVMask(C, VT, Mask);
4958 case X86ISD::VPERMV3: {
4960 SDValue MaskNode = N->getOperand(1);
4961 while (MaskNode->getOpcode() == ISD::BITCAST)
4962 MaskNode = MaskNode->getOperand(1);
4964 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4965 // If we have a build-vector, then things are easy.
4966 assert(MaskNode.getSimpleValueType().isInteger() &&
4967 MaskNode.getSimpleValueType().getVectorNumElements() ==
4968 VT.getVectorNumElements());
4970 SmallVector<uint64_t, 32> RawMask;
4971 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4973 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4974 SDValue Op = MaskNode->getOperand(i);
4975 if (Op->getOpcode() == ISD::UNDEF)
4976 RawMask.push_back((uint64_t)SM_SentinelUndef);
4978 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4981 APInt MaskElement = CN->getAPIntValue();
4982 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4985 DecodeVPERMV3Mask(RawMask, Mask);
4989 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4993 SDValue Ptr = MaskLoad->getBasePtr();
4994 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4995 Ptr->getOpcode() == X86ISD::WrapperRIP)
4996 Ptr = Ptr->getOperand(0);
4998 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4999 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5002 auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
5004 DecodeVPERMV3Mask(C, VT, Mask);
5011 default: llvm_unreachable("unknown target shuffle node");
5014 // If we have a fake unary shuffle, the shuffle mask is spread across two
5015 // inputs that are actually the same node. Re-map the mask to always point
5016 // into the first input.
5019 if (M >= (int)Mask.size())
5025 /// Returns the scalar element that will make up the ith
5026 /// element of the result of the vector shuffle.
5027 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5030 return SDValue(); // Limit search depth.
5032 SDValue V = SDValue(N, 0);
5033 EVT VT = V.getValueType();
5034 unsigned Opcode = V.getOpcode();
5036 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5037 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5038 int Elt = SV->getMaskElt(Index);
5041 return DAG.getUNDEF(VT.getVectorElementType());
5043 unsigned NumElems = VT.getVectorNumElements();
5044 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5045 : SV->getOperand(1);
5046 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5049 // Recurse into target specific vector shuffles to find scalars.
5050 if (isTargetShuffle(Opcode)) {
5051 MVT ShufVT = V.getSimpleValueType();
5052 unsigned NumElems = ShufVT.getVectorNumElements();
5053 SmallVector<int, 16> ShuffleMask;
5056 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5059 int Elt = ShuffleMask[Index];
5061 return DAG.getUNDEF(ShufVT.getVectorElementType());
5063 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5065 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5069 // Actual nodes that may contain scalar elements
5070 if (Opcode == ISD::BITCAST) {
5071 V = V.getOperand(0);
5072 EVT SrcVT = V.getValueType();
5073 unsigned NumElems = VT.getVectorNumElements();
5075 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5079 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5080 return (Index == 0) ? V.getOperand(0)
5081 : DAG.getUNDEF(VT.getVectorElementType());
5083 if (V.getOpcode() == ISD::BUILD_VECTOR)
5084 return V.getOperand(Index);
5089 /// Custom lower build_vector of v16i8.
5090 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5091 unsigned NumNonZero, unsigned NumZero,
5093 const X86Subtarget* Subtarget,
5094 const TargetLowering &TLI) {
5102 // SSE4.1 - use PINSRB to insert each byte directly.
5103 if (Subtarget->hasSSE41()) {
5104 for (unsigned i = 0; i < 16; ++i) {
5105 bool isNonZero = (NonZeros & (1 << i)) != 0;
5109 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
5111 V = DAG.getUNDEF(MVT::v16i8);
5114 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5115 MVT::v16i8, V, Op.getOperand(i),
5116 DAG.getIntPtrConstant(i, dl));
5123 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5124 for (unsigned i = 0; i < 16; ++i) {
5125 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5126 if (ThisIsNonZero && First) {
5128 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5130 V = DAG.getUNDEF(MVT::v8i16);
5135 SDValue ThisElt, LastElt;
5136 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5137 if (LastIsNonZero) {
5138 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5139 MVT::i16, Op.getOperand(i-1));
5141 if (ThisIsNonZero) {
5142 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5143 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5144 ThisElt, DAG.getConstant(8, dl, MVT::i8));
5146 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5150 if (ThisElt.getNode())
5151 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5152 DAG.getIntPtrConstant(i/2, dl));
5156 return DAG.getBitcast(MVT::v16i8, V);
5159 /// Custom lower build_vector of v8i16.
5160 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5161 unsigned NumNonZero, unsigned NumZero,
5163 const X86Subtarget* Subtarget,
5164 const TargetLowering &TLI) {
5171 for (unsigned i = 0; i < 8; ++i) {
5172 bool isNonZero = (NonZeros & (1 << i)) != 0;
5176 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5178 V = DAG.getUNDEF(MVT::v8i16);
5181 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5182 MVT::v8i16, V, Op.getOperand(i),
5183 DAG.getIntPtrConstant(i, dl));
5190 /// Custom lower build_vector of v4i32 or v4f32.
5191 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5192 const X86Subtarget *Subtarget,
5193 const TargetLowering &TLI) {
5194 // Find all zeroable elements.
5195 std::bitset<4> Zeroable;
5196 for (int i=0; i < 4; ++i) {
5197 SDValue Elt = Op->getOperand(i);
5198 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5200 assert(Zeroable.size() - Zeroable.count() > 1 &&
5201 "We expect at least two non-zero elements!");
5203 // We only know how to deal with build_vector nodes where elements are either
5204 // zeroable or extract_vector_elt with constant index.
5205 SDValue FirstNonZero;
5206 unsigned FirstNonZeroIdx;
5207 for (unsigned i=0; i < 4; ++i) {
5210 SDValue Elt = Op->getOperand(i);
5211 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5212 !isa<ConstantSDNode>(Elt.getOperand(1)))
5214 // Make sure that this node is extracting from a 128-bit vector.
5215 MVT VT = Elt.getOperand(0).getSimpleValueType();
5216 if (!VT.is128BitVector())
5218 if (!FirstNonZero.getNode()) {
5220 FirstNonZeroIdx = i;
5224 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5225 SDValue V1 = FirstNonZero.getOperand(0);
5226 MVT VT = V1.getSimpleValueType();
5228 // See if this build_vector can be lowered as a blend with zero.
5230 unsigned EltMaskIdx, EltIdx;
5232 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5233 if (Zeroable[EltIdx]) {
5234 // The zero vector will be on the right hand side.
5235 Mask[EltIdx] = EltIdx+4;
5239 Elt = Op->getOperand(EltIdx);
5240 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5241 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5242 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5244 Mask[EltIdx] = EltIdx;
5248 // Let the shuffle legalizer deal with blend operations.
5249 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5250 if (V1.getSimpleValueType() != VT)
5251 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5252 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5255 // See if we can lower this build_vector to a INSERTPS.
5256 if (!Subtarget->hasSSE41())
5259 SDValue V2 = Elt.getOperand(0);
5260 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5263 bool CanFold = true;
5264 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5268 SDValue Current = Op->getOperand(i);
5269 SDValue SrcVector = Current->getOperand(0);
5272 CanFold = SrcVector == V1 &&
5273 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5279 assert(V1.getNode() && "Expected at least two non-zero elements!");
5280 if (V1.getSimpleValueType() != MVT::v4f32)
5281 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5282 if (V2.getSimpleValueType() != MVT::v4f32)
5283 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5285 // Ok, we can emit an INSERTPS instruction.
5286 unsigned ZMask = Zeroable.to_ulong();
5288 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5289 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5291 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5292 DAG.getIntPtrConstant(InsertPSMask, DL));
5293 return DAG.getBitcast(VT, Result);
5296 /// Return a vector logical shift node.
5297 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5298 unsigned NumBits, SelectionDAG &DAG,
5299 const TargetLowering &TLI, SDLoc dl) {
5300 assert(VT.is128BitVector() && "Unknown type for VShift");
5301 MVT ShVT = MVT::v2i64;
5302 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5303 SrcOp = DAG.getBitcast(ShVT, SrcOp);
5304 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5305 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5306 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5307 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5311 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5313 // Check if the scalar load can be widened into a vector load. And if
5314 // the address is "base + cst" see if the cst can be "absorbed" into
5315 // the shuffle mask.
5316 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5317 SDValue Ptr = LD->getBasePtr();
5318 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5320 EVT PVT = LD->getValueType(0);
5321 if (PVT != MVT::i32 && PVT != MVT::f32)
5326 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5327 FI = FINode->getIndex();
5329 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5330 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5331 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5332 Offset = Ptr.getConstantOperandVal(1);
5333 Ptr = Ptr.getOperand(0);
5338 // FIXME: 256-bit vector instructions don't require a strict alignment,
5339 // improve this code to support it better.
5340 unsigned RequiredAlign = VT.getSizeInBits()/8;
5341 SDValue Chain = LD->getChain();
5342 // Make sure the stack object alignment is at least 16 or 32.
5343 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5344 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5345 if (MFI->isFixedObjectIndex(FI)) {
5346 // Can't change the alignment. FIXME: It's possible to compute
5347 // the exact stack offset and reference FI + adjust offset instead.
5348 // If someone *really* cares about this. That's the way to implement it.
5351 MFI->setObjectAlignment(FI, RequiredAlign);
5355 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5356 // Ptr + (Offset & ~15).
5359 if ((Offset % RequiredAlign) & 3)
5361 int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5364 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5365 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5368 int EltNo = (Offset - StartOffset) >> 2;
5369 unsigned NumElems = VT.getVectorNumElements();
5371 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5372 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5373 LD->getPointerInfo().getWithOffset(StartOffset),
5374 false, false, false, 0);
5376 SmallVector<int, 8> Mask(NumElems, EltNo);
5378 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5384 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5385 /// elements can be replaced by a single large load which has the same value as
5386 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5388 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5390 /// FIXME: we'd also like to handle the case where the last elements are zero
5391 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5392 /// There's even a handy isZeroNode for that purpose.
5393 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5394 SDLoc &DL, SelectionDAG &DAG,
5395 bool isAfterLegalize) {
5396 unsigned NumElems = Elts.size();
5398 LoadSDNode *LDBase = nullptr;
5399 unsigned LastLoadedElt = -1U;
5401 // For each element in the initializer, see if we've found a load or an undef.
5402 // If we don't find an initial load element, or later load elements are
5403 // non-consecutive, bail out.
5404 for (unsigned i = 0; i < NumElems; ++i) {
5405 SDValue Elt = Elts[i];
5406 // Look through a bitcast.
5407 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5408 Elt = Elt.getOperand(0);
5409 if (!Elt.getNode() ||
5410 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5413 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5415 LDBase = cast<LoadSDNode>(Elt.getNode());
5419 if (Elt.getOpcode() == ISD::UNDEF)
5422 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5423 EVT LdVT = Elt.getValueType();
5424 // Each loaded element must be the correct fractional portion of the
5425 // requested vector load.
5426 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5428 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5433 // If we have found an entire vector of loads and undefs, then return a large
5434 // load of the entire vector width starting at the base pointer. If we found
5435 // consecutive loads for the low half, generate a vzext_load node.
5436 if (LastLoadedElt == NumElems - 1) {
5437 assert(LDBase && "Did not find base load for merging consecutive loads");
5438 EVT EltVT = LDBase->getValueType(0);
5439 // Ensure that the input vector size for the merged loads matches the
5440 // cumulative size of the input elements.
5441 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5444 if (isAfterLegalize &&
5445 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5448 SDValue NewLd = SDValue();
5450 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5451 LDBase->getPointerInfo(), LDBase->isVolatile(),
5452 LDBase->isNonTemporal(), LDBase->isInvariant(),
5453 LDBase->getAlignment());
5455 if (LDBase->hasAnyUseOfValue(1)) {
5456 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5458 SDValue(NewLd.getNode(), 1));
5459 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5460 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5461 SDValue(NewLd.getNode(), 1));
5467 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5468 //of a v4i32 / v4f32. It's probably worth generalizing.
5469 EVT EltVT = VT.getVectorElementType();
5470 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5471 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5472 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5473 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5475 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5476 LDBase->getPointerInfo(),
5477 LDBase->getAlignment(),
5478 false/*isVolatile*/, true/*ReadMem*/,
5481 // Make sure the newly-created LOAD is in the same position as LDBase in
5482 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5483 // update uses of LDBase's output chain to use the TokenFactor.
5484 if (LDBase->hasAnyUseOfValue(1)) {
5485 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5486 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5487 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5488 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5489 SDValue(ResNode.getNode(), 1));
5492 return DAG.getBitcast(VT, ResNode);
5497 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5498 /// to generate a splat value for the following cases:
5499 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5500 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5501 /// a scalar load, or a constant.
5502 /// The VBROADCAST node is returned when a pattern is found,
5503 /// or SDValue() otherwise.
5504 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5505 SelectionDAG &DAG) {
5506 // VBROADCAST requires AVX.
5507 // TODO: Splats could be generated for non-AVX CPUs using SSE
5508 // instructions, but there's less potential gain for only 128-bit vectors.
5509 if (!Subtarget->hasAVX())
5512 MVT VT = Op.getSimpleValueType();
5515 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5516 "Unsupported vector type for broadcast.");
5521 switch (Op.getOpcode()) {
5523 // Unknown pattern found.
5526 case ISD::BUILD_VECTOR: {
5527 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5528 BitVector UndefElements;
5529 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5531 // We need a splat of a single value to use broadcast, and it doesn't
5532 // make any sense if the value is only in one element of the vector.
5533 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5537 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5538 Ld.getOpcode() == ISD::ConstantFP);
5540 // Make sure that all of the users of a non-constant load are from the
5541 // BUILD_VECTOR node.
5542 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5547 case ISD::VECTOR_SHUFFLE: {
5548 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5550 // Shuffles must have a splat mask where the first element is
5552 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5555 SDValue Sc = Op.getOperand(0);
5556 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5557 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5559 if (!Subtarget->hasInt256())
5562 // Use the register form of the broadcast instruction available on AVX2.
5563 if (VT.getSizeInBits() >= 256)
5564 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5565 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5568 Ld = Sc.getOperand(0);
5569 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5570 Ld.getOpcode() == ISD::ConstantFP);
5572 // The scalar_to_vector node and the suspected
5573 // load node must have exactly one user.
5574 // Constants may have multiple users.
5576 // AVX-512 has register version of the broadcast
5577 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5578 Ld.getValueType().getSizeInBits() >= 32;
5579 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5586 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5587 bool IsGE256 = (VT.getSizeInBits() >= 256);
5589 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5590 // instruction to save 8 or more bytes of constant pool data.
5591 // TODO: If multiple splats are generated to load the same constant,
5592 // it may be detrimental to overall size. There needs to be a way to detect
5593 // that condition to know if this is truly a size win.
5594 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5596 // Handle broadcasting a single constant scalar from the constant pool
5598 // On Sandybridge (no AVX2), it is still better to load a constant vector
5599 // from the constant pool and not to broadcast it from a scalar.
5600 // But override that restriction when optimizing for size.
5601 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5602 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5603 EVT CVT = Ld.getValueType();
5604 assert(!CVT.isVector() && "Must not broadcast a vector type");
5606 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5607 // For size optimization, also splat v2f64 and v2i64, and for size opt
5608 // with AVX2, also splat i8 and i16.
5609 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5610 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5611 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5612 const Constant *C = nullptr;
5613 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5614 C = CI->getConstantIntValue();
5615 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5616 C = CF->getConstantFPValue();
5618 assert(C && "Invalid constant type");
5620 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5622 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5623 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5625 CVT, dl, DAG.getEntryNode(), CP,
5626 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5627 false, false, Alignment);
5629 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5633 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5635 // Handle AVX2 in-register broadcasts.
5636 if (!IsLoad && Subtarget->hasInt256() &&
5637 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5638 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5640 // The scalar source must be a normal load.
5644 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5645 (Subtarget->hasVLX() && ScalarSize == 64))
5646 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5648 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5649 // double since there is no vbroadcastsd xmm
5650 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5651 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5652 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5655 // Unsupported broadcast.
5659 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5660 /// underlying vector and index.
5662 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5664 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5666 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5667 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5670 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5672 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5674 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5675 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5678 // In this case the vector is the extract_subvector expression and the index
5679 // is 2, as specified by the shuffle.
5680 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5681 SDValue ShuffleVec = SVOp->getOperand(0);
5682 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5683 assert(ShuffleVecVT.getVectorElementType() ==
5684 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5686 int ShuffleIdx = SVOp->getMaskElt(Idx);
5687 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5688 ExtractedFromVec = ShuffleVec;
5694 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5695 MVT VT = Op.getSimpleValueType();
5697 // Skip if insert_vec_elt is not supported.
5698 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5699 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5703 unsigned NumElems = Op.getNumOperands();
5707 SmallVector<unsigned, 4> InsertIndices;
5708 SmallVector<int, 8> Mask(NumElems, -1);
5710 for (unsigned i = 0; i != NumElems; ++i) {
5711 unsigned Opc = Op.getOperand(i).getOpcode();
5713 if (Opc == ISD::UNDEF)
5716 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5717 // Quit if more than 1 elements need inserting.
5718 if (InsertIndices.size() > 1)
5721 InsertIndices.push_back(i);
5725 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5726 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5727 // Quit if non-constant index.
5728 if (!isa<ConstantSDNode>(ExtIdx))
5730 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5732 // Quit if extracted from vector of different type.
5733 if (ExtractedFromVec.getValueType() != VT)
5736 if (!VecIn1.getNode())
5737 VecIn1 = ExtractedFromVec;
5738 else if (VecIn1 != ExtractedFromVec) {
5739 if (!VecIn2.getNode())
5740 VecIn2 = ExtractedFromVec;
5741 else if (VecIn2 != ExtractedFromVec)
5742 // Quit if more than 2 vectors to shuffle
5746 if (ExtractedFromVec == VecIn1)
5748 else if (ExtractedFromVec == VecIn2)
5749 Mask[i] = Idx + NumElems;
5752 if (!VecIn1.getNode())
5755 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5756 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5757 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5758 unsigned Idx = InsertIndices[i];
5759 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5760 DAG.getIntPtrConstant(Idx, DL));
5766 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5767 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5768 Op.getScalarValueSizeInBits() == 1 &&
5769 "Can not convert non-constant vector");
5770 uint64_t Immediate = 0;
5771 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5772 SDValue In = Op.getOperand(idx);
5773 if (In.getOpcode() != ISD::UNDEF)
5774 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5778 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5779 return DAG.getConstant(Immediate, dl, VT);
5781 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5783 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5785 MVT VT = Op.getSimpleValueType();
5786 assert((VT.getVectorElementType() == MVT::i1) &&
5787 "Unexpected type in LowerBUILD_VECTORvXi1!");
5790 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5791 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5792 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5793 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5796 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5797 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5798 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5799 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5802 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5803 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5804 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5805 return DAG.getBitcast(VT, Imm);
5806 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5807 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5808 DAG.getIntPtrConstant(0, dl));
5811 // Vector has one or more non-const elements
5812 uint64_t Immediate = 0;
5813 SmallVector<unsigned, 16> NonConstIdx;
5814 bool IsSplat = true;
5815 bool HasConstElts = false;
5817 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5818 SDValue In = Op.getOperand(idx);
5819 if (In.getOpcode() == ISD::UNDEF)
5821 if (!isa<ConstantSDNode>(In))
5822 NonConstIdx.push_back(idx);
5824 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5825 HasConstElts = true;
5829 else if (In != Op.getOperand(SplatIdx))
5833 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5835 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5836 DAG.getConstant(1, dl, VT),
5837 DAG.getConstant(0, dl, VT));
5839 // insert elements one by one
5843 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5844 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5846 else if (HasConstElts)
5847 Imm = DAG.getConstant(0, dl, VT);
5849 Imm = DAG.getUNDEF(VT);
5850 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5851 DstVec = DAG.getBitcast(VT, Imm);
5853 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5854 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5855 DAG.getIntPtrConstant(0, dl));
5858 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5859 unsigned InsertIdx = NonConstIdx[i];
5860 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5861 Op.getOperand(InsertIdx),
5862 DAG.getIntPtrConstant(InsertIdx, dl));
5867 /// \brief Return true if \p N implements a horizontal binop and return the
5868 /// operands for the horizontal binop into V0 and V1.
5870 /// This is a helper function of LowerToHorizontalOp().
5871 /// This function checks that the build_vector \p N in input implements a
5872 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5873 /// operation to match.
5874 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5875 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5876 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5879 /// This function only analyzes elements of \p N whose indices are
5880 /// in range [BaseIdx, LastIdx).
5881 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5883 unsigned BaseIdx, unsigned LastIdx,
5884 SDValue &V0, SDValue &V1) {
5885 EVT VT = N->getValueType(0);
5887 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5888 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5889 "Invalid Vector in input!");
5891 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5892 bool CanFold = true;
5893 unsigned ExpectedVExtractIdx = BaseIdx;
5894 unsigned NumElts = LastIdx - BaseIdx;
5895 V0 = DAG.getUNDEF(VT);
5896 V1 = DAG.getUNDEF(VT);
5898 // Check if N implements a horizontal binop.
5899 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5900 SDValue Op = N->getOperand(i + BaseIdx);
5903 if (Op->getOpcode() == ISD::UNDEF) {
5904 // Update the expected vector extract index.
5905 if (i * 2 == NumElts)
5906 ExpectedVExtractIdx = BaseIdx;
5907 ExpectedVExtractIdx += 2;
5911 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5916 SDValue Op0 = Op.getOperand(0);
5917 SDValue Op1 = Op.getOperand(1);
5919 // Try to match the following pattern:
5920 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5921 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5922 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5923 Op0.getOperand(0) == Op1.getOperand(0) &&
5924 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5925 isa<ConstantSDNode>(Op1.getOperand(1)));
5929 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5930 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5932 if (i * 2 < NumElts) {
5933 if (V0.getOpcode() == ISD::UNDEF) {
5934 V0 = Op0.getOperand(0);
5935 if (V0.getValueType() != VT)
5939 if (V1.getOpcode() == ISD::UNDEF) {
5940 V1 = Op0.getOperand(0);
5941 if (V1.getValueType() != VT)
5944 if (i * 2 == NumElts)
5945 ExpectedVExtractIdx = BaseIdx;
5948 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5949 if (I0 == ExpectedVExtractIdx)
5950 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5951 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5952 // Try to match the following dag sequence:
5953 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5954 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5958 ExpectedVExtractIdx += 2;
5964 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5965 /// a concat_vector.
5967 /// This is a helper function of LowerToHorizontalOp().
5968 /// This function expects two 256-bit vectors called V0 and V1.
5969 /// At first, each vector is split into two separate 128-bit vectors.
5970 /// Then, the resulting 128-bit vectors are used to implement two
5971 /// horizontal binary operations.
5973 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5975 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5976 /// the two new horizontal binop.
5977 /// When Mode is set, the first horizontal binop dag node would take as input
5978 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5979 /// horizontal binop dag node would take as input the lower 128-bit of V1
5980 /// and the upper 128-bit of V1.
5982 /// HADD V0_LO, V0_HI
5983 /// HADD V1_LO, V1_HI
5985 /// Otherwise, the first horizontal binop dag node takes as input the lower
5986 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5987 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5989 /// HADD V0_LO, V1_LO
5990 /// HADD V0_HI, V1_HI
5992 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5993 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5994 /// the upper 128-bits of the result.
5995 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5996 SDLoc DL, SelectionDAG &DAG,
5997 unsigned X86Opcode, bool Mode,
5998 bool isUndefLO, bool isUndefHI) {
5999 EVT VT = V0.getValueType();
6000 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6001 "Invalid nodes in input!");
6003 unsigned NumElts = VT.getVectorNumElements();
6004 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6005 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6006 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6007 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6008 EVT NewVT = V0_LO.getValueType();
6010 SDValue LO = DAG.getUNDEF(NewVT);
6011 SDValue HI = DAG.getUNDEF(NewVT);
6014 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6015 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6016 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6017 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6018 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6020 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6021 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6022 V1_LO->getOpcode() != ISD::UNDEF))
6023 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6025 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6026 V1_HI->getOpcode() != ISD::UNDEF))
6027 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6030 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6033 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
6035 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
6036 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6037 MVT VT = BV->getSimpleValueType(0);
6038 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
6039 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
6043 unsigned NumElts = VT.getVectorNumElements();
6044 SDValue InVec0 = DAG.getUNDEF(VT);
6045 SDValue InVec1 = DAG.getUNDEF(VT);
6047 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6048 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6050 // Odd-numbered elements in the input build vector are obtained from
6051 // adding two integer/float elements.
6052 // Even-numbered elements in the input build vector are obtained from
6053 // subtracting two integer/float elements.
6054 unsigned ExpectedOpcode = ISD::FSUB;
6055 unsigned NextExpectedOpcode = ISD::FADD;
6056 bool AddFound = false;
6057 bool SubFound = false;
6059 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6060 SDValue Op = BV->getOperand(i);
6062 // Skip 'undef' values.
6063 unsigned Opcode = Op.getOpcode();
6064 if (Opcode == ISD::UNDEF) {
6065 std::swap(ExpectedOpcode, NextExpectedOpcode);
6069 // Early exit if we found an unexpected opcode.
6070 if (Opcode != ExpectedOpcode)
6073 SDValue Op0 = Op.getOperand(0);
6074 SDValue Op1 = Op.getOperand(1);
6076 // Try to match the following pattern:
6077 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6078 // Early exit if we cannot match that sequence.
6079 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6080 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6081 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6082 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6083 Op0.getOperand(1) != Op1.getOperand(1))
6086 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6090 // We found a valid add/sub node. Update the information accordingly.
6096 // Update InVec0 and InVec1.
6097 if (InVec0.getOpcode() == ISD::UNDEF) {
6098 InVec0 = Op0.getOperand(0);
6099 if (InVec0.getSimpleValueType() != VT)
6102 if (InVec1.getOpcode() == ISD::UNDEF) {
6103 InVec1 = Op1.getOperand(0);
6104 if (InVec1.getSimpleValueType() != VT)
6108 // Make sure that operands in input to each add/sub node always
6109 // come from a same pair of vectors.
6110 if (InVec0 != Op0.getOperand(0)) {
6111 if (ExpectedOpcode == ISD::FSUB)
6114 // FADD is commutable. Try to commute the operands
6115 // and then test again.
6116 std::swap(Op0, Op1);
6117 if (InVec0 != Op0.getOperand(0))
6121 if (InVec1 != Op1.getOperand(0))
6124 // Update the pair of expected opcodes.
6125 std::swap(ExpectedOpcode, NextExpectedOpcode);
6128 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6129 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6130 InVec1.getOpcode() != ISD::UNDEF)
6131 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6136 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6137 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6138 const X86Subtarget *Subtarget,
6139 SelectionDAG &DAG) {
6140 MVT VT = BV->getSimpleValueType(0);
6141 unsigned NumElts = VT.getVectorNumElements();
6142 unsigned NumUndefsLO = 0;
6143 unsigned NumUndefsHI = 0;
6144 unsigned Half = NumElts/2;
6146 // Count the number of UNDEF operands in the build_vector in input.
6147 for (unsigned i = 0, e = Half; i != e; ++i)
6148 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6151 for (unsigned i = Half, e = NumElts; i != e; ++i)
6152 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6155 // Early exit if this is either a build_vector of all UNDEFs or all the
6156 // operands but one are UNDEF.
6157 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6161 SDValue InVec0, InVec1;
6162 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6163 // Try to match an SSE3 float HADD/HSUB.
6164 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6165 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6167 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6168 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6169 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6170 // Try to match an SSSE3 integer HADD/HSUB.
6171 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6172 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6174 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6175 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6178 if (!Subtarget->hasAVX())
6181 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6182 // Try to match an AVX horizontal add/sub of packed single/double
6183 // precision floating point values from 256-bit vectors.
6184 SDValue InVec2, InVec3;
6185 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6186 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6187 ((InVec0.getOpcode() == ISD::UNDEF ||
6188 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6189 ((InVec1.getOpcode() == ISD::UNDEF ||
6190 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6191 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6193 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6194 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6195 ((InVec0.getOpcode() == ISD::UNDEF ||
6196 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6197 ((InVec1.getOpcode() == ISD::UNDEF ||
6198 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6199 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6200 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6201 // Try to match an AVX2 horizontal add/sub of signed integers.
6202 SDValue InVec2, InVec3;
6204 bool CanFold = true;
6206 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6207 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6208 ((InVec0.getOpcode() == ISD::UNDEF ||
6209 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6210 ((InVec1.getOpcode() == ISD::UNDEF ||
6211 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6212 X86Opcode = X86ISD::HADD;
6213 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6214 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6215 ((InVec0.getOpcode() == ISD::UNDEF ||
6216 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6217 ((InVec1.getOpcode() == ISD::UNDEF ||
6218 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6219 X86Opcode = X86ISD::HSUB;
6224 // Fold this build_vector into a single horizontal add/sub.
6225 // Do this only if the target has AVX2.
6226 if (Subtarget->hasAVX2())
6227 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6229 // Do not try to expand this build_vector into a pair of horizontal
6230 // add/sub if we can emit a pair of scalar add/sub.
6231 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6234 // Convert this build_vector into a pair of horizontal binop followed by
6236 bool isUndefLO = NumUndefsLO == Half;
6237 bool isUndefHI = NumUndefsHI == Half;
6238 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6239 isUndefLO, isUndefHI);
6243 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6244 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6246 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6247 X86Opcode = X86ISD::HADD;
6248 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6249 X86Opcode = X86ISD::HSUB;
6250 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6251 X86Opcode = X86ISD::FHADD;
6252 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6253 X86Opcode = X86ISD::FHSUB;
6257 // Don't try to expand this build_vector into a pair of horizontal add/sub
6258 // if we can simply emit a pair of scalar add/sub.
6259 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6262 // Convert this build_vector into two horizontal add/sub followed by
6264 bool isUndefLO = NumUndefsLO == Half;
6265 bool isUndefHI = NumUndefsHI == Half;
6266 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6267 isUndefLO, isUndefHI);
6274 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6277 MVT VT = Op.getSimpleValueType();
6278 MVT ExtVT = VT.getVectorElementType();
6279 unsigned NumElems = Op.getNumOperands();
6281 // Generate vectors for predicate vectors.
6282 if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6283 return LowerBUILD_VECTORvXi1(Op, DAG);
6285 // Vectors containing all zeros can be matched by pxor and xorps later
6286 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6287 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6288 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6289 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6292 return getZeroVector(VT, Subtarget, DAG, dl);
6295 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6296 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6297 // vpcmpeqd on 256-bit vectors.
6298 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6299 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6302 if (!VT.is512BitVector())
6303 return getOnesVector(VT, Subtarget, DAG, dl);
6306 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6307 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6309 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6310 return HorizontalOp;
6311 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6314 unsigned EVTBits = ExtVT.getSizeInBits();
6316 unsigned NumZero = 0;
6317 unsigned NumNonZero = 0;
6318 uint64_t NonZeros = 0;
6319 bool IsAllConstants = true;
6320 SmallSet<SDValue, 8> Values;
6321 for (unsigned i = 0; i < NumElems; ++i) {
6322 SDValue Elt = Op.getOperand(i);
6323 if (Elt.getOpcode() == ISD::UNDEF)
6326 if (Elt.getOpcode() != ISD::Constant &&
6327 Elt.getOpcode() != ISD::ConstantFP)
6328 IsAllConstants = false;
6329 if (X86::isZeroNode(Elt))
6332 assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
6333 NonZeros |= ((uint64_t)1 << i);
6338 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6339 if (NumNonZero == 0)
6340 return DAG.getUNDEF(VT);
6342 // Special case for single non-zero, non-undef, element.
6343 if (NumNonZero == 1) {
6344 unsigned Idx = countTrailingZeros(NonZeros);
6345 SDValue Item = Op.getOperand(Idx);
6347 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6348 // the value are obviously zero, truncate the value to i32 and do the
6349 // insertion that way. Only do this if the value is non-constant or if the
6350 // value is a constant being inserted into element 0. It is cheaper to do
6351 // a constant pool load than it is to do a movd + shuffle.
6352 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6353 (!IsAllConstants || Idx == 0)) {
6354 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6356 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6357 MVT VecVT = MVT::v4i32;
6359 // Truncate the value (which may itself be a constant) to i32, and
6360 // convert it to a vector with movd (S2V+shuffle to zero extend).
6361 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6362 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6363 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6364 Item, Idx * 2, true, Subtarget, DAG));
6368 // If we have a constant or non-constant insertion into the low element of
6369 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6370 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6371 // depending on what the source datatype is.
6374 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6376 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6377 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6378 if (VT.is512BitVector()) {
6379 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6380 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6381 Item, DAG.getIntPtrConstant(0, dl));
6383 assert((VT.is128BitVector() || VT.is256BitVector()) &&
6384 "Expected an SSE value type!");
6385 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6386 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6387 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6390 // We can't directly insert an i8 or i16 into a vector, so zero extend
6392 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6393 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6394 if (VT.is256BitVector()) {
6395 if (Subtarget->hasAVX()) {
6396 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6397 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6399 // Without AVX, we need to extend to a 128-bit vector and then
6400 // insert into the 256-bit vector.
6401 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6402 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6403 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6406 assert(VT.is128BitVector() && "Expected an SSE value type!");
6407 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6408 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6410 return DAG.getBitcast(VT, Item);
6414 // Is it a vector logical left shift?
6415 if (NumElems == 2 && Idx == 1 &&
6416 X86::isZeroNode(Op.getOperand(0)) &&
6417 !X86::isZeroNode(Op.getOperand(1))) {
6418 unsigned NumBits = VT.getSizeInBits();
6419 return getVShift(true, VT,
6420 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6421 VT, Op.getOperand(1)),
6422 NumBits/2, DAG, *this, dl);
6425 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6428 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6429 // is a non-constant being inserted into an element other than the low one,
6430 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6431 // movd/movss) to move this into the low element, then shuffle it into
6433 if (EVTBits == 32) {
6434 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6435 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6439 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6440 if (Values.size() == 1) {
6441 if (EVTBits == 32) {
6442 // Instead of a shuffle like this:
6443 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6444 // Check if it's possible to issue this instead.
6445 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6446 unsigned Idx = countTrailingZeros(NonZeros);
6447 SDValue Item = Op.getOperand(Idx);
6448 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6449 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6454 // A vector full of immediates; various special cases are already
6455 // handled, so this is best done with a single constant-pool load.
6459 // For AVX-length vectors, see if we can use a vector load to get all of the
6460 // elements, otherwise build the individual 128-bit pieces and use
6461 // shuffles to put them in place.
6462 if (VT.is256BitVector() || VT.is512BitVector()) {
6463 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6465 // Check for a build vector of consecutive loads.
6466 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6469 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6471 // Build both the lower and upper subvector.
6472 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6473 makeArrayRef(&V[0], NumElems/2));
6474 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6475 makeArrayRef(&V[NumElems / 2], NumElems/2));
6477 // Recreate the wider vector with the lower and upper part.
6478 if (VT.is256BitVector())
6479 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6480 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6483 // Let legalizer expand 2-wide build_vectors.
6484 if (EVTBits == 64) {
6485 if (NumNonZero == 1) {
6486 // One half is zero or undef.
6487 unsigned Idx = countTrailingZeros(NonZeros);
6488 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6489 Op.getOperand(Idx));
6490 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6495 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6496 if (EVTBits == 8 && NumElems == 16)
6497 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
6498 DAG, Subtarget, *this))
6501 if (EVTBits == 16 && NumElems == 8)
6502 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
6503 DAG, Subtarget, *this))
6506 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6507 if (EVTBits == 32 && NumElems == 4)
6508 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6511 // If element VT is == 32 bits, turn it into a number of shuffles.
6512 SmallVector<SDValue, 8> V(NumElems);
6513 if (NumElems == 4 && NumZero > 0) {
6514 for (unsigned i = 0; i < 4; ++i) {
6515 bool isZero = !(NonZeros & (1ULL << i));
6517 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6519 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6522 for (unsigned i = 0; i < 2; ++i) {
6523 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6526 V[i] = V[i*2]; // Must be a zero vector.
6529 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6532 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6535 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6540 bool Reverse1 = (NonZeros & 0x3) == 2;
6541 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6545 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6546 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6548 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6551 if (Values.size() > 1 && VT.is128BitVector()) {
6552 // Check for a build vector of consecutive loads.
6553 for (unsigned i = 0; i < NumElems; ++i)
6554 V[i] = Op.getOperand(i);
6556 // Check for elements which are consecutive loads.
6557 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6560 // Check for a build vector from mostly shuffle plus few inserting.
6561 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6564 // For SSE 4.1, use insertps to put the high elements into the low element.
6565 if (Subtarget->hasSSE41()) {
6567 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6568 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6570 Result = DAG.getUNDEF(VT);
6572 for (unsigned i = 1; i < NumElems; ++i) {
6573 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6574 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6575 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6580 // Otherwise, expand into a number of unpckl*, start by extending each of
6581 // our (non-undef) elements to the full vector width with the element in the
6582 // bottom slot of the vector (which generates no code for SSE).
6583 for (unsigned i = 0; i < NumElems; ++i) {
6584 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6585 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6587 V[i] = DAG.getUNDEF(VT);
6590 // Next, we iteratively mix elements, e.g. for v4f32:
6591 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6592 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6593 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6594 unsigned EltStride = NumElems >> 1;
6595 while (EltStride != 0) {
6596 for (unsigned i = 0; i < EltStride; ++i) {
6597 // If V[i+EltStride] is undef and this is the first round of mixing,
6598 // then it is safe to just drop this shuffle: V[i] is already in the
6599 // right place, the one element (since it's the first round) being
6600 // inserted as undef can be dropped. This isn't safe for successive
6601 // rounds because they will permute elements within both vectors.
6602 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6603 EltStride == NumElems/2)
6606 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6615 // 256-bit AVX can use the vinsertf128 instruction
6616 // to create 256-bit vectors from two other 128-bit ones.
6617 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6619 MVT ResVT = Op.getSimpleValueType();
6621 assert((ResVT.is256BitVector() ||
6622 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6624 SDValue V1 = Op.getOperand(0);
6625 SDValue V2 = Op.getOperand(1);
6626 unsigned NumElems = ResVT.getVectorNumElements();
6627 if (ResVT.is256BitVector())
6628 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6630 if (Op.getNumOperands() == 4) {
6631 MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6632 ResVT.getVectorNumElements()/2);
6633 SDValue V3 = Op.getOperand(2);
6634 SDValue V4 = Op.getOperand(3);
6635 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6636 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6638 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6641 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6642 const X86Subtarget *Subtarget,
6643 SelectionDAG & DAG) {
6645 MVT ResVT = Op.getSimpleValueType();
6646 unsigned NumOfOperands = Op.getNumOperands();
6648 assert(isPowerOf2_32(NumOfOperands) &&
6649 "Unexpected number of operands in CONCAT_VECTORS");
6651 SDValue Undef = DAG.getUNDEF(ResVT);
6652 if (NumOfOperands > 2) {
6653 // Specialize the cases when all, or all but one, of the operands are undef.
6654 unsigned NumOfDefinedOps = 0;
6656 for (unsigned i = 0; i < NumOfOperands; i++)
6657 if (!Op.getOperand(i).isUndef()) {
6661 if (NumOfDefinedOps == 0)
6663 if (NumOfDefinedOps == 1) {
6664 unsigned SubVecNumElts =
6665 Op.getOperand(OpIdx).getValueType().getVectorNumElements();
6666 SDValue IdxVal = DAG.getIntPtrConstant(SubVecNumElts * OpIdx, dl);
6667 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef,
6668 Op.getOperand(OpIdx), IdxVal);
6671 MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6672 ResVT.getVectorNumElements()/2);
6673 SmallVector<SDValue, 2> Ops;
6674 for (unsigned i = 0; i < NumOfOperands/2; i++)
6675 Ops.push_back(Op.getOperand(i));
6676 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6678 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6679 Ops.push_back(Op.getOperand(i));
6680 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6681 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6685 SDValue V1 = Op.getOperand(0);
6686 SDValue V2 = Op.getOperand(1);
6687 unsigned NumElems = ResVT.getVectorNumElements();
6688 assert(V1.getValueType() == V2.getValueType() &&
6689 V1.getValueType().getVectorNumElements() == NumElems/2 &&
6690 "Unexpected operands in CONCAT_VECTORS");
6692 if (ResVT.getSizeInBits() >= 16)
6693 return Op; // The operation is legal with KUNPCK
6695 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6696 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6697 SDValue ZeroVec = getZeroVector(ResVT, Subtarget, DAG, dl);
6698 if (IsZeroV1 && IsZeroV2)
6701 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6703 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6705 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V1, ZeroIdx);
6707 SDValue IdxVal = DAG.getIntPtrConstant(NumElems/2, dl);
6709 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, IdxVal);
6712 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V2, IdxVal);
6714 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6715 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, V1, V2, IdxVal);
6718 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6719 const X86Subtarget *Subtarget,
6720 SelectionDAG &DAG) {
6721 MVT VT = Op.getSimpleValueType();
6722 if (VT.getVectorElementType() == MVT::i1)
6723 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6725 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6726 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6727 Op.getNumOperands() == 4)));
6729 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6730 // from two other 128-bit ones.
6732 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6733 return LowerAVXCONCAT_VECTORS(Op, DAG);
6736 //===----------------------------------------------------------------------===//
6737 // Vector shuffle lowering
6739 // This is an experimental code path for lowering vector shuffles on x86. It is
6740 // designed to handle arbitrary vector shuffles and blends, gracefully
6741 // degrading performance as necessary. It works hard to recognize idiomatic
6742 // shuffles and lower them to optimal instruction patterns without leaving
6743 // a framework that allows reasonably efficient handling of all vector shuffle
6745 //===----------------------------------------------------------------------===//
6747 /// \brief Tiny helper function to identify a no-op mask.
6749 /// This is a somewhat boring predicate function. It checks whether the mask
6750 /// array input, which is assumed to be a single-input shuffle mask of the kind
6751 /// used by the X86 shuffle instructions (not a fully general
6752 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6753 /// in-place shuffle are 'no-op's.
6754 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6755 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6756 if (Mask[i] != -1 && Mask[i] != i)
6761 /// \brief Helper function to classify a mask as a single-input mask.
6763 /// This isn't a generic single-input test because in the vector shuffle
6764 /// lowering we canonicalize single inputs to be the first input operand. This
6765 /// means we can more quickly test for a single input by only checking whether
6766 /// an input from the second operand exists. We also assume that the size of
6767 /// mask corresponds to the size of the input vectors which isn't true in the
6768 /// fully general case.
6769 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6771 if (M >= (int)Mask.size())
6776 /// \brief Test whether there are elements crossing 128-bit lanes in this
6779 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6780 /// and we routinely test for these.
6781 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6782 int LaneSize = 128 / VT.getScalarSizeInBits();
6783 int Size = Mask.size();
6784 for (int i = 0; i < Size; ++i)
6785 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6790 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6792 /// This checks a shuffle mask to see if it is performing the same
6793 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6794 /// that it is also not lane-crossing. It may however involve a blend from the
6795 /// same lane of a second vector.
6797 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6798 /// non-trivial to compute in the face of undef lanes. The representation is
6799 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6800 /// entries from both V1 and V2 inputs to the wider mask.
6802 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6803 SmallVectorImpl<int> &RepeatedMask) {
6804 int LaneSize = 128 / VT.getScalarSizeInBits();
6805 RepeatedMask.resize(LaneSize, -1);
6806 int Size = Mask.size();
6807 for (int i = 0; i < Size; ++i) {
6810 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6811 // This entry crosses lanes, so there is no way to model this shuffle.
6814 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6815 if (RepeatedMask[i % LaneSize] == -1)
6816 // This is the first non-undef entry in this slot of a 128-bit lane.
6817 RepeatedMask[i % LaneSize] =
6818 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6819 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6820 // Found a mismatch with the repeated mask.
6826 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6829 /// This is a fast way to test a shuffle mask against a fixed pattern:
6831 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6833 /// It returns true if the mask is exactly as wide as the argument list, and
6834 /// each element of the mask is either -1 (signifying undef) or the value given
6835 /// in the argument.
6836 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6837 ArrayRef<int> ExpectedMask) {
6838 if (Mask.size() != ExpectedMask.size())
6841 int Size = Mask.size();
6843 // If the values are build vectors, we can look through them to find
6844 // equivalent inputs that make the shuffles equivalent.
6845 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6846 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6848 for (int i = 0; i < Size; ++i)
6849 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6850 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6851 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6852 if (!MaskBV || !ExpectedBV ||
6853 MaskBV->getOperand(Mask[i] % Size) !=
6854 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6861 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6863 /// This helper function produces an 8-bit shuffle immediate corresponding to
6864 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6865 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6868 /// NB: We rely heavily on "undef" masks preserving the input lane.
6869 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6870 SelectionDAG &DAG) {
6871 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6872 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6873 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6874 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6875 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6878 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6879 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6880 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6881 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6882 return DAG.getConstant(Imm, DL, MVT::i8);
6885 /// \brief Compute whether each element of a shuffle is zeroable.
6887 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6888 /// Either it is an undef element in the shuffle mask, the element of the input
6889 /// referenced is undef, or the element of the input referenced is known to be
6890 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6891 /// as many lanes with this technique as possible to simplify the remaining
6893 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6894 SDValue V1, SDValue V2) {
6895 SmallBitVector Zeroable(Mask.size(), false);
6897 while (V1.getOpcode() == ISD::BITCAST)
6898 V1 = V1->getOperand(0);
6899 while (V2.getOpcode() == ISD::BITCAST)
6900 V2 = V2->getOperand(0);
6902 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6903 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6905 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6907 // Handle the easy cases.
6908 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6913 // If this is an index into a build_vector node (which has the same number
6914 // of elements), dig out the input value and use it.
6915 SDValue V = M < Size ? V1 : V2;
6916 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6919 SDValue Input = V.getOperand(M % Size);
6920 // The UNDEF opcode check really should be dead code here, but not quite
6921 // worth asserting on (it isn't invalid, just unexpected).
6922 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6929 // X86 has dedicated unpack instructions that can handle specific blend
6930 // operations: UNPCKH and UNPCKL.
6931 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6932 SDValue V1, SDValue V2,
6933 SelectionDAG &DAG) {
6934 int NumElts = VT.getVectorNumElements();
6935 int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6936 SmallVector<int, 8> Unpckl;
6937 SmallVector<int, 8> Unpckh;
6939 for (int i = 0; i < NumElts; ++i) {
6940 unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6941 int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6942 int HiPos = LoPos + NumEltsInLane / 2;
6943 Unpckl.push_back(LoPos);
6944 Unpckh.push_back(HiPos);
6947 if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6948 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6949 if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6950 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6952 // Commute and try again.
6953 ShuffleVectorSDNode::commuteMask(Unpckl);
6954 if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6955 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6957 ShuffleVectorSDNode::commuteMask(Unpckh);
6958 if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6959 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6964 /// \brief Try to emit a bitmask instruction for a shuffle.
6966 /// This handles cases where we can model a blend exactly as a bitmask due to
6967 /// one of the inputs being zeroable.
6968 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6969 SDValue V2, ArrayRef<int> Mask,
6970 SelectionDAG &DAG) {
6971 MVT EltVT = VT.getVectorElementType();
6972 int NumEltBits = EltVT.getSizeInBits();
6973 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6974 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6975 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6977 if (EltVT.isFloatingPoint()) {
6978 Zero = DAG.getBitcast(EltVT, Zero);
6979 AllOnes = DAG.getBitcast(EltVT, AllOnes);
6981 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6982 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6984 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6987 if (Mask[i] % Size != i)
6988 return SDValue(); // Not a blend.
6990 V = Mask[i] < Size ? V1 : V2;
6991 else if (V != (Mask[i] < Size ? V1 : V2))
6992 return SDValue(); // Can only let one input through the mask.
6994 VMaskOps[i] = AllOnes;
6997 return SDValue(); // No non-zeroable elements!
6999 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
7000 V = DAG.getNode(VT.isFloatingPoint()
7001 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
7006 /// \brief Try to emit a blend instruction for a shuffle using bit math.
7008 /// This is used as a fallback approach when first class blend instructions are
7009 /// unavailable. Currently it is only suitable for integer vectors, but could
7010 /// be generalized for floating point vectors if desirable.
7011 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
7012 SDValue V2, ArrayRef<int> Mask,
7013 SelectionDAG &DAG) {
7014 assert(VT.isInteger() && "Only supports integer vector types!");
7015 MVT EltVT = VT.getVectorElementType();
7016 int NumEltBits = EltVT.getSizeInBits();
7017 SDValue Zero = DAG.getConstant(0, DL, EltVT);
7018 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7020 SmallVector<SDValue, 16> MaskOps;
7021 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7022 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
7023 return SDValue(); // Shuffled input!
7024 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
7027 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
7028 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
7029 // We have to cast V2 around.
7030 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
7031 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
7032 DAG.getBitcast(MaskVT, V1Mask),
7033 DAG.getBitcast(MaskVT, V2)));
7034 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
7037 /// \brief Try to emit a blend instruction for a shuffle.
7039 /// This doesn't do any checks for the availability of instructions for blending
7040 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7041 /// be matched in the backend with the type given. What it does check for is
7042 /// that the shuffle mask is a blend, or convertible into a blend with zero.
7043 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7044 SDValue V2, ArrayRef<int> Original,
7045 const X86Subtarget *Subtarget,
7046 SelectionDAG &DAG) {
7047 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7048 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7049 SmallVector<int, 8> Mask(Original.begin(), Original.end());
7050 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7051 bool ForceV1Zero = false, ForceV2Zero = false;
7053 // Attempt to generate the binary blend mask. If an input is zero then
7054 // we can use any lane.
7055 // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
7056 unsigned BlendMask = 0;
7057 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7063 if (M == i + Size) {
7064 BlendMask |= 1u << i;
7075 BlendMask |= 1u << i;
7080 return SDValue(); // Shuffled input!
7083 // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
7085 V1 = getZeroVector(VT, Subtarget, DAG, DL);
7087 V2 = getZeroVector(VT, Subtarget, DAG, DL);
7089 auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
7090 unsigned ScaledMask = 0;
7091 for (int i = 0; i != Size; ++i)
7092 if (BlendMask & (1u << i))
7093 for (int j = 0; j != Scale; ++j)
7094 ScaledMask |= 1u << (i * Scale + j);
7098 switch (VT.SimpleTy) {
7103 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7104 DAG.getConstant(BlendMask, DL, MVT::i8));
7108 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7112 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7113 // that instruction.
7114 if (Subtarget->hasAVX2()) {
7115 // Scale the blend by the number of 32-bit dwords per element.
7116 int Scale = VT.getScalarSizeInBits() / 32;
7117 BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7118 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7119 V1 = DAG.getBitcast(BlendVT, V1);
7120 V2 = DAG.getBitcast(BlendVT, V2);
7121 return DAG.getBitcast(
7122 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7123 DAG.getConstant(BlendMask, DL, MVT::i8)));
7127 // For integer shuffles we need to expand the mask and cast the inputs to
7128 // v8i16s prior to blending.
7129 int Scale = 8 / VT.getVectorNumElements();
7130 BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7131 V1 = DAG.getBitcast(MVT::v8i16, V1);
7132 V2 = DAG.getBitcast(MVT::v8i16, V2);
7133 return DAG.getBitcast(VT,
7134 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7135 DAG.getConstant(BlendMask, DL, MVT::i8)));
7139 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7140 SmallVector<int, 8> RepeatedMask;
7141 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7142 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7143 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7145 for (int i = 0; i < 8; ++i)
7146 if (RepeatedMask[i] >= 16)
7147 BlendMask |= 1u << i;
7148 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7149 DAG.getConstant(BlendMask, DL, MVT::i8));
7155 assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
7156 "256-bit byte-blends require AVX2 support!");
7158 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
7159 if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
7162 // Scale the blend by the number of bytes per element.
7163 int Scale = VT.getScalarSizeInBits() / 8;
7165 // This form of blend is always done on bytes. Compute the byte vector
7167 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
7169 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7170 // mix of LLVM's code generator and the x86 backend. We tell the code
7171 // generator that boolean values in the elements of an x86 vector register
7172 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7173 // mapping a select to operand #1, and 'false' mapping to operand #2. The
7174 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7175 // of the element (the remaining are ignored) and 0 in that high bit would
7176 // mean operand #1 while 1 in the high bit would mean operand #2. So while
7177 // the LLVM model for boolean values in vector elements gets the relevant
7178 // bit set, it is set backwards and over constrained relative to x86's
7180 SmallVector<SDValue, 32> VSELECTMask;
7181 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7182 for (int j = 0; j < Scale; ++j)
7183 VSELECTMask.push_back(
7184 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7185 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7188 V1 = DAG.getBitcast(BlendVT, V1);
7189 V2 = DAG.getBitcast(BlendVT, V2);
7190 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7191 DAG.getNode(ISD::BUILD_VECTOR, DL,
7192 BlendVT, VSELECTMask),
7197 llvm_unreachable("Not a supported integer vector type!");
7201 /// \brief Try to lower as a blend of elements from two inputs followed by
7202 /// a single-input permutation.
7204 /// This matches the pattern where we can blend elements from two inputs and
7205 /// then reduce the shuffle to a single-input permutation.
7206 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7209 SelectionDAG &DAG) {
7210 // We build up the blend mask while checking whether a blend is a viable way
7211 // to reduce the shuffle.
7212 SmallVector<int, 32> BlendMask(Mask.size(), -1);
7213 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7215 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7219 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7221 if (BlendMask[Mask[i] % Size] == -1)
7222 BlendMask[Mask[i] % Size] = Mask[i];
7223 else if (BlendMask[Mask[i] % Size] != Mask[i])
7224 return SDValue(); // Can't blend in the needed input!
7226 PermuteMask[i] = Mask[i] % Size;
7229 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7230 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7233 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7234 /// blends and permutes.
7236 /// This matches the extremely common pattern for handling combined
7237 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7238 /// operations. It will try to pick the best arrangement of shuffles and
7240 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7244 SelectionDAG &DAG) {
7245 // Shuffle the input elements into the desired positions in V1 and V2 and
7246 // blend them together.
7247 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7248 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7249 SmallVector<int, 32> BlendMask(Mask.size(), -1);
7250 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7251 if (Mask[i] >= 0 && Mask[i] < Size) {
7252 V1Mask[i] = Mask[i];
7254 } else if (Mask[i] >= Size) {
7255 V2Mask[i] = Mask[i] - Size;
7256 BlendMask[i] = i + Size;
7259 // Try to lower with the simpler initial blend strategy unless one of the
7260 // input shuffles would be a no-op. We prefer to shuffle inputs as the
7261 // shuffle may be able to fold with a load or other benefit. However, when
7262 // we'll have to do 2x as many shuffles in order to achieve this, blending
7263 // first is a better strategy.
7264 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7265 if (SDValue BlendPerm =
7266 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7269 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7270 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7271 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7274 /// \brief Try to lower a vector shuffle as a byte rotation.
7276 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7277 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7278 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7279 /// try to generically lower a vector shuffle through such an pattern. It
7280 /// does not check for the profitability of lowering either as PALIGNR or
7281 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7282 /// This matches shuffle vectors that look like:
7284 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7286 /// Essentially it concatenates V1 and V2, shifts right by some number of
7287 /// elements, and takes the low elements as the result. Note that while this is
7288 /// specified as a *right shift* because x86 is little-endian, it is a *left
7289 /// rotate* of the vector lanes.
7290 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7293 const X86Subtarget *Subtarget,
7294 SelectionDAG &DAG) {
7295 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7297 int NumElts = Mask.size();
7298 int NumLanes = VT.getSizeInBits() / 128;
7299 int NumLaneElts = NumElts / NumLanes;
7301 // We need to detect various ways of spelling a rotation:
7302 // [11, 12, 13, 14, 15, 0, 1, 2]
7303 // [-1, 12, 13, 14, -1, -1, 1, -1]
7304 // [-1, -1, -1, -1, -1, -1, 1, 2]
7305 // [ 3, 4, 5, 6, 7, 8, 9, 10]
7306 // [-1, 4, 5, 6, -1, -1, 9, -1]
7307 // [-1, 4, 5, 6, -1, -1, -1, -1]
7310 for (int l = 0; l < NumElts; l += NumLaneElts) {
7311 for (int i = 0; i < NumLaneElts; ++i) {
7312 if (Mask[l + i] == -1)
7314 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7316 // Get the mod-Size index and lane correct it.
7317 int LaneIdx = (Mask[l + i] % NumElts) - l;
7318 // Make sure it was in this lane.
7319 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7322 // Determine where a rotated vector would have started.
7323 int StartIdx = i - LaneIdx;
7325 // The identity rotation isn't interesting, stop.
7328 // If we found the tail of a vector the rotation must be the missing
7329 // front. If we found the head of a vector, it must be how much of the
7331 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7334 Rotation = CandidateRotation;
7335 else if (Rotation != CandidateRotation)
7336 // The rotations don't match, so we can't match this mask.
7339 // Compute which value this mask is pointing at.
7340 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7342 // Compute which of the two target values this index should be assigned
7343 // to. This reflects whether the high elements are remaining or the low
7344 // elements are remaining.
7345 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7347 // Either set up this value if we've not encountered it before, or check
7348 // that it remains consistent.
7351 else if (TargetV != MaskV)
7352 // This may be a rotation, but it pulls from the inputs in some
7353 // unsupported interleaving.
7358 // Check that we successfully analyzed the mask, and normalize the results.
7359 assert(Rotation != 0 && "Failed to locate a viable rotation!");
7360 assert((Lo || Hi) && "Failed to find a rotated input vector!");
7366 // The actual rotate instruction rotates bytes, so we need to scale the
7367 // rotation based on how many bytes are in the vector lane.
7368 int Scale = 16 / NumLaneElts;
7370 // SSSE3 targets can use the palignr instruction.
7371 if (Subtarget->hasSSSE3()) {
7372 // Cast the inputs to i8 vector of correct length to match PALIGNR.
7373 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7374 Lo = DAG.getBitcast(AlignVT, Lo);
7375 Hi = DAG.getBitcast(AlignVT, Hi);
7377 return DAG.getBitcast(
7378 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7379 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7382 assert(VT.is128BitVector() &&
7383 "Rotate-based lowering only supports 128-bit lowering!");
7384 assert(Mask.size() <= 16 &&
7385 "Can shuffle at most 16 bytes in a 128-bit vector!");
7387 // Default SSE2 implementation
7388 int LoByteShift = 16 - Rotation * Scale;
7389 int HiByteShift = Rotation * Scale;
7391 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7392 Lo = DAG.getBitcast(MVT::v2i64, Lo);
7393 Hi = DAG.getBitcast(MVT::v2i64, Hi);
7395 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7396 DAG.getConstant(LoByteShift, DL, MVT::i8));
7397 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7398 DAG.getConstant(HiByteShift, DL, MVT::i8));
7399 return DAG.getBitcast(VT,
7400 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7403 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7405 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7406 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7407 /// matches elements from one of the input vectors shuffled to the left or
7408 /// right with zeroable elements 'shifted in'. It handles both the strictly
7409 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7412 /// PSHL : (little-endian) left bit shift.
7413 /// [ zz, 0, zz, 2 ]
7414 /// [ -1, 4, zz, -1 ]
7415 /// PSRL : (little-endian) right bit shift.
7417 /// [ -1, -1, 7, zz]
7418 /// PSLLDQ : (little-endian) left byte shift
7419 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
7420 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
7421 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
7422 /// PSRLDQ : (little-endian) right byte shift
7423 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
7424 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
7425 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
7426 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7427 SDValue V2, ArrayRef<int> Mask,
7428 SelectionDAG &DAG) {
7429 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7431 int Size = Mask.size();
7432 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7434 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7435 for (int i = 0; i < Size; i += Scale)
7436 for (int j = 0; j < Shift; ++j)
7437 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7443 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7444 for (int i = 0; i != Size; i += Scale) {
7445 unsigned Pos = Left ? i + Shift : i;
7446 unsigned Low = Left ? i : i + Shift;
7447 unsigned Len = Scale - Shift;
7448 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7449 Low + (V == V1 ? 0 : Size)))
7453 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7454 bool ByteShift = ShiftEltBits > 64;
7455 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7456 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7457 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7459 // Normalize the scale for byte shifts to still produce an i64 element
7461 Scale = ByteShift ? Scale / 2 : Scale;
7463 // We need to round trip through the appropriate type for the shift.
7464 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7465 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7466 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7467 "Illegal integer vector type");
7468 V = DAG.getBitcast(ShiftVT, V);
7470 V = DAG.getNode(OpCode, DL, ShiftVT, V,
7471 DAG.getConstant(ShiftAmt, DL, MVT::i8));
7472 return DAG.getBitcast(VT, V);
7475 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7476 // keep doubling the size of the integer elements up to that. We can
7477 // then shift the elements of the integer vector by whole multiples of
7478 // their width within the elements of the larger integer vector. Test each
7479 // multiple to see if we can find a match with the moved element indices
7480 // and that the shifted in elements are all zeroable.
7481 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7482 for (int Shift = 1; Shift != Scale; ++Shift)
7483 for (bool Left : {true, false})
7484 if (CheckZeros(Shift, Scale, Left))
7485 for (SDValue V : {V1, V2})
7486 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7493 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7494 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7495 SDValue V2, ArrayRef<int> Mask,
7496 SelectionDAG &DAG) {
7497 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7498 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7500 int Size = Mask.size();
7501 int HalfSize = Size / 2;
7502 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7504 // Upper half must be undefined.
7505 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7508 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7509 // Remainder of lower half result is zero and upper half is all undef.
7510 auto LowerAsEXTRQ = [&]() {
7511 // Determine the extraction length from the part of the
7512 // lower half that isn't zeroable.
7514 for (; Len > 0; --Len)
7515 if (!Zeroable[Len - 1])
7517 assert(Len > 0 && "Zeroable shuffle mask");
7519 // Attempt to match first Len sequential elements from the lower half.
7522 for (int i = 0; i != Len; ++i) {
7526 SDValue &V = (M < Size ? V1 : V2);
7529 // The extracted elements must start at a valid index and all mask
7530 // elements must be in the lower half.
7531 if (i > M || M >= HalfSize)
7534 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7545 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7546 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7547 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7548 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7549 DAG.getConstant(BitLen, DL, MVT::i8),
7550 DAG.getConstant(BitIdx, DL, MVT::i8));
7553 if (SDValue ExtrQ = LowerAsEXTRQ())
7556 // INSERTQ: Extract lowest Len elements from lower half of second source and
7557 // insert over first source, starting at Idx.
7558 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7559 auto LowerAsInsertQ = [&]() {
7560 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7563 // Attempt to match first source from mask before insertion point.
7564 if (isUndefInRange(Mask, 0, Idx)) {
7566 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7568 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7574 // Extend the extraction length looking to match both the insertion of
7575 // the second source and the remaining elements of the first.
7576 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7581 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7583 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7589 // Match the remaining elements of the lower half.
7590 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7592 } else if ((!Base || (Base == V1)) &&
7593 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7595 } else if ((!Base || (Base == V2)) &&
7596 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7603 // We may not have a base (first source) - this can safely be undefined.
7605 Base = DAG.getUNDEF(VT);
7607 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7608 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7609 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7610 DAG.getConstant(BitLen, DL, MVT::i8),
7611 DAG.getConstant(BitIdx, DL, MVT::i8));
7618 if (SDValue InsertQ = LowerAsInsertQ())
7624 /// \brief Lower a vector shuffle as a zero or any extension.
7626 /// Given a specific number of elements, element bit width, and extension
7627 /// stride, produce either a zero or any extension based on the available
7628 /// features of the subtarget. The extended elements are consecutive and
7629 /// begin and can start from an offseted element index in the input; to
7630 /// avoid excess shuffling the offset must either being in the bottom lane
7631 /// or at the start of a higher lane. All extended elements must be from
7633 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7634 SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7635 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7636 assert(Scale > 1 && "Need a scale to extend.");
7637 int EltBits = VT.getScalarSizeInBits();
7638 int NumElements = VT.getVectorNumElements();
7639 int NumEltsPerLane = 128 / EltBits;
7640 int OffsetLane = Offset / NumEltsPerLane;
7641 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7642 "Only 8, 16, and 32 bit elements can be extended.");
7643 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7644 assert(0 <= Offset && "Extension offset must be positive.");
7645 assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7646 "Extension offset must be in the first lane or start an upper lane.");
7648 // Check that an index is in same lane as the base offset.
7649 auto SafeOffset = [&](int Idx) {
7650 return OffsetLane == (Idx / NumEltsPerLane);
7653 // Shift along an input so that the offset base moves to the first element.
7654 auto ShuffleOffset = [&](SDValue V) {
7658 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7659 for (int i = 0; i * Scale < NumElements; ++i) {
7660 int SrcIdx = i + Offset;
7661 ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7663 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7666 // Found a valid zext mask! Try various lowering strategies based on the
7667 // input type and available ISA extensions.
7668 if (Subtarget->hasSSE41()) {
7669 // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7670 // PUNPCK will catch this in a later shuffle match.
7671 if (Offset && Scale == 2 && VT.is128BitVector())
7673 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7674 NumElements / Scale);
7675 InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7676 return DAG.getBitcast(VT, InputV);
7679 assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7681 // For any extends we can cheat for larger element sizes and use shuffle
7682 // instructions that can fold with a load and/or copy.
7683 if (AnyExt && EltBits == 32) {
7684 int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7686 return DAG.getBitcast(
7687 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7688 DAG.getBitcast(MVT::v4i32, InputV),
7689 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7691 if (AnyExt && EltBits == 16 && Scale > 2) {
7692 int PSHUFDMask[4] = {Offset / 2, -1,
7693 SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7694 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7695 DAG.getBitcast(MVT::v4i32, InputV),
7696 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7697 int PSHUFWMask[4] = {1, -1, -1, -1};
7698 unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7699 return DAG.getBitcast(
7700 VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7701 DAG.getBitcast(MVT::v8i16, InputV),
7702 getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7705 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7707 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7708 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7709 assert(VT.is128BitVector() && "Unexpected vector width!");
7711 int LoIdx = Offset * EltBits;
7712 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7713 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7714 DAG.getConstant(EltBits, DL, MVT::i8),
7715 DAG.getConstant(LoIdx, DL, MVT::i8)));
7717 if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7718 !SafeOffset(Offset + 1))
7719 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7721 int HiIdx = (Offset + 1) * EltBits;
7722 SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7723 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7724 DAG.getConstant(EltBits, DL, MVT::i8),
7725 DAG.getConstant(HiIdx, DL, MVT::i8)));
7726 return DAG.getNode(ISD::BITCAST, DL, VT,
7727 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7730 // If this would require more than 2 unpack instructions to expand, use
7731 // pshufb when available. We can only use more than 2 unpack instructions
7732 // when zero extending i8 elements which also makes it easier to use pshufb.
7733 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7734 assert(NumElements == 16 && "Unexpected byte vector width!");
7735 SDValue PSHUFBMask[16];
7736 for (int i = 0; i < 16; ++i) {
7737 int Idx = Offset + (i / Scale);
7738 PSHUFBMask[i] = DAG.getConstant(
7739 (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7741 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7742 return DAG.getBitcast(VT,
7743 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7744 DAG.getNode(ISD::BUILD_VECTOR, DL,
7745 MVT::v16i8, PSHUFBMask)));
7748 // If we are extending from an offset, ensure we start on a boundary that
7749 // we can unpack from.
7750 int AlignToUnpack = Offset % (NumElements / Scale);
7751 if (AlignToUnpack) {
7752 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7753 for (int i = AlignToUnpack; i < NumElements; ++i)
7754 ShMask[i - AlignToUnpack] = i;
7755 InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7756 Offset -= AlignToUnpack;
7759 // Otherwise emit a sequence of unpacks.
7761 unsigned UnpackLoHi = X86ISD::UNPCKL;
7762 if (Offset >= (NumElements / 2)) {
7763 UnpackLoHi = X86ISD::UNPCKH;
7764 Offset -= (NumElements / 2);
7767 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7768 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7769 : getZeroVector(InputVT, Subtarget, DAG, DL);
7770 InputV = DAG.getBitcast(InputVT, InputV);
7771 InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7775 } while (Scale > 1);
7776 return DAG.getBitcast(VT, InputV);
7779 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7781 /// This routine will try to do everything in its power to cleverly lower
7782 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7783 /// check for the profitability of this lowering, it tries to aggressively
7784 /// match this pattern. It will use all of the micro-architectural details it
7785 /// can to emit an efficient lowering. It handles both blends with all-zero
7786 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7787 /// masking out later).
7789 /// The reason we have dedicated lowering for zext-style shuffles is that they
7790 /// are both incredibly common and often quite performance sensitive.
7791 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7792 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7793 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7794 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7796 int Bits = VT.getSizeInBits();
7797 int NumLanes = Bits / 128;
7798 int NumElements = VT.getVectorNumElements();
7799 int NumEltsPerLane = NumElements / NumLanes;
7800 assert(VT.getScalarSizeInBits() <= 32 &&
7801 "Exceeds 32-bit integer zero extension limit");
7802 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7804 // Define a helper function to check a particular ext-scale and lower to it if
7806 auto Lower = [&](int Scale) -> SDValue {
7811 for (int i = 0; i < NumElements; ++i) {
7814 continue; // Valid anywhere but doesn't tell us anything.
7815 if (i % Scale != 0) {
7816 // Each of the extended elements need to be zeroable.
7820 // We no longer are in the anyext case.
7825 // Each of the base elements needs to be consecutive indices into the
7826 // same input vector.
7827 SDValue V = M < NumElements ? V1 : V2;
7828 M = M % NumElements;
7831 Offset = M - (i / Scale);
7832 } else if (InputV != V)
7833 return SDValue(); // Flip-flopping inputs.
7835 // Offset must start in the lowest 128-bit lane or at the start of an
7837 // FIXME: Is it ever worth allowing a negative base offset?
7838 if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7839 (Offset % NumEltsPerLane) == 0))
7842 // If we are offsetting, all referenced entries must come from the same
7844 if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7847 if ((M % NumElements) != (Offset + (i / Scale)))
7848 return SDValue(); // Non-consecutive strided elements.
7852 // If we fail to find an input, we have a zero-shuffle which should always
7853 // have already been handled.
7854 // FIXME: Maybe handle this here in case during blending we end up with one?
7858 // If we are offsetting, don't extend if we only match a single input, we
7859 // can always do better by using a basic PSHUF or PUNPCK.
7860 if (Offset != 0 && Matches < 2)
7863 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7864 DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7867 // The widest scale possible for extending is to a 64-bit integer.
7868 assert(Bits % 64 == 0 &&
7869 "The number of bits in a vector must be divisible by 64 on x86!");
7870 int NumExtElements = Bits / 64;
7872 // Each iteration, try extending the elements half as much, but into twice as
7874 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7875 assert(NumElements % NumExtElements == 0 &&
7876 "The input vector size must be divisible by the extended size.");
7877 if (SDValue V = Lower(NumElements / NumExtElements))
7881 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7885 // Returns one of the source operands if the shuffle can be reduced to a
7886 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7887 auto CanZExtLowHalf = [&]() {
7888 for (int i = NumElements / 2; i != NumElements; ++i)
7891 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7893 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7898 if (SDValue V = CanZExtLowHalf()) {
7899 V = DAG.getBitcast(MVT::v2i64, V);
7900 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7901 return DAG.getBitcast(VT, V);
7904 // No viable ext lowering found.
7908 /// \brief Try to get a scalar value for a specific element of a vector.
7910 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7911 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7912 SelectionDAG &DAG) {
7913 MVT VT = V.getSimpleValueType();
7914 MVT EltVT = VT.getVectorElementType();
7915 while (V.getOpcode() == ISD::BITCAST)
7916 V = V.getOperand(0);
7917 // If the bitcasts shift the element size, we can't extract an equivalent
7919 MVT NewVT = V.getSimpleValueType();
7920 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7923 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7924 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7925 // Ensure the scalar operand is the same size as the destination.
7926 // FIXME: Add support for scalar truncation where possible.
7927 SDValue S = V.getOperand(Idx);
7928 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7929 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7935 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7937 /// This is particularly important because the set of instructions varies
7938 /// significantly based on whether the operand is a load or not.
7939 static bool isShuffleFoldableLoad(SDValue V) {
7940 while (V.getOpcode() == ISD::BITCAST)
7941 V = V.getOperand(0);
7943 return ISD::isNON_EXTLoad(V.getNode());
7946 /// \brief Try to lower insertion of a single element into a zero vector.
7948 /// This is a common pattern that we have especially efficient patterns to lower
7949 /// across all subtarget feature sets.
7950 static SDValue lowerVectorShuffleAsElementInsertion(
7951 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7952 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7953 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7955 MVT EltVT = VT.getVectorElementType();
7957 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7958 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7960 bool IsV1Zeroable = true;
7961 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7962 if (i != V2Index && !Zeroable[i]) {
7963 IsV1Zeroable = false;
7967 // Check for a single input from a SCALAR_TO_VECTOR node.
7968 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7969 // all the smarts here sunk into that routine. However, the current
7970 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7971 // vector shuffle lowering is dead.
7972 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7974 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7975 // We need to zext the scalar if it is smaller than an i32.
7976 V2S = DAG.getBitcast(EltVT, V2S);
7977 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7978 // Using zext to expand a narrow element won't work for non-zero
7983 // Zero-extend directly to i32.
7985 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7987 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7988 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7989 EltVT == MVT::i16) {
7990 // Either not inserting from the low element of the input or the input
7991 // element size is too small to use VZEXT_MOVL to clear the high bits.
7995 if (!IsV1Zeroable) {
7996 // If V1 can't be treated as a zero vector we have fewer options to lower
7997 // this. We can't support integer vectors or non-zero targets cheaply, and
7998 // the V1 elements can't be permuted in any way.
7999 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
8000 if (!VT.isFloatingPoint() || V2Index != 0)
8002 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8003 V1Mask[V2Index] = -1;
8004 if (!isNoopShuffleMask(V1Mask))
8006 // This is essentially a special case blend operation, but if we have
8007 // general purpose blend operations, they are always faster. Bail and let
8008 // the rest of the lowering handle these as blends.
8009 if (Subtarget->hasSSE41())
8012 // Otherwise, use MOVSD or MOVSS.
8013 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8014 "Only two types of floating point element types to handle!");
8015 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8019 // This lowering only works for the low element with floating point vectors.
8020 if (VT.isFloatingPoint() && V2Index != 0)
8023 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8025 V2 = DAG.getBitcast(VT, V2);
8028 // If we have 4 or fewer lanes we can cheaply shuffle the element into
8029 // the desired position. Otherwise it is more efficient to do a vector
8030 // shift left. We know that we can do a vector shift left because all
8031 // the inputs are zero.
8032 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8033 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8034 V2Shuffle[V2Index] = 0;
8035 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8037 V2 = DAG.getBitcast(MVT::v2i64, V2);
8039 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8040 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
8041 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
8042 DAG.getDataLayout(), VT)));
8043 V2 = DAG.getBitcast(VT, V2);
8049 /// \brief Try to lower broadcast of a single - truncated - integer element,
8050 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
8052 /// This assumes we have AVX2.
8053 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
8055 const X86Subtarget *Subtarget,
8056 SelectionDAG &DAG) {
8057 assert(Subtarget->hasAVX2() &&
8058 "We can only lower integer broadcasts with AVX2!");
8060 EVT EltVT = VT.getVectorElementType();
8061 EVT V0VT = V0.getValueType();
8063 assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
8064 assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
8066 EVT V0EltVT = V0VT.getVectorElementType();
8067 if (!V0EltVT.isInteger())
8070 const unsigned EltSize = EltVT.getSizeInBits();
8071 const unsigned V0EltSize = V0EltVT.getSizeInBits();
8073 // This is only a truncation if the original element type is larger.
8074 if (V0EltSize <= EltSize)
8077 assert(((V0EltSize % EltSize) == 0) &&
8078 "Scalar type sizes must all be powers of 2 on x86!");
8080 const unsigned V0Opc = V0.getOpcode();
8081 const unsigned Scale = V0EltSize / EltSize;
8082 const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
8084 if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
8085 V0Opc != ISD::BUILD_VECTOR)
8088 SDValue Scalar = V0.getOperand(V0BroadcastIdx);
8090 // If we're extracting non-least-significant bits, shift so we can truncate.
8091 // Hopefully, we can fold away the trunc/srl/load into the broadcast.
8092 // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
8093 // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
8094 if (const int OffsetIdx = BroadcastIdx % Scale)
8095 Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
8096 DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
8098 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
8099 DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
8102 /// \brief Try to lower broadcast of a single element.
8104 /// For convenience, this code also bundles all of the subtarget feature set
8105 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8106 /// a convenient way to factor it out.
8107 /// FIXME: This is very similar to LowerVectorBroadcast - can we merge them?
8108 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
8110 const X86Subtarget *Subtarget,
8111 SelectionDAG &DAG) {
8112 if (!Subtarget->hasAVX())
8114 if (VT.isInteger() && !Subtarget->hasAVX2())
8117 // Check that the mask is a broadcast.
8118 int BroadcastIdx = -1;
8120 if (M >= 0 && BroadcastIdx == -1)
8122 else if (M >= 0 && M != BroadcastIdx)
8125 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8126 "a sorted mask where the broadcast "
8129 // Go up the chain of (vector) values to find a scalar load that we can
8130 // combine with the broadcast.
8132 switch (V.getOpcode()) {
8133 case ISD::CONCAT_VECTORS: {
8134 int OperandSize = Mask.size() / V.getNumOperands();
8135 V = V.getOperand(BroadcastIdx / OperandSize);
8136 BroadcastIdx %= OperandSize;
8140 case ISD::INSERT_SUBVECTOR: {
8141 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8142 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8146 int BeginIdx = (int)ConstantIdx->getZExtValue();
8148 BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
8149 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8150 BroadcastIdx -= BeginIdx;
8161 // Check if this is a broadcast of a scalar. We special case lowering
8162 // for scalars so that we can more effectively fold with loads.
8163 // First, look through bitcast: if the original value has a larger element
8164 // type than the shuffle, the broadcast element is in essence truncated.
8165 // Make that explicit to ease folding.
8166 if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
8167 if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
8168 DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
8169 return TruncBroadcast;
8171 // Also check the simpler case, where we can directly reuse the scalar.
8172 if (V.getOpcode() == ISD::BUILD_VECTOR ||
8173 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8174 V = V.getOperand(BroadcastIdx);
8176 // If the scalar isn't a load, we can't broadcast from it in AVX1.
8177 // Only AVX2 has register broadcasts.
8178 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8180 } else if (MayFoldLoad(V) && !cast<LoadSDNode>(V)->isVolatile()) {
8181 // If we are broadcasting a load that is only used by the shuffle
8182 // then we can reduce the vector load to the broadcasted scalar load.
8183 LoadSDNode *Ld = cast<LoadSDNode>(V);
8184 SDValue BaseAddr = Ld->getOperand(1);
8185 EVT AddrVT = BaseAddr.getValueType();
8186 EVT SVT = VT.getScalarType();
8187 unsigned Offset = BroadcastIdx * SVT.getStoreSize();
8188 SDValue NewAddr = DAG.getNode(
8189 ISD::ADD, DL, AddrVT, BaseAddr,
8190 DAG.getConstant(Offset, DL, AddrVT));
8191 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
8192 DAG.getMachineFunction().getMachineMemOperand(
8193 Ld->getMemOperand(), Offset, SVT.getStoreSize()));
8194 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8195 // We can't broadcast from a vector register without AVX2, and we can only
8196 // broadcast from the zero-element of a vector register.
8200 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
8203 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8204 // INSERTPS when the V1 elements are already in the correct locations
8205 // because otherwise we can just always use two SHUFPS instructions which
8206 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8207 // perform INSERTPS if a single V1 element is out of place and all V2
8208 // elements are zeroable.
8209 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8211 SelectionDAG &DAG) {
8212 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8213 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8214 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8215 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8217 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8220 int V1DstIndex = -1;
8221 int V2DstIndex = -1;
8222 bool V1UsedInPlace = false;
8224 for (int i = 0; i < 4; ++i) {
8225 // Synthesize a zero mask from the zeroable elements (includes undefs).
8231 // Flag if we use any V1 inputs in place.
8233 V1UsedInPlace = true;
8237 // We can only insert a single non-zeroable element.
8238 if (V1DstIndex != -1 || V2DstIndex != -1)
8242 // V1 input out of place for insertion.
8245 // V2 input for insertion.
8250 // Don't bother if we have no (non-zeroable) element for insertion.
8251 if (V1DstIndex == -1 && V2DstIndex == -1)
8254 // Determine element insertion src/dst indices. The src index is from the
8255 // start of the inserted vector, not the start of the concatenated vector.
8256 unsigned V2SrcIndex = 0;
8257 if (V1DstIndex != -1) {
8258 // If we have a V1 input out of place, we use V1 as the V2 element insertion
8259 // and don't use the original V2 at all.
8260 V2SrcIndex = Mask[V1DstIndex];
8261 V2DstIndex = V1DstIndex;
8264 V2SrcIndex = Mask[V2DstIndex] - 4;
8267 // If no V1 inputs are used in place, then the result is created only from
8268 // the zero mask and the V2 insertion - so remove V1 dependency.
8270 V1 = DAG.getUNDEF(MVT::v4f32);
8272 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8273 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8275 // Insert the V2 element into the desired position.
8277 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8278 DAG.getConstant(InsertPSMask, DL, MVT::i8));
8281 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8282 /// UNPCK instruction.
8284 /// This specifically targets cases where we end up with alternating between
8285 /// the two inputs, and so can permute them into something that feeds a single
8286 /// UNPCK instruction. Note that this routine only targets integer vectors
8287 /// because for floating point vectors we have a generalized SHUFPS lowering
8288 /// strategy that handles everything that doesn't *exactly* match an unpack,
8289 /// making this clever lowering unnecessary.
8290 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8291 SDValue V1, SDValue V2,
8293 SelectionDAG &DAG) {
8294 assert(!VT.isFloatingPoint() &&
8295 "This routine only supports integer vectors.");
8296 assert(!isSingleInputShuffleMask(Mask) &&
8297 "This routine should only be used when blending two inputs.");
8298 assert(Mask.size() >= 2 && "Single element masks are invalid.");
8300 int Size = Mask.size();
8302 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8303 return M >= 0 && M % Size < Size / 2;
8305 int NumHiInputs = std::count_if(
8306 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8308 bool UnpackLo = NumLoInputs >= NumHiInputs;
8310 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8311 SmallVector<int, 32> V1Mask(Mask.size(), -1);
8312 SmallVector<int, 32> V2Mask(Mask.size(), -1);
8314 for (int i = 0; i < Size; ++i) {
8318 // Each element of the unpack contains Scale elements from this mask.
8319 int UnpackIdx = i / Scale;
8321 // We only handle the case where V1 feeds the first slots of the unpack.
8322 // We rely on canonicalization to ensure this is the case.
8323 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8326 // Setup the mask for this input. The indexing is tricky as we have to
8327 // handle the unpack stride.
8328 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8329 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8333 // If we will have to shuffle both inputs to use the unpack, check whether
8334 // we can just unpack first and shuffle the result. If so, skip this unpack.
8335 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8336 !isNoopShuffleMask(V2Mask))
8339 // Shuffle the inputs into place.
8340 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8341 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8343 // Cast the inputs to the type we will use to unpack them.
8344 V1 = DAG.getBitcast(UnpackVT, V1);
8345 V2 = DAG.getBitcast(UnpackVT, V2);
8347 // Unpack the inputs and cast the result back to the desired type.
8348 return DAG.getBitcast(
8349 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8353 // We try each unpack from the largest to the smallest to try and find one
8354 // that fits this mask.
8355 int OrigNumElements = VT.getVectorNumElements();
8356 int OrigScalarSize = VT.getScalarSizeInBits();
8357 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8358 int Scale = ScalarSize / OrigScalarSize;
8359 int NumElements = OrigNumElements / Scale;
8360 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8361 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8365 // If none of the unpack-rooted lowerings worked (or were profitable) try an
8367 if (NumLoInputs == 0 || NumHiInputs == 0) {
8368 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8369 "We have to have *some* inputs!");
8370 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8372 // FIXME: We could consider the total complexity of the permute of each
8373 // possible unpacking. Or at the least we should consider how many
8374 // half-crossings are created.
8375 // FIXME: We could consider commuting the unpacks.
8377 SmallVector<int, 32> PermMask;
8378 PermMask.assign(Size, -1);
8379 for (int i = 0; i < Size; ++i) {
8383 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8386 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8388 return DAG.getVectorShuffle(
8389 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8391 DAG.getUNDEF(VT), PermMask);
8397 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8399 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8400 /// support for floating point shuffles but not integer shuffles. These
8401 /// instructions will incur a domain crossing penalty on some chips though so
8402 /// it is better to avoid lowering through this for integer vectors where
8404 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8405 const X86Subtarget *Subtarget,
8406 SelectionDAG &DAG) {
8408 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8409 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8410 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8411 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8412 ArrayRef<int> Mask = SVOp->getMask();
8413 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8415 if (isSingleInputShuffleMask(Mask)) {
8416 // Use low duplicate instructions for masks that match their pattern.
8417 if (Subtarget->hasSSE3())
8418 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8419 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8421 // Straight shuffle of a single input vector. Simulate this by using the
8422 // single input as both of the "inputs" to this instruction..
8423 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8425 if (Subtarget->hasAVX()) {
8426 // If we have AVX, we can use VPERMILPS which will allow folding a load
8427 // into the shuffle.
8428 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8429 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8432 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8433 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8435 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8436 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8438 // If we have a single input, insert that into V1 if we can do so cheaply.
8439 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8440 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8441 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8443 // Try inverting the insertion since for v2 masks it is easy to do and we
8444 // can't reliably sort the mask one way or the other.
8445 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8446 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8447 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8448 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8452 // Try to use one of the special instruction patterns to handle two common
8453 // blend patterns if a zero-blend above didn't work.
8454 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8455 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8456 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8457 // We can either use a special instruction to load over the low double or
8458 // to move just the low double.
8460 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8462 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8464 if (Subtarget->hasSSE41())
8465 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8469 // Use dedicated unpack instructions for masks that match their pattern.
8471 lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8474 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8475 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8476 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8479 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8481 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8482 /// the integer unit to minimize domain crossing penalties. However, for blends
8483 /// it falls back to the floating point shuffle operation with appropriate bit
8485 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8486 const X86Subtarget *Subtarget,
8487 SelectionDAG &DAG) {
8489 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8490 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8491 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8492 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8493 ArrayRef<int> Mask = SVOp->getMask();
8494 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8496 if (isSingleInputShuffleMask(Mask)) {
8497 // Check for being able to broadcast a single element.
8498 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8499 Mask, Subtarget, DAG))
8502 // Straight shuffle of a single input vector. For everything from SSE2
8503 // onward this has a single fast instruction with no scary immediates.
8504 // We have to map the mask as it is actually a v4i32 shuffle instruction.
8505 V1 = DAG.getBitcast(MVT::v4i32, V1);
8506 int WidenedMask[4] = {
8507 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8508 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8509 return DAG.getBitcast(
8511 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8512 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8514 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8515 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8516 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8517 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8519 // If we have a blend of two PACKUS operations an the blend aligns with the
8520 // low and half halves, we can just merge the PACKUS operations. This is
8521 // particularly important as it lets us merge shuffles that this routine itself
8523 auto GetPackNode = [](SDValue V) {
8524 while (V.getOpcode() == ISD::BITCAST)
8525 V = V.getOperand(0);
8527 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8529 if (SDValue V1Pack = GetPackNode(V1))
8530 if (SDValue V2Pack = GetPackNode(V2))
8531 return DAG.getBitcast(MVT::v2i64,
8532 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8533 Mask[0] == 0 ? V1Pack.getOperand(0)
8534 : V1Pack.getOperand(1),
8535 Mask[1] == 2 ? V2Pack.getOperand(0)
8536 : V2Pack.getOperand(1)));
8538 // Try to use shift instructions.
8540 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8543 // When loading a scalar and then shuffling it into a vector we can often do
8544 // the insertion cheaply.
8545 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8546 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8548 // Try inverting the insertion since for v2 masks it is easy to do and we
8549 // can't reliably sort the mask one way or the other.
8550 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8551 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8552 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8555 // We have different paths for blend lowering, but they all must use the
8556 // *exact* same predicate.
8557 bool IsBlendSupported = Subtarget->hasSSE41();
8558 if (IsBlendSupported)
8559 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8563 // Use dedicated unpack instructions for masks that match their pattern.
8565 lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8568 // Try to use byte rotation instructions.
8569 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8570 if (Subtarget->hasSSSE3())
8571 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8572 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8575 // If we have direct support for blends, we should lower by decomposing into
8576 // a permute. That will be faster than the domain cross.
8577 if (IsBlendSupported)
8578 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8581 // We implement this with SHUFPD which is pretty lame because it will likely
8582 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8583 // However, all the alternatives are still more cycles and newer chips don't
8584 // have this problem. It would be really nice if x86 had better shuffles here.
8585 V1 = DAG.getBitcast(MVT::v2f64, V1);
8586 V2 = DAG.getBitcast(MVT::v2f64, V2);
8587 return DAG.getBitcast(MVT::v2i64,
8588 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8591 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8593 /// This is used to disable more specialized lowerings when the shufps lowering
8594 /// will happen to be efficient.
8595 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8596 // This routine only handles 128-bit shufps.
8597 assert(Mask.size() == 4 && "Unsupported mask size!");
8599 // To lower with a single SHUFPS we need to have the low half and high half
8600 // each requiring a single input.
8601 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8603 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8609 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8611 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8612 /// It makes no assumptions about whether this is the *best* lowering, it simply
8614 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8615 ArrayRef<int> Mask, SDValue V1,
8616 SDValue V2, SelectionDAG &DAG) {
8617 SDValue LowV = V1, HighV = V2;
8618 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8621 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8623 if (NumV2Elements == 1) {
8625 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8628 // Compute the index adjacent to V2Index and in the same half by toggling
8630 int V2AdjIndex = V2Index ^ 1;
8632 if (Mask[V2AdjIndex] == -1) {
8633 // Handles all the cases where we have a single V2 element and an undef.
8634 // This will only ever happen in the high lanes because we commute the
8635 // vector otherwise.
8637 std::swap(LowV, HighV);
8638 NewMask[V2Index] -= 4;
8640 // Handle the case where the V2 element ends up adjacent to a V1 element.
8641 // To make this work, blend them together as the first step.
8642 int V1Index = V2AdjIndex;
8643 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8644 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8645 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8647 // Now proceed to reconstruct the final blend as we have the necessary
8648 // high or low half formed.
8655 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8656 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8658 } else if (NumV2Elements == 2) {
8659 if (Mask[0] < 4 && Mask[1] < 4) {
8660 // Handle the easy case where we have V1 in the low lanes and V2 in the
8664 } else if (Mask[2] < 4 && Mask[3] < 4) {
8665 // We also handle the reversed case because this utility may get called
8666 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8667 // arrange things in the right direction.
8673 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8674 // trying to place elements directly, just blend them and set up the final
8675 // shuffle to place them.
8677 // The first two blend mask elements are for V1, the second two are for
8679 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8680 Mask[2] < 4 ? Mask[2] : Mask[3],
8681 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8682 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8683 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8684 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8686 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8689 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8690 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8691 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8692 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8695 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8696 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8699 /// \brief Lower 4-lane 32-bit floating point shuffles.
8701 /// Uses instructions exclusively from the floating point unit to minimize
8702 /// domain crossing penalties, as these are sufficient to implement all v4f32
8704 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8705 const X86Subtarget *Subtarget,
8706 SelectionDAG &DAG) {
8708 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8709 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8710 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8711 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8712 ArrayRef<int> Mask = SVOp->getMask();
8713 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8716 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8718 if (NumV2Elements == 0) {
8719 // Check for being able to broadcast a single element.
8720 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8721 Mask, Subtarget, DAG))
8724 // Use even/odd duplicate instructions for masks that match their pattern.
8725 if (Subtarget->hasSSE3()) {
8726 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8727 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8728 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8729 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8732 if (Subtarget->hasAVX()) {
8733 // If we have AVX, we can use VPERMILPS which will allow folding a load
8734 // into the shuffle.
8735 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8736 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8739 // Otherwise, use a straight shuffle of a single input vector. We pass the
8740 // input vector to both operands to simulate this with a SHUFPS.
8741 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8742 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8745 // There are special ways we can lower some single-element blends. However, we
8746 // have custom ways we can lower more complex single-element blends below that
8747 // we defer to if both this and BLENDPS fail to match, so restrict this to
8748 // when the V2 input is targeting element 0 of the mask -- that is the fast
8750 if (NumV2Elements == 1 && Mask[0] >= 4)
8751 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8752 Mask, Subtarget, DAG))
8755 if (Subtarget->hasSSE41()) {
8756 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8760 // Use INSERTPS if we can complete the shuffle efficiently.
8761 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8764 if (!isSingleSHUFPSMask(Mask))
8765 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8766 DL, MVT::v4f32, V1, V2, Mask, DAG))
8770 // Use dedicated unpack instructions for masks that match their pattern.
8772 lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8775 // Otherwise fall back to a SHUFPS lowering strategy.
8776 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8779 /// \brief Lower 4-lane i32 vector shuffles.
8781 /// We try to handle these with integer-domain shuffles where we can, but for
8782 /// blends we use the floating point domain blend instructions.
8783 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8784 const X86Subtarget *Subtarget,
8785 SelectionDAG &DAG) {
8787 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8788 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8789 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8790 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8791 ArrayRef<int> Mask = SVOp->getMask();
8792 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8794 // Whenever we can lower this as a zext, that instruction is strictly faster
8795 // than any alternative. It also allows us to fold memory operands into the
8796 // shuffle in many cases.
8797 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8798 Mask, Subtarget, DAG))
8802 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8804 if (NumV2Elements == 0) {
8805 // Check for being able to broadcast a single element.
8806 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8807 Mask, Subtarget, DAG))
8810 // Straight shuffle of a single input vector. For everything from SSE2
8811 // onward this has a single fast instruction with no scary immediates.
8812 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8813 // but we aren't actually going to use the UNPCK instruction because doing
8814 // so prevents folding a load into this instruction or making a copy.
8815 const int UnpackLoMask[] = {0, 0, 1, 1};
8816 const int UnpackHiMask[] = {2, 2, 3, 3};
8817 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8818 Mask = UnpackLoMask;
8819 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8820 Mask = UnpackHiMask;
8822 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8823 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8826 // Try to use shift instructions.
8828 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8831 // There are special ways we can lower some single-element blends.
8832 if (NumV2Elements == 1)
8833 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8834 Mask, Subtarget, DAG))
8837 // We have different paths for blend lowering, but they all must use the
8838 // *exact* same predicate.
8839 bool IsBlendSupported = Subtarget->hasSSE41();
8840 if (IsBlendSupported)
8841 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8845 if (SDValue Masked =
8846 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8849 // Use dedicated unpack instructions for masks that match their pattern.
8851 lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8854 // Try to use byte rotation instructions.
8855 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8856 if (Subtarget->hasSSSE3())
8857 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8858 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8861 // If we have direct support for blends, we should lower by decomposing into
8862 // a permute. That will be faster than the domain cross.
8863 if (IsBlendSupported)
8864 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8867 // Try to lower by permuting the inputs into an unpack instruction.
8868 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8872 // We implement this with SHUFPS because it can blend from two vectors.
8873 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8874 // up the inputs, bypassing domain shift penalties that we would encur if we
8875 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8877 return DAG.getBitcast(
8879 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8880 DAG.getBitcast(MVT::v4f32, V2), Mask));
8883 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8884 /// shuffle lowering, and the most complex part.
8886 /// The lowering strategy is to try to form pairs of input lanes which are
8887 /// targeted at the same half of the final vector, and then use a dword shuffle
8888 /// to place them onto the right half, and finally unpack the paired lanes into
8889 /// their final position.
8891 /// The exact breakdown of how to form these dword pairs and align them on the
8892 /// correct sides is really tricky. See the comments within the function for
8893 /// more of the details.
8895 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8896 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8897 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8898 /// vector, form the analogous 128-bit 8-element Mask.
8899 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8900 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8901 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8902 assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8903 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8905 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8906 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8907 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8909 SmallVector<int, 4> LoInputs;
8910 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8911 [](int M) { return M >= 0; });
8912 std::sort(LoInputs.begin(), LoInputs.end());
8913 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8914 SmallVector<int, 4> HiInputs;
8915 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8916 [](int M) { return M >= 0; });
8917 std::sort(HiInputs.begin(), HiInputs.end());
8918 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8920 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8921 int NumHToL = LoInputs.size() - NumLToL;
8923 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8924 int NumHToH = HiInputs.size() - NumLToH;
8925 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8926 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8927 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8928 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8930 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8931 // such inputs we can swap two of the dwords across the half mark and end up
8932 // with <=2 inputs to each half in each half. Once there, we can fall through
8933 // to the generic code below. For example:
8935 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8936 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8938 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8939 // and an existing 2-into-2 on the other half. In this case we may have to
8940 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8941 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8942 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8943 // because any other situation (including a 3-into-1 or 1-into-3 in the other
8944 // half than the one we target for fixing) will be fixed when we re-enter this
8945 // path. We will also combine away any sequence of PSHUFD instructions that
8946 // result into a single instruction. Here is an example of the tricky case:
8948 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8949 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8951 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8953 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8954 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8956 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8957 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8959 // The result is fine to be handled by the generic logic.
8960 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8961 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8962 int AOffset, int BOffset) {
8963 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8964 "Must call this with A having 3 or 1 inputs from the A half.");
8965 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8966 "Must call this with B having 1 or 3 inputs from the B half.");
8967 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8968 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8970 bool ThreeAInputs = AToAInputs.size() == 3;
8972 // Compute the index of dword with only one word among the three inputs in
8973 // a half by taking the sum of the half with three inputs and subtracting
8974 // the sum of the actual three inputs. The difference is the remaining
8977 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8978 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8979 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8980 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8981 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8982 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8983 int TripleNonInputIdx =
8984 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8985 TripleDWord = TripleNonInputIdx / 2;
8987 // We use xor with one to compute the adjacent DWord to whichever one the
8989 OneInputDWord = (OneInput / 2) ^ 1;
8991 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8992 // and BToA inputs. If there is also such a problem with the BToB and AToB
8993 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8994 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8995 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8996 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8997 // Compute how many inputs will be flipped by swapping these DWords. We
8999 // to balance this to ensure we don't form a 3-1 shuffle in the other
9001 int NumFlippedAToBInputs =
9002 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
9003 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
9004 int NumFlippedBToBInputs =
9005 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
9006 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
9007 if ((NumFlippedAToBInputs == 1 &&
9008 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
9009 (NumFlippedBToBInputs == 1 &&
9010 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
9011 // We choose whether to fix the A half or B half based on whether that
9012 // half has zero flipped inputs. At zero, we may not be able to fix it
9013 // with that half. We also bias towards fixing the B half because that
9014 // will more commonly be the high half, and we have to bias one way.
9015 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
9016 ArrayRef<int> Inputs) {
9017 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
9018 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
9019 PinnedIdx ^ 1) != Inputs.end();
9020 // Determine whether the free index is in the flipped dword or the
9021 // unflipped dword based on where the pinned index is. We use this bit
9022 // in an xor to conditionally select the adjacent dword.
9023 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
9024 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9025 FixFreeIdx) != Inputs.end();
9026 if (IsFixIdxInput == IsFixFreeIdxInput)
9028 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9029 FixFreeIdx) != Inputs.end();
9030 assert(IsFixIdxInput != IsFixFreeIdxInput &&
9031 "We need to be changing the number of flipped inputs!");
9032 int PSHUFHalfMask[] = {0, 1, 2, 3};
9033 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
9034 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
9036 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
9039 if (M != -1 && M == FixIdx)
9041 else if (M != -1 && M == FixFreeIdx)
9044 if (NumFlippedBToBInputs != 0) {
9046 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
9047 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
9049 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
9050 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
9051 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
9056 int PSHUFDMask[] = {0, 1, 2, 3};
9057 PSHUFDMask[ADWord] = BDWord;
9058 PSHUFDMask[BDWord] = ADWord;
9061 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9062 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9064 // Adjust the mask to match the new locations of A and B.
9066 if (M != -1 && M/2 == ADWord)
9067 M = 2 * BDWord + M % 2;
9068 else if (M != -1 && M/2 == BDWord)
9069 M = 2 * ADWord + M % 2;
9071 // Recurse back into this routine to re-compute state now that this isn't
9072 // a 3 and 1 problem.
9073 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
9076 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
9077 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
9078 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
9079 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
9081 // At this point there are at most two inputs to the low and high halves from
9082 // each half. That means the inputs can always be grouped into dwords and
9083 // those dwords can then be moved to the correct half with a dword shuffle.
9084 // We use at most one low and one high word shuffle to collect these paired
9085 // inputs into dwords, and finally a dword shuffle to place them.
9086 int PSHUFLMask[4] = {-1, -1, -1, -1};
9087 int PSHUFHMask[4] = {-1, -1, -1, -1};
9088 int PSHUFDMask[4] = {-1, -1, -1, -1};
9090 // First fix the masks for all the inputs that are staying in their
9091 // original halves. This will then dictate the targets of the cross-half
9093 auto fixInPlaceInputs =
9094 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
9095 MutableArrayRef<int> SourceHalfMask,
9096 MutableArrayRef<int> HalfMask, int HalfOffset) {
9097 if (InPlaceInputs.empty())
9099 if (InPlaceInputs.size() == 1) {
9100 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9101 InPlaceInputs[0] - HalfOffset;
9102 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
9105 if (IncomingInputs.empty()) {
9106 // Just fix all of the in place inputs.
9107 for (int Input : InPlaceInputs) {
9108 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
9109 PSHUFDMask[Input / 2] = Input / 2;
9114 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
9115 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9116 InPlaceInputs[0] - HalfOffset;
9117 // Put the second input next to the first so that they are packed into
9118 // a dword. We find the adjacent index by toggling the low bit.
9119 int AdjIndex = InPlaceInputs[0] ^ 1;
9120 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
9121 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
9122 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
9124 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
9125 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
9127 // Now gather the cross-half inputs and place them into a free dword of
9128 // their target half.
9129 // FIXME: This operation could almost certainly be simplified dramatically to
9130 // look more like the 3-1 fixing operation.
9131 auto moveInputsToRightHalf = [&PSHUFDMask](
9132 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
9133 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
9134 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
9136 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
9137 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
9139 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
9141 int LowWord = Word & ~1;
9142 int HighWord = Word | 1;
9143 return isWordClobbered(SourceHalfMask, LowWord) ||
9144 isWordClobbered(SourceHalfMask, HighWord);
9147 if (IncomingInputs.empty())
9150 if (ExistingInputs.empty()) {
9151 // Map any dwords with inputs from them into the right half.
9152 for (int Input : IncomingInputs) {
9153 // If the source half mask maps over the inputs, turn those into
9154 // swaps and use the swapped lane.
9155 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
9156 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
9157 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
9158 Input - SourceOffset;
9159 // We have to swap the uses in our half mask in one sweep.
9160 for (int &M : HalfMask)
9161 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
9163 else if (M == Input)
9164 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9166 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
9167 Input - SourceOffset &&
9168 "Previous placement doesn't match!");
9170 // Note that this correctly re-maps both when we do a swap and when
9171 // we observe the other side of the swap above. We rely on that to
9172 // avoid swapping the members of the input list directly.
9173 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9176 // Map the input's dword into the correct half.
9177 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
9178 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
9180 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
9182 "Previous placement doesn't match!");
9185 // And just directly shift any other-half mask elements to be same-half
9186 // as we will have mirrored the dword containing the element into the
9187 // same position within that half.
9188 for (int &M : HalfMask)
9189 if (M >= SourceOffset && M < SourceOffset + 4) {
9190 M = M - SourceOffset + DestOffset;
9191 assert(M >= 0 && "This should never wrap below zero!");
9196 // Ensure we have the input in a viable dword of its current half. This
9197 // is particularly tricky because the original position may be clobbered
9198 // by inputs being moved and *staying* in that half.
9199 if (IncomingInputs.size() == 1) {
9200 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9201 int InputFixed = std::find(std::begin(SourceHalfMask),
9202 std::end(SourceHalfMask), -1) -
9203 std::begin(SourceHalfMask) + SourceOffset;
9204 SourceHalfMask[InputFixed - SourceOffset] =
9205 IncomingInputs[0] - SourceOffset;
9206 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9208 IncomingInputs[0] = InputFixed;
9210 } else if (IncomingInputs.size() == 2) {
9211 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9212 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9213 // We have two non-adjacent or clobbered inputs we need to extract from
9214 // the source half. To do this, we need to map them into some adjacent
9215 // dword slot in the source mask.
9216 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9217 IncomingInputs[1] - SourceOffset};
9219 // If there is a free slot in the source half mask adjacent to one of
9220 // the inputs, place the other input in it. We use (Index XOR 1) to
9221 // compute an adjacent index.
9222 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9223 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9224 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9225 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9226 InputsFixed[1] = InputsFixed[0] ^ 1;
9227 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9228 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9229 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9230 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9231 InputsFixed[0] = InputsFixed[1] ^ 1;
9232 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9233 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9234 // The two inputs are in the same DWord but it is clobbered and the
9235 // adjacent DWord isn't used at all. Move both inputs to the free
9237 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9238 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9239 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9240 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9242 // The only way we hit this point is if there is no clobbering
9243 // (because there are no off-half inputs to this half) and there is no
9244 // free slot adjacent to one of the inputs. In this case, we have to
9245 // swap an input with a non-input.
9246 for (int i = 0; i < 4; ++i)
9247 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9248 "We can't handle any clobbers here!");
9249 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9250 "Cannot have adjacent inputs here!");
9252 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9253 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9255 // We also have to update the final source mask in this case because
9256 // it may need to undo the above swap.
9257 for (int &M : FinalSourceHalfMask)
9258 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9259 M = InputsFixed[1] + SourceOffset;
9260 else if (M == InputsFixed[1] + SourceOffset)
9261 M = (InputsFixed[0] ^ 1) + SourceOffset;
9263 InputsFixed[1] = InputsFixed[0] ^ 1;
9266 // Point everything at the fixed inputs.
9267 for (int &M : HalfMask)
9268 if (M == IncomingInputs[0])
9269 M = InputsFixed[0] + SourceOffset;
9270 else if (M == IncomingInputs[1])
9271 M = InputsFixed[1] + SourceOffset;
9273 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9274 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9277 llvm_unreachable("Unhandled input size!");
9280 // Now hoist the DWord down to the right half.
9281 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9282 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9283 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9284 for (int &M : HalfMask)
9285 for (int Input : IncomingInputs)
9287 M = FreeDWord * 2 + Input % 2;
9289 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9290 /*SourceOffset*/ 4, /*DestOffset*/ 0);
9291 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9292 /*SourceOffset*/ 0, /*DestOffset*/ 4);
9294 // Now enact all the shuffles we've computed to move the inputs into their
9296 if (!isNoopShuffleMask(PSHUFLMask))
9297 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9298 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9299 if (!isNoopShuffleMask(PSHUFHMask))
9300 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9301 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9302 if (!isNoopShuffleMask(PSHUFDMask))
9305 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9306 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9308 // At this point, each half should contain all its inputs, and we can then
9309 // just shuffle them into their final position.
9310 assert(std::count_if(LoMask.begin(), LoMask.end(),
9311 [](int M) { return M >= 4; }) == 0 &&
9312 "Failed to lift all the high half inputs to the low mask!");
9313 assert(std::count_if(HiMask.begin(), HiMask.end(),
9314 [](int M) { return M >= 0 && M < 4; }) == 0 &&
9315 "Failed to lift all the low half inputs to the high mask!");
9317 // Do a half shuffle for the low mask.
9318 if (!isNoopShuffleMask(LoMask))
9319 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9320 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9322 // Do a half shuffle with the high mask after shifting its values down.
9323 for (int &M : HiMask)
9326 if (!isNoopShuffleMask(HiMask))
9327 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9328 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9333 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9334 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9335 SDValue V2, ArrayRef<int> Mask,
9336 SelectionDAG &DAG, bool &V1InUse,
9338 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9344 int Size = Mask.size();
9345 int Scale = 16 / Size;
9346 for (int i = 0; i < 16; ++i) {
9347 if (Mask[i / Scale] == -1) {
9348 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9350 const int ZeroMask = 0x80;
9351 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9353 int V2Idx = Mask[i / Scale] < Size
9355 : (Mask[i / Scale] - Size) * Scale + i % Scale;
9356 if (Zeroable[i / Scale])
9357 V1Idx = V2Idx = ZeroMask;
9358 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9359 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9360 V1InUse |= (ZeroMask != V1Idx);
9361 V2InUse |= (ZeroMask != V2Idx);
9366 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9367 DAG.getBitcast(MVT::v16i8, V1),
9368 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9370 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9371 DAG.getBitcast(MVT::v16i8, V2),
9372 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9374 // If we need shuffled inputs from both, blend the two.
9376 if (V1InUse && V2InUse)
9377 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9379 V = V1InUse ? V1 : V2;
9381 // Cast the result back to the correct type.
9382 return DAG.getBitcast(VT, V);
9385 /// \brief Generic lowering of 8-lane i16 shuffles.
9387 /// This handles both single-input shuffles and combined shuffle/blends with
9388 /// two inputs. The single input shuffles are immediately delegated to
9389 /// a dedicated lowering routine.
9391 /// The blends are lowered in one of three fundamental ways. If there are few
9392 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9393 /// of the input is significantly cheaper when lowered as an interleaving of
9394 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9395 /// halves of the inputs separately (making them have relatively few inputs)
9396 /// and then concatenate them.
9397 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9398 const X86Subtarget *Subtarget,
9399 SelectionDAG &DAG) {
9401 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9402 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9403 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9404 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9405 ArrayRef<int> OrigMask = SVOp->getMask();
9406 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9407 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9408 MutableArrayRef<int> Mask(MaskStorage);
9410 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9412 // Whenever we can lower this as a zext, that instruction is strictly faster
9413 // than any alternative.
9414 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9415 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9418 auto isV1 = [](int M) { return M >= 0 && M < 8; };
9420 auto isV2 = [](int M) { return M >= 8; };
9422 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9424 if (NumV2Inputs == 0) {
9425 // Check for being able to broadcast a single element.
9426 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9427 Mask, Subtarget, DAG))
9430 // Try to use shift instructions.
9432 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9435 // Use dedicated unpack instructions for masks that match their pattern.
9437 lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9440 // Try to use byte rotation instructions.
9441 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9442 Mask, Subtarget, DAG))
9445 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9449 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9450 "All single-input shuffles should be canonicalized to be V1-input "
9453 // Try to use shift instructions.
9455 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9458 // See if we can use SSE4A Extraction / Insertion.
9459 if (Subtarget->hasSSE4A())
9460 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9463 // There are special ways we can lower some single-element blends.
9464 if (NumV2Inputs == 1)
9465 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9466 Mask, Subtarget, DAG))
9469 // We have different paths for blend lowering, but they all must use the
9470 // *exact* same predicate.
9471 bool IsBlendSupported = Subtarget->hasSSE41();
9472 if (IsBlendSupported)
9473 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9477 if (SDValue Masked =
9478 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9481 // Use dedicated unpack instructions for masks that match their pattern.
9483 lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9486 // Try to use byte rotation instructions.
9487 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9488 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9491 if (SDValue BitBlend =
9492 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9495 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9499 // If we can't directly blend but can use PSHUFB, that will be better as it
9500 // can both shuffle and set up the inefficient blend.
9501 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9502 bool V1InUse, V2InUse;
9503 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9507 // We can always bit-blend if we have to so the fallback strategy is to
9508 // decompose into single-input permutes and blends.
9509 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9513 /// \brief Check whether a compaction lowering can be done by dropping even
9514 /// elements and compute how many times even elements must be dropped.
9516 /// This handles shuffles which take every Nth element where N is a power of
9517 /// two. Example shuffle masks:
9519 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
9520 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9521 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
9522 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
9523 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
9524 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
9526 /// Any of these lanes can of course be undef.
9528 /// This routine only supports N <= 3.
9529 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9532 /// \returns N above, or the number of times even elements must be dropped if
9533 /// there is such a number. Otherwise returns zero.
9534 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9535 // Figure out whether we're looping over two inputs or just one.
9536 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9538 // The modulus for the shuffle vector entries is based on whether this is
9539 // a single input or not.
9540 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9541 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9542 "We should only be called with masks with a power-of-2 size!");
9544 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9546 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9547 // and 2^3 simultaneously. This is because we may have ambiguity with
9548 // partially undef inputs.
9549 bool ViableForN[3] = {true, true, true};
9551 for (int i = 0, e = Mask.size(); i < e; ++i) {
9552 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9557 bool IsAnyViable = false;
9558 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9559 if (ViableForN[j]) {
9562 // The shuffle mask must be equal to (i * 2^N) % M.
9563 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9566 ViableForN[j] = false;
9568 // Early exit if we exhaust the possible powers of two.
9573 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9577 // Return 0 as there is no viable power of two.
9581 /// \brief Generic lowering of v16i8 shuffles.
9583 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9584 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9585 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9586 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9588 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9589 const X86Subtarget *Subtarget,
9590 SelectionDAG &DAG) {
9592 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9593 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9594 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9595 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9596 ArrayRef<int> Mask = SVOp->getMask();
9597 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9599 // Try to use shift instructions.
9601 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9604 // Try to use byte rotation instructions.
9605 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9606 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9609 // Try to use a zext lowering.
9610 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9611 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9614 // See if we can use SSE4A Extraction / Insertion.
9615 if (Subtarget->hasSSE4A())
9616 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9620 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9622 // For single-input shuffles, there are some nicer lowering tricks we can use.
9623 if (NumV2Elements == 0) {
9624 // Check for being able to broadcast a single element.
9625 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9626 Mask, Subtarget, DAG))
9629 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9630 // Notably, this handles splat and partial-splat shuffles more efficiently.
9631 // However, it only makes sense if the pre-duplication shuffle simplifies
9632 // things significantly. Currently, this means we need to be able to
9633 // express the pre-duplication shuffle as an i16 shuffle.
9635 // FIXME: We should check for other patterns which can be widened into an
9636 // i16 shuffle as well.
9637 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9638 for (int i = 0; i < 16; i += 2)
9639 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9644 auto tryToWidenViaDuplication = [&]() -> SDValue {
9645 if (!canWidenViaDuplication(Mask))
9647 SmallVector<int, 4> LoInputs;
9648 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9649 [](int M) { return M >= 0 && M < 8; });
9650 std::sort(LoInputs.begin(), LoInputs.end());
9651 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9653 SmallVector<int, 4> HiInputs;
9654 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9655 [](int M) { return M >= 8; });
9656 std::sort(HiInputs.begin(), HiInputs.end());
9657 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9660 bool TargetLo = LoInputs.size() >= HiInputs.size();
9661 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9662 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9664 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9665 SmallDenseMap<int, int, 8> LaneMap;
9666 for (int I : InPlaceInputs) {
9667 PreDupI16Shuffle[I/2] = I/2;
9670 int j = TargetLo ? 0 : 4, je = j + 4;
9671 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9672 // Check if j is already a shuffle of this input. This happens when
9673 // there are two adjacent bytes after we move the low one.
9674 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9675 // If we haven't yet mapped the input, search for a slot into which
9677 while (j < je && PreDupI16Shuffle[j] != -1)
9681 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9684 // Map this input with the i16 shuffle.
9685 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9688 // Update the lane map based on the mapping we ended up with.
9689 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9691 V1 = DAG.getBitcast(
9693 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9694 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9696 // Unpack the bytes to form the i16s that will be shuffled into place.
9697 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9698 MVT::v16i8, V1, V1);
9700 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9701 for (int i = 0; i < 16; ++i)
9702 if (Mask[i] != -1) {
9703 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9704 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9705 if (PostDupI16Shuffle[i / 2] == -1)
9706 PostDupI16Shuffle[i / 2] = MappedMask;
9708 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9709 "Conflicting entrties in the original shuffle!");
9711 return DAG.getBitcast(
9713 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9714 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9716 if (SDValue V = tryToWidenViaDuplication())
9720 if (SDValue Masked =
9721 lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9724 // Use dedicated unpack instructions for masks that match their pattern.
9726 lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9729 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9730 // with PSHUFB. It is important to do this before we attempt to generate any
9731 // blends but after all of the single-input lowerings. If the single input
9732 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9733 // want to preserve that and we can DAG combine any longer sequences into
9734 // a PSHUFB in the end. But once we start blending from multiple inputs,
9735 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9736 // and there are *very* few patterns that would actually be faster than the
9737 // PSHUFB approach because of its ability to zero lanes.
9739 // FIXME: The only exceptions to the above are blends which are exact
9740 // interleavings with direct instructions supporting them. We currently don't
9741 // handle those well here.
9742 if (Subtarget->hasSSSE3()) {
9743 bool V1InUse = false;
9744 bool V2InUse = false;
9746 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9747 DAG, V1InUse, V2InUse);
9749 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9750 // do so. This avoids using them to handle blends-with-zero which is
9751 // important as a single pshufb is significantly faster for that.
9752 if (V1InUse && V2InUse) {
9753 if (Subtarget->hasSSE41())
9754 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9755 Mask, Subtarget, DAG))
9758 // We can use an unpack to do the blending rather than an or in some
9759 // cases. Even though the or may be (very minorly) more efficient, we
9760 // preference this lowering because there are common cases where part of
9761 // the complexity of the shuffles goes away when we do the final blend as
9763 // FIXME: It might be worth trying to detect if the unpack-feeding
9764 // shuffles will both be pshufb, in which case we shouldn't bother with
9766 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9767 DL, MVT::v16i8, V1, V2, Mask, DAG))
9774 // There are special ways we can lower some single-element blends.
9775 if (NumV2Elements == 1)
9776 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9777 Mask, Subtarget, DAG))
9780 if (SDValue BitBlend =
9781 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9784 // Check whether a compaction lowering can be done. This handles shuffles
9785 // which take every Nth element for some even N. See the helper function for
9788 // We special case these as they can be particularly efficiently handled with
9789 // the PACKUSB instruction on x86 and they show up in common patterns of
9790 // rearranging bytes to truncate wide elements.
9791 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9792 // NumEvenDrops is the power of two stride of the elements. Another way of
9793 // thinking about it is that we need to drop the even elements this many
9794 // times to get the original input.
9795 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9797 // First we need to zero all the dropped bytes.
9798 assert(NumEvenDrops <= 3 &&
9799 "No support for dropping even elements more than 3 times.");
9800 // We use the mask type to pick which bytes are preserved based on how many
9801 // elements are dropped.
9802 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9803 SDValue ByteClearMask = DAG.getBitcast(
9804 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9805 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9807 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9809 // Now pack things back together.
9810 V1 = DAG.getBitcast(MVT::v8i16, V1);
9811 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9812 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9813 for (int i = 1; i < NumEvenDrops; ++i) {
9814 Result = DAG.getBitcast(MVT::v8i16, Result);
9815 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9821 // Handle multi-input cases by blending single-input shuffles.
9822 if (NumV2Elements > 0)
9823 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9826 // The fallback path for single-input shuffles widens this into two v8i16
9827 // vectors with unpacks, shuffles those, and then pulls them back together
9831 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9832 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9833 for (int i = 0; i < 16; ++i)
9835 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9837 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9839 SDValue VLoHalf, VHiHalf;
9840 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9841 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9843 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9844 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9845 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9846 [](int M) { return M >= 0 && M % 2 == 1; })) {
9847 // Use a mask to drop the high bytes.
9848 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9849 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9850 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9852 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9853 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9855 // Squash the masks to point directly into VLoHalf.
9856 for (int &M : LoBlendMask)
9859 for (int &M : HiBlendMask)
9863 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9864 // VHiHalf so that we can blend them as i16s.
9865 VLoHalf = DAG.getBitcast(
9866 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9867 VHiHalf = DAG.getBitcast(
9868 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9871 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9872 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9874 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9877 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9879 /// This routine breaks down the specific type of 128-bit shuffle and
9880 /// dispatches to the lowering routines accordingly.
9881 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9882 MVT VT, const X86Subtarget *Subtarget,
9883 SelectionDAG &DAG) {
9884 switch (VT.SimpleTy) {
9886 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9888 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9890 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9892 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9894 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9896 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9899 llvm_unreachable("Unimplemented!");
9903 /// \brief Helper function to test whether a shuffle mask could be
9904 /// simplified by widening the elements being shuffled.
9906 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9907 /// leaves it in an unspecified state.
9909 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9910 /// shuffle masks. The latter have the special property of a '-2' representing
9911 /// a zero-ed lane of a vector.
9912 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9913 SmallVectorImpl<int> &WidenedMask) {
9914 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9915 // If both elements are undef, its trivial.
9916 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9917 WidenedMask.push_back(SM_SentinelUndef);
9921 // Check for an undef mask and a mask value properly aligned to fit with
9922 // a pair of values. If we find such a case, use the non-undef mask's value.
9923 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9924 WidenedMask.push_back(Mask[i + 1] / 2);
9927 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9928 WidenedMask.push_back(Mask[i] / 2);
9932 // When zeroing, we need to spread the zeroing across both lanes to widen.
9933 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9934 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9935 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9936 WidenedMask.push_back(SM_SentinelZero);
9942 // Finally check if the two mask values are adjacent and aligned with
9944 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9945 WidenedMask.push_back(Mask[i] / 2);
9949 // Otherwise we can't safely widen the elements used in this shuffle.
9952 assert(WidenedMask.size() == Mask.size() / 2 &&
9953 "Incorrect size of mask after widening the elements!");
9958 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9960 /// This routine just extracts two subvectors, shuffles them independently, and
9961 /// then concatenates them back together. This should work effectively with all
9962 /// AVX vector shuffle types.
9963 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9964 SDValue V2, ArrayRef<int> Mask,
9965 SelectionDAG &DAG) {
9966 assert(VT.getSizeInBits() >= 256 &&
9967 "Only for 256-bit or wider vector shuffles!");
9968 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9969 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9971 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9972 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9974 int NumElements = VT.getVectorNumElements();
9975 int SplitNumElements = NumElements / 2;
9976 MVT ScalarVT = VT.getVectorElementType();
9977 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9979 // Rather than splitting build-vectors, just build two narrower build
9980 // vectors. This helps shuffling with splats and zeros.
9981 auto SplitVector = [&](SDValue V) {
9982 while (V.getOpcode() == ISD::BITCAST)
9983 V = V->getOperand(0);
9985 MVT OrigVT = V.getSimpleValueType();
9986 int OrigNumElements = OrigVT.getVectorNumElements();
9987 int OrigSplitNumElements = OrigNumElements / 2;
9988 MVT OrigScalarVT = OrigVT.getVectorElementType();
9989 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9993 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9995 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9996 DAG.getIntPtrConstant(0, DL));
9997 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9998 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
10001 SmallVector<SDValue, 16> LoOps, HiOps;
10002 for (int i = 0; i < OrigSplitNumElements; ++i) {
10003 LoOps.push_back(BV->getOperand(i));
10004 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
10006 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
10007 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
10009 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
10010 DAG.getBitcast(SplitVT, HiV));
10013 SDValue LoV1, HiV1, LoV2, HiV2;
10014 std::tie(LoV1, HiV1) = SplitVector(V1);
10015 std::tie(LoV2, HiV2) = SplitVector(V2);
10017 // Now create two 4-way blends of these half-width vectors.
10018 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
10019 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
10020 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
10021 for (int i = 0; i < SplitNumElements; ++i) {
10022 int M = HalfMask[i];
10023 if (M >= NumElements) {
10024 if (M >= NumElements + SplitNumElements)
10028 V2BlendMask.push_back(M - NumElements);
10029 V1BlendMask.push_back(-1);
10030 BlendMask.push_back(SplitNumElements + i);
10031 } else if (M >= 0) {
10032 if (M >= SplitNumElements)
10036 V2BlendMask.push_back(-1);
10037 V1BlendMask.push_back(M);
10038 BlendMask.push_back(i);
10040 V2BlendMask.push_back(-1);
10041 V1BlendMask.push_back(-1);
10042 BlendMask.push_back(-1);
10046 // Because the lowering happens after all combining takes place, we need to
10047 // manually combine these blend masks as much as possible so that we create
10048 // a minimal number of high-level vector shuffle nodes.
10050 // First try just blending the halves of V1 or V2.
10051 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
10052 return DAG.getUNDEF(SplitVT);
10053 if (!UseLoV2 && !UseHiV2)
10054 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10055 if (!UseLoV1 && !UseHiV1)
10056 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10058 SDValue V1Blend, V2Blend;
10059 if (UseLoV1 && UseHiV1) {
10061 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10063 // We only use half of V1 so map the usage down into the final blend mask.
10064 V1Blend = UseLoV1 ? LoV1 : HiV1;
10065 for (int i = 0; i < SplitNumElements; ++i)
10066 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
10067 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
10069 if (UseLoV2 && UseHiV2) {
10071 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10073 // We only use half of V2 so map the usage down into the final blend mask.
10074 V2Blend = UseLoV2 ? LoV2 : HiV2;
10075 for (int i = 0; i < SplitNumElements; ++i)
10076 if (BlendMask[i] >= SplitNumElements)
10077 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
10079 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
10081 SDValue Lo = HalfBlend(LoMask);
10082 SDValue Hi = HalfBlend(HiMask);
10083 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
10086 /// \brief Either split a vector in halves or decompose the shuffles and the
10089 /// This is provided as a good fallback for many lowerings of non-single-input
10090 /// shuffles with more than one 128-bit lane. In those cases, we want to select
10091 /// between splitting the shuffle into 128-bit components and stitching those
10092 /// back together vs. extracting the single-input shuffles and blending those
10094 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
10095 SDValue V2, ArrayRef<int> Mask,
10096 SelectionDAG &DAG) {
10097 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
10098 "lower single-input shuffles as it "
10099 "could then recurse on itself.");
10100 int Size = Mask.size();
10102 // If this can be modeled as a broadcast of two elements followed by a blend,
10103 // prefer that lowering. This is especially important because broadcasts can
10104 // often fold with memory operands.
10105 auto DoBothBroadcast = [&] {
10106 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
10109 if (V2BroadcastIdx == -1)
10110 V2BroadcastIdx = M - Size;
10111 else if (M - Size != V2BroadcastIdx)
10113 } else if (M >= 0) {
10114 if (V1BroadcastIdx == -1)
10115 V1BroadcastIdx = M;
10116 else if (M != V1BroadcastIdx)
10121 if (DoBothBroadcast())
10122 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
10125 // If the inputs all stem from a single 128-bit lane of each input, then we
10126 // split them rather than blending because the split will decompose to
10127 // unusually few instructions.
10128 int LaneCount = VT.getSizeInBits() / 128;
10129 int LaneSize = Size / LaneCount;
10130 SmallBitVector LaneInputs[2];
10131 LaneInputs[0].resize(LaneCount, false);
10132 LaneInputs[1].resize(LaneCount, false);
10133 for (int i = 0; i < Size; ++i)
10135 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
10136 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
10137 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10139 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
10140 // that the decomposed single-input shuffles don't end up here.
10141 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10144 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
10145 /// a permutation and blend of those lanes.
10147 /// This essentially blends the out-of-lane inputs to each lane into the lane
10148 /// from a permuted copy of the vector. This lowering strategy results in four
10149 /// instructions in the worst case for a single-input cross lane shuffle which
10150 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
10151 /// of. Special cases for each particular shuffle pattern should be handled
10152 /// prior to trying this lowering.
10153 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
10154 SDValue V1, SDValue V2,
10155 ArrayRef<int> Mask,
10156 SelectionDAG &DAG) {
10157 // FIXME: This should probably be generalized for 512-bit vectors as well.
10158 assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
10159 int LaneSize = Mask.size() / 2;
10161 // If there are only inputs from one 128-bit lane, splitting will in fact be
10162 // less expensive. The flags track whether the given lane contains an element
10163 // that crosses to another lane.
10164 bool LaneCrossing[2] = {false, false};
10165 for (int i = 0, Size = Mask.size(); i < Size; ++i)
10166 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10167 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
10168 if (!LaneCrossing[0] || !LaneCrossing[1])
10169 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10171 if (isSingleInputShuffleMask(Mask)) {
10172 SmallVector<int, 32> FlippedBlendMask;
10173 for (int i = 0, Size = Mask.size(); i < Size; ++i)
10174 FlippedBlendMask.push_back(
10175 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
10177 : Mask[i] % LaneSize +
10178 (i / LaneSize) * LaneSize + Size));
10180 // Flip the vector, and blend the results which should now be in-lane. The
10181 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
10182 // 5 for the high source. The value 3 selects the high half of source 2 and
10183 // the value 2 selects the low half of source 2. We only use source 2 to
10184 // allow folding it into a memory operand.
10185 unsigned PERMMask = 3 | 2 << 4;
10186 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
10187 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
10188 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
10191 // This now reduces to two single-input shuffles of V1 and V2 which at worst
10192 // will be handled by the above logic and a blend of the results, much like
10193 // other patterns in AVX.
10194 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10197 /// \brief Handle lowering 2-lane 128-bit shuffles.
10198 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10199 SDValue V2, ArrayRef<int> Mask,
10200 const X86Subtarget *Subtarget,
10201 SelectionDAG &DAG) {
10202 // TODO: If minimizing size and one of the inputs is a zero vector and the
10203 // the zero vector has only one use, we could use a VPERM2X128 to save the
10204 // instruction bytes needed to explicitly generate the zero vector.
10206 // Blends are faster and handle all the non-lane-crossing cases.
10207 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10211 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10212 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10214 // If either input operand is a zero vector, use VPERM2X128 because its mask
10215 // allows us to replace the zero input with an implicit zero.
10216 if (!IsV1Zero && !IsV2Zero) {
10217 // Check for patterns which can be matched with a single insert of a 128-bit
10219 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10220 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10221 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10222 VT.getVectorNumElements() / 2);
10223 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10224 DAG.getIntPtrConstant(0, DL));
10225 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10226 OnlyUsesV1 ? V1 : V2,
10227 DAG.getIntPtrConstant(0, DL));
10228 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10232 // Otherwise form a 128-bit permutation. After accounting for undefs,
10233 // convert the 64-bit shuffle mask selection values into 128-bit
10234 // selection bits by dividing the indexes by 2 and shifting into positions
10235 // defined by a vperm2*128 instruction's immediate control byte.
10237 // The immediate permute control byte looks like this:
10238 // [1:0] - select 128 bits from sources for low half of destination
10240 // [3] - zero low half of destination
10241 // [5:4] - select 128 bits from sources for high half of destination
10243 // [7] - zero high half of destination
10245 int MaskLO = Mask[0];
10246 if (MaskLO == SM_SentinelUndef)
10247 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10249 int MaskHI = Mask[2];
10250 if (MaskHI == SM_SentinelUndef)
10251 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10253 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10255 // If either input is a zero vector, replace it with an undef input.
10256 // Shuffle mask values < 4 are selecting elements of V1.
10257 // Shuffle mask values >= 4 are selecting elements of V2.
10258 // Adjust each half of the permute mask by clearing the half that was
10259 // selecting the zero vector and setting the zero mask bit.
10261 V1 = DAG.getUNDEF(VT);
10263 PermMask = (PermMask & 0xf0) | 0x08;
10265 PermMask = (PermMask & 0x0f) | 0x80;
10268 V2 = DAG.getUNDEF(VT);
10270 PermMask = (PermMask & 0xf0) | 0x08;
10272 PermMask = (PermMask & 0x0f) | 0x80;
10275 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10276 DAG.getConstant(PermMask, DL, MVT::i8));
10279 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10280 /// shuffling each lane.
10282 /// This will only succeed when the result of fixing the 128-bit lanes results
10283 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10284 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10285 /// the lane crosses early and then use simpler shuffles within each lane.
10287 /// FIXME: It might be worthwhile at some point to support this without
10288 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10289 /// in x86 only floating point has interesting non-repeating shuffles, and even
10290 /// those are still *marginally* more expensive.
10291 static SDValue lowerVectorShuffleByMerging128BitLanes(
10292 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10293 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10294 assert(!isSingleInputShuffleMask(Mask) &&
10295 "This is only useful with multiple inputs.");
10297 int Size = Mask.size();
10298 int LaneSize = 128 / VT.getScalarSizeInBits();
10299 int NumLanes = Size / LaneSize;
10300 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10302 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10303 // check whether the in-128-bit lane shuffles share a repeating pattern.
10304 SmallVector<int, 4> Lanes;
10305 Lanes.resize(NumLanes, -1);
10306 SmallVector<int, 4> InLaneMask;
10307 InLaneMask.resize(LaneSize, -1);
10308 for (int i = 0; i < Size; ++i) {
10312 int j = i / LaneSize;
10314 if (Lanes[j] < 0) {
10315 // First entry we've seen for this lane.
10316 Lanes[j] = Mask[i] / LaneSize;
10317 } else if (Lanes[j] != Mask[i] / LaneSize) {
10318 // This doesn't match the lane selected previously!
10322 // Check that within each lane we have a consistent shuffle mask.
10323 int k = i % LaneSize;
10324 if (InLaneMask[k] < 0) {
10325 InLaneMask[k] = Mask[i] % LaneSize;
10326 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10327 // This doesn't fit a repeating in-lane mask.
10332 // First shuffle the lanes into place.
10333 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10334 VT.getSizeInBits() / 64);
10335 SmallVector<int, 8> LaneMask;
10336 LaneMask.resize(NumLanes * 2, -1);
10337 for (int i = 0; i < NumLanes; ++i)
10338 if (Lanes[i] >= 0) {
10339 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10340 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10343 V1 = DAG.getBitcast(LaneVT, V1);
10344 V2 = DAG.getBitcast(LaneVT, V2);
10345 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10347 // Cast it back to the type we actually want.
10348 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10350 // Now do a simple shuffle that isn't lane crossing.
10351 SmallVector<int, 8> NewMask;
10352 NewMask.resize(Size, -1);
10353 for (int i = 0; i < Size; ++i)
10355 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10356 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10357 "Must not introduce lane crosses at this point!");
10359 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10362 /// Lower shuffles where an entire half of a 256-bit vector is UNDEF.
10363 /// This allows for fast cases such as subvector extraction/insertion
10364 /// or shuffling smaller vector types which can lower more efficiently.
10365 static SDValue lowerVectorShuffleWithUndefHalf(SDLoc DL, MVT VT, SDValue V1,
10366 SDValue V2, ArrayRef<int> Mask,
10367 const X86Subtarget *Subtarget,
10368 SelectionDAG &DAG) {
10369 assert(VT.getSizeInBits() == 256 && "Expected 256-bit vector");
10371 unsigned NumElts = VT.getVectorNumElements();
10372 unsigned HalfNumElts = NumElts / 2;
10373 MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(), HalfNumElts);
10375 bool UndefLower = isUndefInRange(Mask, 0, HalfNumElts);
10376 bool UndefUpper = isUndefInRange(Mask, HalfNumElts, HalfNumElts);
10377 if (!UndefLower && !UndefUpper)
10380 // Upper half is undef and lower half is whole upper subvector.
10381 // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
10383 isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
10384 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10385 DAG.getIntPtrConstant(HalfNumElts, DL));
10386 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10387 DAG.getIntPtrConstant(0, DL));
10390 // Lower half is undef and upper half is whole lower subvector.
10391 // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
10393 isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
10394 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10395 DAG.getIntPtrConstant(0, DL));
10396 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10397 DAG.getIntPtrConstant(HalfNumElts, DL));
10400 // AVX2 supports efficient immediate 64-bit element cross-lane shuffles.
10401 if (UndefLower && Subtarget->hasAVX2() &&
10402 (VT == MVT::v4f64 || VT == MVT::v4i64))
10405 // If the shuffle only uses the lower halves of the input operands,
10406 // then extract them and perform the 'half' shuffle at half width.
10407 // e.g. vector_shuffle <X, X, X, X, u, u, u, u> or <X, X, u, u>
10408 int HalfIdx1 = -1, HalfIdx2 = -1;
10409 SmallVector<int, 8> HalfMask;
10410 unsigned Offset = UndefLower ? HalfNumElts : 0;
10411 for (unsigned i = 0; i != HalfNumElts; ++i) {
10412 int M = Mask[i + Offset];
10414 HalfMask.push_back(M);
10418 // Determine which of the 4 half vectors this element is from.
10419 // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
10420 int HalfIdx = M / HalfNumElts;
10422 // Only shuffle using the lower halves of the inputs.
10423 // TODO: Investigate usefulness of shuffling with upper halves.
10424 if (HalfIdx != 0 && HalfIdx != 2)
10427 // Determine the element index into its half vector source.
10428 int HalfElt = M % HalfNumElts;
10430 // We can shuffle with up to 2 half vectors, set the new 'half'
10431 // shuffle mask accordingly.
10432 if (-1 == HalfIdx1 || HalfIdx1 == HalfIdx) {
10433 HalfMask.push_back(HalfElt);
10434 HalfIdx1 = HalfIdx;
10437 if (-1 == HalfIdx2 || HalfIdx2 == HalfIdx) {
10438 HalfMask.push_back(HalfElt + HalfNumElts);
10439 HalfIdx2 = HalfIdx;
10443 // Too many half vectors referenced.
10446 assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
10448 auto GetHalfVector = [&](int HalfIdx) {
10450 return DAG.getUNDEF(HalfVT);
10451 SDValue V = (HalfIdx < 2 ? V1 : V2);
10452 HalfIdx = (HalfIdx % 2) * HalfNumElts;
10453 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
10454 DAG.getIntPtrConstant(HalfIdx, DL));
10457 SDValue Half1 = GetHalfVector(HalfIdx1);
10458 SDValue Half2 = GetHalfVector(HalfIdx2);
10459 SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
10460 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
10461 DAG.getIntPtrConstant(Offset, DL));
10464 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10467 /// This returns true if the elements from a particular input are already in the
10468 /// slot required by the given mask and require no permutation.
10469 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10470 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10471 int Size = Mask.size();
10472 for (int i = 0; i < Size; ++i)
10473 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10479 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10480 ArrayRef<int> Mask, SDValue V1,
10481 SDValue V2, SelectionDAG &DAG) {
10483 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
10484 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
10485 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10486 int NumElts = VT.getVectorNumElements();
10487 bool ShufpdMask = true;
10488 bool CommutableMask = true;
10489 unsigned Immediate = 0;
10490 for (int i = 0; i < NumElts; ++i) {
10493 int Val = (i & 6) + NumElts * (i & 1);
10494 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10495 if (Mask[i] < Val || Mask[i] > Val + 1)
10496 ShufpdMask = false;
10497 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
10498 CommutableMask = false;
10499 Immediate |= (Mask[i] % 2) << i;
10502 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10503 DAG.getConstant(Immediate, DL, MVT::i8));
10504 if (CommutableMask)
10505 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10506 DAG.getConstant(Immediate, DL, MVT::i8));
10510 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10512 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10513 /// isn't available.
10514 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10515 const X86Subtarget *Subtarget,
10516 SelectionDAG &DAG) {
10518 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10519 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10520 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10521 ArrayRef<int> Mask = SVOp->getMask();
10522 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10524 SmallVector<int, 4> WidenedMask;
10525 if (canWidenShuffleElements(Mask, WidenedMask))
10526 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10529 if (isSingleInputShuffleMask(Mask)) {
10530 // Check for being able to broadcast a single element.
10531 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10532 Mask, Subtarget, DAG))
10535 // Use low duplicate instructions for masks that match their pattern.
10536 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10537 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10539 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10540 // Non-half-crossing single input shuffles can be lowerid with an
10541 // interleaved permutation.
10542 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10543 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10544 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10545 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10548 // With AVX2 we have direct support for this permutation.
10549 if (Subtarget->hasAVX2())
10550 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10551 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10553 // Otherwise, fall back.
10554 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10558 // Use dedicated unpack instructions for masks that match their pattern.
10560 lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10563 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10567 // Check if the blend happens to exactly fit that of SHUFPD.
10569 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10572 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10573 // shuffle. However, if we have AVX2 and either inputs are already in place,
10574 // we will be able to shuffle even across lanes the other input in a single
10575 // instruction so skip this pattern.
10576 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10577 isShuffleMaskInputInPlace(1, Mask))))
10578 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10579 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10582 // If we have AVX2 then we always want to lower with a blend because an v4 we
10583 // can fully permute the elements.
10584 if (Subtarget->hasAVX2())
10585 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10588 // Otherwise fall back on generic lowering.
10589 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10592 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10594 /// This routine is only called when we have AVX2 and thus a reasonable
10595 /// instruction set for v4i64 shuffling..
10596 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10597 const X86Subtarget *Subtarget,
10598 SelectionDAG &DAG) {
10600 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10601 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10602 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10603 ArrayRef<int> Mask = SVOp->getMask();
10604 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10605 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10607 SmallVector<int, 4> WidenedMask;
10608 if (canWidenShuffleElements(Mask, WidenedMask))
10609 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10612 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10616 // Check for being able to broadcast a single element.
10617 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10618 Mask, Subtarget, DAG))
10621 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10622 // use lower latency instructions that will operate on both 128-bit lanes.
10623 SmallVector<int, 2> RepeatedMask;
10624 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10625 if (isSingleInputShuffleMask(Mask)) {
10626 int PSHUFDMask[] = {-1, -1, -1, -1};
10627 for (int i = 0; i < 2; ++i)
10628 if (RepeatedMask[i] >= 0) {
10629 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10630 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10632 return DAG.getBitcast(
10634 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10635 DAG.getBitcast(MVT::v8i32, V1),
10636 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10640 // AVX2 provides a direct instruction for permuting a single input across
10642 if (isSingleInputShuffleMask(Mask))
10643 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10644 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10646 // Try to use shift instructions.
10647 if (SDValue Shift =
10648 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10651 // Use dedicated unpack instructions for masks that match their pattern.
10653 lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10656 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10657 // shuffle. However, if we have AVX2 and either inputs are already in place,
10658 // we will be able to shuffle even across lanes the other input in a single
10659 // instruction so skip this pattern.
10660 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10661 isShuffleMaskInputInPlace(1, Mask))))
10662 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10663 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10666 // Otherwise fall back on generic blend lowering.
10667 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10671 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10673 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10674 /// isn't available.
10675 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10676 const X86Subtarget *Subtarget,
10677 SelectionDAG &DAG) {
10679 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10680 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10681 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10682 ArrayRef<int> Mask = SVOp->getMask();
10683 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10685 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10689 // Check for being able to broadcast a single element.
10690 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10691 Mask, Subtarget, DAG))
10694 // If the shuffle mask is repeated in each 128-bit lane, we have many more
10695 // options to efficiently lower the shuffle.
10696 SmallVector<int, 4> RepeatedMask;
10697 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10698 assert(RepeatedMask.size() == 4 &&
10699 "Repeated masks must be half the mask width!");
10701 // Use even/odd duplicate instructions for masks that match their pattern.
10702 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10703 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10704 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10705 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10707 if (isSingleInputShuffleMask(Mask))
10708 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10709 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10711 // Use dedicated unpack instructions for masks that match their pattern.
10713 lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10716 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10717 // have already handled any direct blends. We also need to squash the
10718 // repeated mask into a simulated v4f32 mask.
10719 for (int i = 0; i < 4; ++i)
10720 if (RepeatedMask[i] >= 8)
10721 RepeatedMask[i] -= 4;
10722 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10725 // If we have a single input shuffle with different shuffle patterns in the
10726 // two 128-bit lanes use the variable mask to VPERMILPS.
10727 if (isSingleInputShuffleMask(Mask)) {
10728 SDValue VPermMask[8];
10729 for (int i = 0; i < 8; ++i)
10730 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10731 : DAG.getConstant(Mask[i], DL, MVT::i32);
10732 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10733 return DAG.getNode(
10734 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10735 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10737 if (Subtarget->hasAVX2())
10738 return DAG.getNode(
10739 X86ISD::VPERMV, DL, MVT::v8f32,
10740 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10742 // Otherwise, fall back.
10743 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10747 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10749 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10750 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10753 // If we have AVX2 then we always want to lower with a blend because at v8 we
10754 // can fully permute the elements.
10755 if (Subtarget->hasAVX2())
10756 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10759 // Otherwise fall back on generic lowering.
10760 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10763 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10765 /// This routine is only called when we have AVX2 and thus a reasonable
10766 /// instruction set for v8i32 shuffling..
10767 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10768 const X86Subtarget *Subtarget,
10769 SelectionDAG &DAG) {
10771 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10772 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10773 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10774 ArrayRef<int> Mask = SVOp->getMask();
10775 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10776 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10778 // Whenever we can lower this as a zext, that instruction is strictly faster
10779 // than any alternative. It also allows us to fold memory operands into the
10780 // shuffle in many cases.
10781 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10782 Mask, Subtarget, DAG))
10785 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10789 // Check for being able to broadcast a single element.
10790 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10791 Mask, Subtarget, DAG))
10794 // If the shuffle mask is repeated in each 128-bit lane we can use more
10795 // efficient instructions that mirror the shuffles across the two 128-bit
10797 SmallVector<int, 4> RepeatedMask;
10798 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10799 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10800 if (isSingleInputShuffleMask(Mask))
10801 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10802 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10804 // Use dedicated unpack instructions for masks that match their pattern.
10806 lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10810 // Try to use shift instructions.
10811 if (SDValue Shift =
10812 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10815 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10816 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10819 // If the shuffle patterns aren't repeated but it is a single input, directly
10820 // generate a cross-lane VPERMD instruction.
10821 if (isSingleInputShuffleMask(Mask)) {
10822 SDValue VPermMask[8];
10823 for (int i = 0; i < 8; ++i)
10824 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10825 : DAG.getConstant(Mask[i], DL, MVT::i32);
10826 return DAG.getNode(
10827 X86ISD::VPERMV, DL, MVT::v8i32,
10828 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10831 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10833 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10834 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10837 // Otherwise fall back on generic blend lowering.
10838 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10842 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10844 /// This routine is only called when we have AVX2 and thus a reasonable
10845 /// instruction set for v16i16 shuffling..
10846 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10847 const X86Subtarget *Subtarget,
10848 SelectionDAG &DAG) {
10850 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10851 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10852 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10853 ArrayRef<int> Mask = SVOp->getMask();
10854 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10855 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10857 // Whenever we can lower this as a zext, that instruction is strictly faster
10858 // than any alternative. It also allows us to fold memory operands into the
10859 // shuffle in many cases.
10860 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10861 Mask, Subtarget, DAG))
10864 // Check for being able to broadcast a single element.
10865 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10866 Mask, Subtarget, DAG))
10869 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10873 // Use dedicated unpack instructions for masks that match their pattern.
10875 lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10878 // Try to use shift instructions.
10879 if (SDValue Shift =
10880 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10883 // Try to use byte rotation instructions.
10884 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10885 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10888 if (isSingleInputShuffleMask(Mask)) {
10889 // There are no generalized cross-lane shuffle operations available on i16
10891 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10892 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10895 SmallVector<int, 8> RepeatedMask;
10896 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10897 // As this is a single-input shuffle, the repeated mask should be
10898 // a strictly valid v8i16 mask that we can pass through to the v8i16
10899 // lowering to handle even the v16 case.
10900 return lowerV8I16GeneralSingleInputVectorShuffle(
10901 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10904 SDValue PSHUFBMask[32];
10905 for (int i = 0; i < 16; ++i) {
10906 if (Mask[i] == -1) {
10907 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10911 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10912 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10913 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10914 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10916 return DAG.getBitcast(MVT::v16i16,
10917 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10918 DAG.getBitcast(MVT::v32i8, V1),
10919 DAG.getNode(ISD::BUILD_VECTOR, DL,
10920 MVT::v32i8, PSHUFBMask)));
10923 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10925 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10926 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10929 // Otherwise fall back on generic lowering.
10930 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10933 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10935 /// This routine is only called when we have AVX2 and thus a reasonable
10936 /// instruction set for v32i8 shuffling..
10937 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10938 const X86Subtarget *Subtarget,
10939 SelectionDAG &DAG) {
10941 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10942 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10943 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10944 ArrayRef<int> Mask = SVOp->getMask();
10945 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10946 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10948 // Whenever we can lower this as a zext, that instruction is strictly faster
10949 // than any alternative. It also allows us to fold memory operands into the
10950 // shuffle in many cases.
10951 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10952 Mask, Subtarget, DAG))
10955 // Check for being able to broadcast a single element.
10956 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10957 Mask, Subtarget, DAG))
10960 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10964 // Use dedicated unpack instructions for masks that match their pattern.
10966 lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
10969 // Try to use shift instructions.
10970 if (SDValue Shift =
10971 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10974 // Try to use byte rotation instructions.
10975 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10976 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10979 if (isSingleInputShuffleMask(Mask)) {
10980 // There are no generalized cross-lane shuffle operations available on i8
10982 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10983 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10986 SDValue PSHUFBMask[32];
10987 for (int i = 0; i < 32; ++i)
10990 ? DAG.getUNDEF(MVT::i8)
10991 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10994 return DAG.getNode(
10995 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10996 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10999 // Try to simplify this by merging 128-bit lanes to enable a lane-based
11001 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
11002 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11005 // Otherwise fall back on generic lowering.
11006 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
11009 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
11011 /// This routine either breaks down the specific type of a 256-bit x86 vector
11012 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
11013 /// together based on the available instructions.
11014 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11015 MVT VT, const X86Subtarget *Subtarget,
11016 SelectionDAG &DAG) {
11018 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11019 ArrayRef<int> Mask = SVOp->getMask();
11021 // If we have a single input to the zero element, insert that into V1 if we
11022 // can do so cheaply.
11023 int NumElts = VT.getVectorNumElements();
11024 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
11025 return M >= NumElts;
11028 if (NumV2Elements == 1 && Mask[0] >= NumElts)
11029 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
11030 DL, VT, V1, V2, Mask, Subtarget, DAG))
11033 // Handle special cases where the lower or upper half is UNDEF.
11035 lowerVectorShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
11038 // There is a really nice hard cut-over between AVX1 and AVX2 that means we
11039 // can check for those subtargets here and avoid much of the subtarget
11040 // querying in the per-vector-type lowering routines. With AVX1 we have
11041 // essentially *zero* ability to manipulate a 256-bit vector with integer
11042 // types. Since we'll use floating point types there eventually, just
11043 // immediately cast everything to a float and operate entirely in that domain.
11044 if (VT.isInteger() && !Subtarget->hasAVX2()) {
11045 int ElementBits = VT.getScalarSizeInBits();
11046 if (ElementBits < 32)
11047 // No floating point type available, decompose into 128-bit vectors.
11048 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11050 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
11051 VT.getVectorNumElements());
11052 V1 = DAG.getBitcast(FpVT, V1);
11053 V2 = DAG.getBitcast(FpVT, V2);
11054 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
11057 switch (VT.SimpleTy) {
11059 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11061 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11063 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11065 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11067 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11069 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11072 llvm_unreachable("Not a valid 256-bit x86 vector type!");
11076 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
11077 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
11078 ArrayRef<int> Mask,
11079 SDValue V1, SDValue V2,
11080 SelectionDAG &DAG) {
11081 assert(VT.getScalarSizeInBits() == 64 &&
11082 "Unexpected element type size for 128bit shuffle.");
11084 // To handle 256 bit vector requires VLX and most probably
11085 // function lowerV2X128VectorShuffle() is better solution.
11086 assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
11088 SmallVector<int, 4> WidenedMask;
11089 if (!canWidenShuffleElements(Mask, WidenedMask))
11092 // Form a 128-bit permutation.
11093 // Convert the 64-bit shuffle mask selection values into 128-bit selection
11094 // bits defined by a vshuf64x2 instruction's immediate control byte.
11095 unsigned PermMask = 0, Imm = 0;
11096 unsigned ControlBitsNum = WidenedMask.size() / 2;
11098 for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
11099 if (WidenedMask[i] == SM_SentinelZero)
11102 // Use first element in place of undef mask.
11103 Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
11104 PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
11107 return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
11108 DAG.getConstant(PermMask, DL, MVT::i8));
11111 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
11112 ArrayRef<int> Mask, SDValue V1,
11113 SDValue V2, SelectionDAG &DAG) {
11115 assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
11117 MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
11118 MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
11120 SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
11121 if (isSingleInputShuffleMask(Mask))
11122 return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
11124 return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
11127 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
11128 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11129 const X86Subtarget *Subtarget,
11130 SelectionDAG &DAG) {
11132 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11133 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11134 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11135 ArrayRef<int> Mask = SVOp->getMask();
11136 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11138 if (SDValue Shuf128 =
11139 lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
11142 if (SDValue Unpck =
11143 lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
11146 return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
11149 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
11150 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11151 const X86Subtarget *Subtarget,
11152 SelectionDAG &DAG) {
11154 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11155 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11156 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11157 ArrayRef<int> Mask = SVOp->getMask();
11158 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11160 if (SDValue Unpck =
11161 lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
11164 return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
11167 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
11168 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11169 const X86Subtarget *Subtarget,
11170 SelectionDAG &DAG) {
11172 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11173 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11174 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11175 ArrayRef<int> Mask = SVOp->getMask();
11176 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11178 if (SDValue Shuf128 =
11179 lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
11182 if (SDValue Unpck =
11183 lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
11186 return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
11189 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
11190 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11191 const X86Subtarget *Subtarget,
11192 SelectionDAG &DAG) {
11194 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11195 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11196 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11197 ArrayRef<int> Mask = SVOp->getMask();
11198 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11200 if (SDValue Unpck =
11201 lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
11204 return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
11207 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
11208 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11209 const X86Subtarget *Subtarget,
11210 SelectionDAG &DAG) {
11212 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11213 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11214 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11215 ArrayRef<int> Mask = SVOp->getMask();
11216 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11217 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
11219 return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
11222 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
11223 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11224 const X86Subtarget *Subtarget,
11225 SelectionDAG &DAG) {
11227 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11228 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11229 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11230 ArrayRef<int> Mask = SVOp->getMask();
11231 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
11232 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
11234 // FIXME: Implement direct support for this type!
11235 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
11238 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
11240 /// This routine either breaks down the specific type of a 512-bit x86 vector
11241 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
11242 /// together based on the available instructions.
11243 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11244 MVT VT, const X86Subtarget *Subtarget,
11245 SelectionDAG &DAG) {
11247 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11248 ArrayRef<int> Mask = SVOp->getMask();
11249 assert(Subtarget->hasAVX512() &&
11250 "Cannot lower 512-bit vectors w/ basic ISA!");
11252 // Check for being able to broadcast a single element.
11253 if (SDValue Broadcast =
11254 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
11257 // Dispatch to each element type for lowering. If we don't have supprot for
11258 // specific element type shuffles at 512 bits, immediately split them and
11259 // lower them. Each lowering routine of a given type is allowed to assume that
11260 // the requisite ISA extensions for that element type are available.
11261 switch (VT.SimpleTy) {
11263 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11265 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11267 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11269 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11271 if (Subtarget->hasBWI())
11272 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11275 if (Subtarget->hasBWI())
11276 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11280 llvm_unreachable("Not a valid 512-bit x86 vector type!");
11283 // Otherwise fall back on splitting.
11284 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11287 // Lower vXi1 vector shuffles.
11288 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
11289 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
11290 // vector, shuffle and then truncate it back.
11291 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11292 MVT VT, const X86Subtarget *Subtarget,
11293 SelectionDAG &DAG) {
11295 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11296 ArrayRef<int> Mask = SVOp->getMask();
11297 assert(Subtarget->hasAVX512() &&
11298 "Cannot lower 512-bit vectors w/o basic ISA!");
11300 switch (VT.SimpleTy) {
11302 llvm_unreachable("Expected a vector of i1 elements");
11304 ExtVT = MVT::v2i64;
11307 ExtVT = MVT::v4i32;
11310 ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11313 ExtVT = MVT::v16i32;
11316 ExtVT = MVT::v32i16;
11319 ExtVT = MVT::v64i8;
11323 if (ISD::isBuildVectorAllZeros(V1.getNode()))
11324 V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11325 else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11326 V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11328 V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11331 V2 = DAG.getUNDEF(ExtVT);
11332 else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11333 V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11334 else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11335 V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11337 V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11338 return DAG.getNode(ISD::TRUNCATE, DL, VT,
11339 DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11341 /// \brief Top-level lowering for x86 vector shuffles.
11343 /// This handles decomposition, canonicalization, and lowering of all x86
11344 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11345 /// above in helper routines. The canonicalization attempts to widen shuffles
11346 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11347 /// s.t. only one of the two inputs needs to be tested, etc.
11348 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11349 SelectionDAG &DAG) {
11350 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11351 ArrayRef<int> Mask = SVOp->getMask();
11352 SDValue V1 = Op.getOperand(0);
11353 SDValue V2 = Op.getOperand(1);
11354 MVT VT = Op.getSimpleValueType();
11355 int NumElements = VT.getVectorNumElements();
11357 bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11359 assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11360 "Can't lower MMX shuffles");
11362 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11363 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11364 if (V1IsUndef && V2IsUndef)
11365 return DAG.getUNDEF(VT);
11367 // When we create a shuffle node we put the UNDEF node to second operand,
11368 // but in some cases the first operand may be transformed to UNDEF.
11369 // In this case we should just commute the node.
11371 return DAG.getCommutedVectorShuffle(*SVOp);
11373 // Check for non-undef masks pointing at an undef vector and make the masks
11374 // undef as well. This makes it easier to match the shuffle based solely on
11378 if (M >= NumElements) {
11379 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11380 for (int &M : NewMask)
11381 if (M >= NumElements)
11383 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11386 // We actually see shuffles that are entirely re-arrangements of a set of
11387 // zero inputs. This mostly happens while decomposing complex shuffles into
11388 // simple ones. Directly lower these as a buildvector of zeros.
11389 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11390 if (Zeroable.all())
11391 return getZeroVector(VT, Subtarget, DAG, dl);
11393 // Try to collapse shuffles into using a vector type with fewer elements but
11394 // wider element types. We cap this to not form integers or floating point
11395 // elements wider than 64 bits, but it might be interesting to form i128
11396 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11397 SmallVector<int, 16> WidenedMask;
11398 if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11399 canWidenShuffleElements(Mask, WidenedMask)) {
11400 MVT NewEltVT = VT.isFloatingPoint()
11401 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11402 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11403 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11404 // Make sure that the new vector type is legal. For example, v2f64 isn't
11406 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11407 V1 = DAG.getBitcast(NewVT, V1);
11408 V2 = DAG.getBitcast(NewVT, V2);
11409 return DAG.getBitcast(
11410 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11414 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11415 for (int M : SVOp->getMask())
11417 ++NumUndefElements;
11418 else if (M < NumElements)
11423 // Commute the shuffle as needed such that more elements come from V1 than
11424 // V2. This allows us to match the shuffle pattern strictly on how many
11425 // elements come from V1 without handling the symmetric cases.
11426 if (NumV2Elements > NumV1Elements)
11427 return DAG.getCommutedVectorShuffle(*SVOp);
11429 // When the number of V1 and V2 elements are the same, try to minimize the
11430 // number of uses of V2 in the low half of the vector. When that is tied,
11431 // ensure that the sum of indices for V1 is equal to or lower than the sum
11432 // indices for V2. When those are equal, try to ensure that the number of odd
11433 // indices for V1 is lower than the number of odd indices for V2.
11434 if (NumV1Elements == NumV2Elements) {
11435 int LowV1Elements = 0, LowV2Elements = 0;
11436 for (int M : SVOp->getMask().slice(0, NumElements / 2))
11437 if (M >= NumElements)
11441 if (LowV2Elements > LowV1Elements) {
11442 return DAG.getCommutedVectorShuffle(*SVOp);
11443 } else if (LowV2Elements == LowV1Elements) {
11444 int SumV1Indices = 0, SumV2Indices = 0;
11445 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11446 if (SVOp->getMask()[i] >= NumElements)
11448 else if (SVOp->getMask()[i] >= 0)
11450 if (SumV2Indices < SumV1Indices) {
11451 return DAG.getCommutedVectorShuffle(*SVOp);
11452 } else if (SumV2Indices == SumV1Indices) {
11453 int NumV1OddIndices = 0, NumV2OddIndices = 0;
11454 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11455 if (SVOp->getMask()[i] >= NumElements)
11456 NumV2OddIndices += i % 2;
11457 else if (SVOp->getMask()[i] >= 0)
11458 NumV1OddIndices += i % 2;
11459 if (NumV2OddIndices < NumV1OddIndices)
11460 return DAG.getCommutedVectorShuffle(*SVOp);
11465 // For each vector width, delegate to a specialized lowering routine.
11466 if (VT.is128BitVector())
11467 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11469 if (VT.is256BitVector())
11470 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11472 if (VT.is512BitVector())
11473 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11476 return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11477 llvm_unreachable("Unimplemented!");
11480 // This function assumes its argument is a BUILD_VECTOR of constants or
11481 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11483 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11484 unsigned &MaskValue) {
11486 unsigned NumElems = BuildVector->getNumOperands();
11488 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11489 // We don't handle the >2 lanes case right now.
11490 unsigned NumLanes = (NumElems - 1) / 8 + 1;
11494 unsigned NumElemsInLane = NumElems / NumLanes;
11496 // Blend for v16i16 should be symmetric for the both lanes.
11497 for (unsigned i = 0; i < NumElemsInLane; ++i) {
11498 SDValue EltCond = BuildVector->getOperand(i);
11499 SDValue SndLaneEltCond =
11500 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11502 int Lane1Cond = -1, Lane2Cond = -1;
11503 if (isa<ConstantSDNode>(EltCond))
11504 Lane1Cond = !isNullConstant(EltCond);
11505 if (isa<ConstantSDNode>(SndLaneEltCond))
11506 Lane2Cond = !isNullConstant(SndLaneEltCond);
11508 unsigned LaneMask = 0;
11509 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11510 // Lane1Cond != 0, means we want the first argument.
11511 // Lane1Cond == 0, means we want the second argument.
11512 // The encoding of this argument is 0 for the first argument, 1
11513 // for the second. Therefore, invert the condition.
11514 LaneMask = !Lane1Cond << i;
11515 else if (Lane1Cond < 0)
11516 LaneMask = !Lane2Cond << i;
11520 MaskValue |= LaneMask;
11522 MaskValue |= LaneMask << NumElemsInLane;
11527 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11528 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11529 const X86Subtarget *Subtarget,
11530 SelectionDAG &DAG) {
11531 SDValue Cond = Op.getOperand(0);
11532 SDValue LHS = Op.getOperand(1);
11533 SDValue RHS = Op.getOperand(2);
11535 MVT VT = Op.getSimpleValueType();
11537 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11539 auto *CondBV = cast<BuildVectorSDNode>(Cond);
11541 // Only non-legal VSELECTs reach this lowering, convert those into generic
11542 // shuffles and re-use the shuffle lowering path for blends.
11543 SmallVector<int, 32> Mask;
11544 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11545 SDValue CondElt = CondBV->getOperand(i);
11547 isa<ConstantSDNode>(CondElt) ? i + (isNullConstant(CondElt) ? Size : 0)
11550 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11553 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11554 // A vselect where all conditions and data are constants can be optimized into
11555 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11556 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11557 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11558 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11561 // Try to lower this to a blend-style vector shuffle. This can handle all
11562 // constant condition cases.
11563 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11566 // Variable blends are only legal from SSE4.1 onward.
11567 if (!Subtarget->hasSSE41())
11570 // Only some types will be legal on some subtargets. If we can emit a legal
11571 // VSELECT-matching blend, return Op, and but if we need to expand, return
11573 switch (Op.getSimpleValueType().SimpleTy) {
11575 // Most of the vector types have blends past SSE4.1.
11579 // The byte blends for AVX vectors were introduced only in AVX2.
11580 if (Subtarget->hasAVX2())
11587 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11588 if (Subtarget->hasBWI() && Subtarget->hasVLX())
11591 // FIXME: We should custom lower this by fixing the condition and using i8
11597 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11598 MVT VT = Op.getSimpleValueType();
11601 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11604 if (VT.getSizeInBits() == 8) {
11605 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11606 Op.getOperand(0), Op.getOperand(1));
11607 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11608 DAG.getValueType(VT));
11609 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11612 if (VT.getSizeInBits() == 16) {
11613 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11614 if (isNullConstant(Op.getOperand(1)))
11615 return DAG.getNode(
11616 ISD::TRUNCATE, dl, MVT::i16,
11617 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11618 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11619 Op.getOperand(1)));
11620 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11621 Op.getOperand(0), Op.getOperand(1));
11622 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11623 DAG.getValueType(VT));
11624 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11627 if (VT == MVT::f32) {
11628 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11629 // the result back to FR32 register. It's only worth matching if the
11630 // result has a single use which is a store or a bitcast to i32. And in
11631 // the case of a store, it's not worth it if the index is a constant 0,
11632 // because a MOVSSmr can be used instead, which is smaller and faster.
11633 if (!Op.hasOneUse())
11635 SDNode *User = *Op.getNode()->use_begin();
11636 if ((User->getOpcode() != ISD::STORE ||
11637 isNullConstant(Op.getOperand(1))) &&
11638 (User->getOpcode() != ISD::BITCAST ||
11639 User->getValueType(0) != MVT::i32))
11641 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11642 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11644 return DAG.getBitcast(MVT::f32, Extract);
11647 if (VT == MVT::i32 || VT == MVT::i64) {
11648 // ExtractPS/pextrq works with constant index.
11649 if (isa<ConstantSDNode>(Op.getOperand(1)))
11655 /// Extract one bit from mask vector, like v16i1 or v8i1.
11656 /// AVX-512 feature.
11658 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11659 SDValue Vec = Op.getOperand(0);
11661 MVT VecVT = Vec.getSimpleValueType();
11662 SDValue Idx = Op.getOperand(1);
11663 MVT EltVT = Op.getSimpleValueType();
11665 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11666 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11667 "Unexpected vector type in ExtractBitFromMaskVector");
11669 // variable index can't be handled in mask registers,
11670 // extend vector to VR512
11671 if (!isa<ConstantSDNode>(Idx)) {
11672 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11673 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11674 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11675 ExtVT.getVectorElementType(), Ext, Idx);
11676 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11679 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11680 const TargetRegisterClass* rc = getRegClassFor(VecVT);
11681 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11682 rc = getRegClassFor(MVT::v16i1);
11683 unsigned MaxSift = rc->getSize()*8 - 1;
11684 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11685 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11686 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11687 DAG.getConstant(MaxSift, dl, MVT::i8));
11688 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11689 DAG.getIntPtrConstant(0, dl));
11693 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11694 SelectionDAG &DAG) const {
11696 SDValue Vec = Op.getOperand(0);
11697 MVT VecVT = Vec.getSimpleValueType();
11698 SDValue Idx = Op.getOperand(1);
11700 if (Op.getSimpleValueType() == MVT::i1)
11701 return ExtractBitFromMaskVector(Op, DAG);
11703 if (!isa<ConstantSDNode>(Idx)) {
11704 if (VecVT.is512BitVector() ||
11705 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11706 VecVT.getVectorElementType().getSizeInBits() == 32)) {
11709 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11710 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11711 MaskEltVT.getSizeInBits());
11713 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11714 auto PtrVT = getPointerTy(DAG.getDataLayout());
11715 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11716 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11717 DAG.getConstant(0, dl, PtrVT));
11718 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11719 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11720 DAG.getConstant(0, dl, PtrVT));
11725 // If this is a 256-bit vector result, first extract the 128-bit vector and
11726 // then extract the element from the 128-bit vector.
11727 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11729 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11730 // Get the 128-bit vector.
11731 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11732 MVT EltVT = VecVT.getVectorElementType();
11734 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11735 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11737 // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11738 // this can be done with a mask.
11739 IdxVal &= ElemsPerChunk - 1;
11740 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11741 DAG.getConstant(IdxVal, dl, MVT::i32));
11744 assert(VecVT.is128BitVector() && "Unexpected vector length");
11746 if (Subtarget->hasSSE41())
11747 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11750 MVT VT = Op.getSimpleValueType();
11751 // TODO: handle v16i8.
11752 if (VT.getSizeInBits() == 16) {
11753 SDValue Vec = Op.getOperand(0);
11754 if (isNullConstant(Op.getOperand(1)))
11755 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11756 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11757 DAG.getBitcast(MVT::v4i32, Vec),
11758 Op.getOperand(1)));
11759 // Transform it so it match pextrw which produces a 32-bit result.
11760 MVT EltVT = MVT::i32;
11761 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11762 Op.getOperand(0), Op.getOperand(1));
11763 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11764 DAG.getValueType(VT));
11765 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11768 if (VT.getSizeInBits() == 32) {
11769 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11773 // SHUFPS the element to the lowest double word, then movss.
11774 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11775 MVT VVT = Op.getOperand(0).getSimpleValueType();
11776 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11777 DAG.getUNDEF(VVT), Mask);
11778 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11779 DAG.getIntPtrConstant(0, dl));
11782 if (VT.getSizeInBits() == 64) {
11783 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11784 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11785 // to match extract_elt for f64.
11786 if (isNullConstant(Op.getOperand(1)))
11789 // UNPCKHPD the element to the lowest double word, then movsd.
11790 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11791 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11792 int Mask[2] = { 1, -1 };
11793 MVT VVT = Op.getOperand(0).getSimpleValueType();
11794 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11795 DAG.getUNDEF(VVT), Mask);
11796 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11797 DAG.getIntPtrConstant(0, dl));
11803 /// Insert one bit to mask vector, like v16i1 or v8i1.
11804 /// AVX-512 feature.
11806 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11808 SDValue Vec = Op.getOperand(0);
11809 SDValue Elt = Op.getOperand(1);
11810 SDValue Idx = Op.getOperand(2);
11811 MVT VecVT = Vec.getSimpleValueType();
11813 if (!isa<ConstantSDNode>(Idx)) {
11814 // Non constant index. Extend source and destination,
11815 // insert element and then truncate the result.
11816 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11817 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
11818 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11819 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11820 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11821 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11824 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11825 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11827 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11828 DAG.getConstant(IdxVal, dl, MVT::i8));
11829 if (Vec.getOpcode() == ISD::UNDEF)
11831 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11834 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11835 SelectionDAG &DAG) const {
11836 MVT VT = Op.getSimpleValueType();
11837 MVT EltVT = VT.getVectorElementType();
11839 if (EltVT == MVT::i1)
11840 return InsertBitToMaskVector(Op, DAG);
11843 SDValue N0 = Op.getOperand(0);
11844 SDValue N1 = Op.getOperand(1);
11845 SDValue N2 = Op.getOperand(2);
11846 if (!isa<ConstantSDNode>(N2))
11848 auto *N2C = cast<ConstantSDNode>(N2);
11849 unsigned IdxVal = N2C->getZExtValue();
11851 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11852 // into that, and then insert the subvector back into the result.
11853 if (VT.is256BitVector() || VT.is512BitVector()) {
11854 // With a 256-bit vector, we can insert into the zero element efficiently
11855 // using a blend if we have AVX or AVX2 and the right data type.
11856 if (VT.is256BitVector() && IdxVal == 0) {
11857 // TODO: It is worthwhile to cast integer to floating point and back
11858 // and incur a domain crossing penalty if that's what we'll end up
11859 // doing anyway after extracting to a 128-bit vector.
11860 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11861 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11862 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11863 N2 = DAG.getIntPtrConstant(1, dl);
11864 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11868 // Get the desired 128-bit vector chunk.
11869 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11871 // Insert the element into the desired chunk.
11872 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11873 assert(isPowerOf2_32(NumEltsIn128));
11874 // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11875 unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11877 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11878 DAG.getConstant(IdxIn128, dl, MVT::i32));
11880 // Insert the changed part back into the bigger vector
11881 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11883 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11885 if (Subtarget->hasSSE41()) {
11886 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11888 if (VT == MVT::v8i16) {
11889 Opc = X86ISD::PINSRW;
11891 assert(VT == MVT::v16i8);
11892 Opc = X86ISD::PINSRB;
11895 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11897 if (N1.getValueType() != MVT::i32)
11898 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11899 if (N2.getValueType() != MVT::i32)
11900 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11901 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11904 if (EltVT == MVT::f32) {
11905 // Bits [7:6] of the constant are the source select. This will always be
11906 // zero here. The DAG Combiner may combine an extract_elt index into
11907 // these bits. For example (insert (extract, 3), 2) could be matched by
11908 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11909 // Bits [5:4] of the constant are the destination select. This is the
11910 // value of the incoming immediate.
11911 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11912 // combine either bitwise AND or insert of float 0.0 to set these bits.
11914 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11915 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11916 // If this is an insertion of 32-bits into the low 32-bits of
11917 // a vector, we prefer to generate a blend with immediate rather
11918 // than an insertps. Blends are simpler operations in hardware and so
11919 // will always have equal or better performance than insertps.
11920 // But if optimizing for size and there's a load folding opportunity,
11921 // generate insertps because blendps does not have a 32-bit memory
11923 N2 = DAG.getIntPtrConstant(1, dl);
11924 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11925 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11927 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11928 // Create this as a scalar to vector..
11929 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11930 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11933 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11934 // PINSR* works with constant index.
11939 if (EltVT == MVT::i8)
11942 if (EltVT.getSizeInBits() == 16) {
11943 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11944 // as its second argument.
11945 if (N1.getValueType() != MVT::i32)
11946 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11947 if (N2.getValueType() != MVT::i32)
11948 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11949 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11954 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11956 MVT OpVT = Op.getSimpleValueType();
11958 // If this is a 256-bit vector result, first insert into a 128-bit
11959 // vector and then insert into the 256-bit vector.
11960 if (!OpVT.is128BitVector()) {
11961 // Insert into a 128-bit vector.
11962 unsigned SizeFactor = OpVT.getSizeInBits()/128;
11963 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11964 OpVT.getVectorNumElements() / SizeFactor);
11966 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11968 // Insert the 128-bit vector.
11969 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11972 if (OpVT == MVT::v1i64 &&
11973 Op.getOperand(0).getValueType() == MVT::i64)
11974 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11976 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11977 assert(OpVT.is128BitVector() && "Expected an SSE type!");
11978 return DAG.getBitcast(
11979 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11982 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
11983 // a simple subregister reference or explicit instructions to grab
11984 // upper bits of a vector.
11985 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11986 SelectionDAG &DAG) {
11988 SDValue In = Op.getOperand(0);
11989 SDValue Idx = Op.getOperand(1);
11990 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11991 MVT ResVT = Op.getSimpleValueType();
11992 MVT InVT = In.getSimpleValueType();
11994 if (Subtarget->hasFp256()) {
11995 if (ResVT.is128BitVector() &&
11996 (InVT.is256BitVector() || InVT.is512BitVector()) &&
11997 isa<ConstantSDNode>(Idx)) {
11998 return Extract128BitVector(In, IdxVal, DAG, dl);
12000 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
12001 isa<ConstantSDNode>(Idx)) {
12002 return Extract256BitVector(In, IdxVal, DAG, dl);
12008 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
12009 // simple superregister reference or explicit instructions to insert
12010 // the upper bits of a vector.
12011 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12012 SelectionDAG &DAG) {
12013 if (!Subtarget->hasAVX())
12017 SDValue Vec = Op.getOperand(0);
12018 SDValue SubVec = Op.getOperand(1);
12019 SDValue Idx = Op.getOperand(2);
12021 if (!isa<ConstantSDNode>(Idx))
12024 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12025 MVT OpVT = Op.getSimpleValueType();
12026 MVT SubVecVT = SubVec.getSimpleValueType();
12028 // Fold two 16-byte subvector loads into one 32-byte load:
12029 // (insert_subvector (insert_subvector undef, (load addr), 0),
12030 // (load addr + 16), Elts/2)
12032 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
12033 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
12034 OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
12035 auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
12036 if (Idx2 && Idx2->getZExtValue() == 0) {
12037 SDValue SubVec2 = Vec.getOperand(1);
12038 // If needed, look through a bitcast to get to the load.
12039 if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
12040 SubVec2 = SubVec2.getOperand(0);
12042 if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
12044 unsigned Alignment = FirstLd->getAlignment();
12045 unsigned AS = FirstLd->getAddressSpace();
12046 const X86TargetLowering *TLI = Subtarget->getTargetLowering();
12047 if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
12048 OpVT, AS, Alignment, &Fast) && Fast) {
12049 SDValue Ops[] = { SubVec2, SubVec };
12050 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
12057 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
12058 SubVecVT.is128BitVector())
12059 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
12061 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
12062 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
12064 if (OpVT.getVectorElementType() == MVT::i1)
12065 return Insert1BitVector(Op, DAG);
12070 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
12071 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
12072 // one of the above mentioned nodes. It has to be wrapped because otherwise
12073 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
12074 // be used to form addressing mode. These wrapped nodes will be selected
12077 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
12078 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
12080 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12081 // global base reg.
12082 unsigned char OpFlag = 0;
12083 unsigned WrapperKind = X86ISD::Wrapper;
12084 CodeModel::Model M = DAG.getTarget().getCodeModel();
12086 if (Subtarget->isPICStyleRIPRel() &&
12087 (M == CodeModel::Small || M == CodeModel::Kernel))
12088 WrapperKind = X86ISD::WrapperRIP;
12089 else if (Subtarget->isPICStyleGOT())
12090 OpFlag = X86II::MO_GOTOFF;
12091 else if (Subtarget->isPICStyleStubPIC())
12092 OpFlag = X86II::MO_PIC_BASE_OFFSET;
12094 auto PtrVT = getPointerTy(DAG.getDataLayout());
12095 SDValue Result = DAG.getTargetConstantPool(
12096 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
12098 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12099 // With PIC, the address is actually $g + Offset.
12102 DAG.getNode(ISD::ADD, DL, PtrVT,
12103 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12109 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
12110 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
12112 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12113 // global base reg.
12114 unsigned char OpFlag = 0;
12115 unsigned WrapperKind = X86ISD::Wrapper;
12116 CodeModel::Model M = DAG.getTarget().getCodeModel();
12118 if (Subtarget->isPICStyleRIPRel() &&
12119 (M == CodeModel::Small || M == CodeModel::Kernel))
12120 WrapperKind = X86ISD::WrapperRIP;
12121 else if (Subtarget->isPICStyleGOT())
12122 OpFlag = X86II::MO_GOTOFF;
12123 else if (Subtarget->isPICStyleStubPIC())
12124 OpFlag = X86II::MO_PIC_BASE_OFFSET;
12126 auto PtrVT = getPointerTy(DAG.getDataLayout());
12127 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
12129 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12131 // With PIC, the address is actually $g + Offset.
12134 DAG.getNode(ISD::ADD, DL, PtrVT,
12135 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12141 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
12142 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
12144 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12145 // global base reg.
12146 unsigned char OpFlag = 0;
12147 unsigned WrapperKind = X86ISD::Wrapper;
12148 CodeModel::Model M = DAG.getTarget().getCodeModel();
12150 if (Subtarget->isPICStyleRIPRel() &&
12151 (M == CodeModel::Small || M == CodeModel::Kernel)) {
12152 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
12153 OpFlag = X86II::MO_GOTPCREL;
12154 WrapperKind = X86ISD::WrapperRIP;
12155 } else if (Subtarget->isPICStyleGOT()) {
12156 OpFlag = X86II::MO_GOT;
12157 } else if (Subtarget->isPICStyleStubPIC()) {
12158 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
12159 } else if (Subtarget->isPICStyleStubNoDynamic()) {
12160 OpFlag = X86II::MO_DARWIN_NONLAZY;
12163 auto PtrVT = getPointerTy(DAG.getDataLayout());
12164 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
12167 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12169 // With PIC, the address is actually $g + Offset.
12170 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
12171 !Subtarget->is64Bit()) {
12173 DAG.getNode(ISD::ADD, DL, PtrVT,
12174 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12177 // For symbols that require a load from a stub to get the address, emit the
12179 if (isGlobalStubReference(OpFlag))
12180 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
12181 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12182 false, false, false, 0);
12188 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12189 // Create the TargetBlockAddressAddress node.
12190 unsigned char OpFlags =
12191 Subtarget->ClassifyBlockAddressReference();
12192 CodeModel::Model M = DAG.getTarget().getCodeModel();
12193 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12194 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12196 auto PtrVT = getPointerTy(DAG.getDataLayout());
12197 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
12199 if (Subtarget->isPICStyleRIPRel() &&
12200 (M == CodeModel::Small || M == CodeModel::Kernel))
12201 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12203 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12205 // With PIC, the address is actually $g + Offset.
12206 if (isGlobalRelativeToPICBase(OpFlags)) {
12207 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12208 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12215 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
12216 int64_t Offset, SelectionDAG &DAG) const {
12217 // Create the TargetGlobalAddress node, folding in the constant
12218 // offset if it is legal.
12219 unsigned char OpFlags =
12220 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
12221 CodeModel::Model M = DAG.getTarget().getCodeModel();
12222 auto PtrVT = getPointerTy(DAG.getDataLayout());
12224 if (OpFlags == X86II::MO_NO_FLAG &&
12225 X86::isOffsetSuitableForCodeModel(Offset, M)) {
12226 // A direct static reference to a global.
12227 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
12230 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
12233 if (Subtarget->isPICStyleRIPRel() &&
12234 (M == CodeModel::Small || M == CodeModel::Kernel))
12235 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12237 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12239 // With PIC, the address is actually $g + Offset.
12240 if (isGlobalRelativeToPICBase(OpFlags)) {
12241 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12242 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12245 // For globals that require a load from a stub to get the address, emit the
12247 if (isGlobalStubReference(OpFlags))
12248 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
12249 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12250 false, false, false, 0);
12252 // If there was a non-zero offset that we didn't fold, create an explicit
12253 // addition for it.
12255 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
12256 DAG.getConstant(Offset, dl, PtrVT));
12262 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
12263 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
12264 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12265 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12269 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12270 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12271 unsigned char OperandFlags, bool LocalDynamic = false) {
12272 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12273 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12275 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12276 GA->getValueType(0),
12280 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12284 SDValue Ops[] = { Chain, TGA, *InFlag };
12285 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12287 SDValue Ops[] = { Chain, TGA };
12288 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12291 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12292 MFI->setAdjustsStack(true);
12293 MFI->setHasCalls(true);
12295 SDValue Flag = Chain.getValue(1);
12296 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12299 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12301 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12304 SDLoc dl(GA); // ? function entry point might be better
12305 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12306 DAG.getNode(X86ISD::GlobalBaseReg,
12307 SDLoc(), PtrVT), InFlag);
12308 InFlag = Chain.getValue(1);
12310 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12313 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12315 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12317 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12318 X86::RAX, X86II::MO_TLSGD);
12321 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12327 // Get the start address of the TLS block for this module.
12328 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12329 .getInfo<X86MachineFunctionInfo>();
12330 MFI->incNumLocalDynamicTLSAccesses();
12334 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12335 X86II::MO_TLSLD, /*LocalDynamic=*/true);
12338 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12339 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12340 InFlag = Chain.getValue(1);
12341 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12342 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12345 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12349 unsigned char OperandFlags = X86II::MO_DTPOFF;
12350 unsigned WrapperKind = X86ISD::Wrapper;
12351 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12352 GA->getValueType(0),
12353 GA->getOffset(), OperandFlags);
12354 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12356 // Add x@dtpoff with the base.
12357 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12360 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12361 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12362 const EVT PtrVT, TLSModel::Model model,
12363 bool is64Bit, bool isPIC) {
12366 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12367 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12368 is64Bit ? 257 : 256));
12370 SDValue ThreadPointer =
12371 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12372 MachinePointerInfo(Ptr), false, false, false, 0);
12374 unsigned char OperandFlags = 0;
12375 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
12377 unsigned WrapperKind = X86ISD::Wrapper;
12378 if (model == TLSModel::LocalExec) {
12379 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12380 } else if (model == TLSModel::InitialExec) {
12382 OperandFlags = X86II::MO_GOTTPOFF;
12383 WrapperKind = X86ISD::WrapperRIP;
12385 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12388 llvm_unreachable("Unexpected model");
12391 // emit "addl x@ntpoff,%eax" (local exec)
12392 // or "addl x@indntpoff,%eax" (initial exec)
12393 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12395 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12396 GA->getOffset(), OperandFlags);
12397 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12399 if (model == TLSModel::InitialExec) {
12400 if (isPIC && !is64Bit) {
12401 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12402 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12406 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12407 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12408 false, false, false, 0);
12411 // The address of the thread local variable is the add of the thread
12412 // pointer with the offset of the variable.
12413 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12417 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12419 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12421 // Cygwin uses emutls.
12422 // FIXME: It may be EmulatedTLS-generic also for X86-Android.
12423 if (Subtarget->isTargetWindowsCygwin())
12424 return LowerToTLSEmulatedModel(GA, DAG);
12426 const GlobalValue *GV = GA->getGlobal();
12427 auto PtrVT = getPointerTy(DAG.getDataLayout());
12429 if (Subtarget->isTargetELF()) {
12430 if (DAG.getTarget().Options.EmulatedTLS)
12431 return LowerToTLSEmulatedModel(GA, DAG);
12432 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12434 case TLSModel::GeneralDynamic:
12435 if (Subtarget->is64Bit())
12436 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12437 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12438 case TLSModel::LocalDynamic:
12439 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12440 Subtarget->is64Bit());
12441 case TLSModel::InitialExec:
12442 case TLSModel::LocalExec:
12443 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12444 DAG.getTarget().getRelocationModel() ==
12447 llvm_unreachable("Unknown TLS model.");
12450 if (Subtarget->isTargetDarwin()) {
12451 // Darwin only has one model of TLS. Lower to that.
12452 unsigned char OpFlag = 0;
12453 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12454 X86ISD::WrapperRIP : X86ISD::Wrapper;
12456 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12457 // global base reg.
12458 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12459 !Subtarget->is64Bit();
12461 OpFlag = X86II::MO_TLVP_PIC_BASE;
12463 OpFlag = X86II::MO_TLVP;
12465 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12466 GA->getValueType(0),
12467 GA->getOffset(), OpFlag);
12468 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12470 // With PIC32, the address is actually $g + Offset.
12472 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12473 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12476 // Lowering the machine isd will make sure everything is in the right
12478 SDValue Chain = DAG.getEntryNode();
12479 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12480 SDValue Args[] = { Chain, Offset };
12481 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12483 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12484 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12485 MFI->setAdjustsStack(true);
12487 // And our return value (tls address) is in the standard call return value
12489 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12490 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12493 if (Subtarget->isTargetKnownWindowsMSVC() ||
12494 Subtarget->isTargetWindowsGNU()) {
12495 // Just use the implicit TLS architecture
12496 // Need to generate someting similar to:
12497 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12499 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
12500 // mov rcx, qword [rdx+rcx*8]
12501 // mov eax, .tls$:tlsvar
12502 // [rax+rcx] contains the address
12503 // Windows 64bit: gs:0x58
12504 // Windows 32bit: fs:__tls_array
12507 SDValue Chain = DAG.getEntryNode();
12509 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12510 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12511 // use its literal value of 0x2C.
12512 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12513 ? Type::getInt8PtrTy(*DAG.getContext(),
12515 : Type::getInt32PtrTy(*DAG.getContext(),
12518 SDValue TlsArray = Subtarget->is64Bit()
12519 ? DAG.getIntPtrConstant(0x58, dl)
12520 : (Subtarget->isTargetWindowsGNU()
12521 ? DAG.getIntPtrConstant(0x2C, dl)
12522 : DAG.getExternalSymbol("_tls_array", PtrVT));
12524 SDValue ThreadPointer =
12525 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12529 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12530 res = ThreadPointer;
12532 // Load the _tls_index variable
12533 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12534 if (Subtarget->is64Bit())
12535 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12536 MachinePointerInfo(), MVT::i32, false, false,
12539 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12542 auto &DL = DAG.getDataLayout();
12544 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12545 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12547 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12550 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12553 // Get the offset of start of .tls section
12554 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12555 GA->getValueType(0),
12556 GA->getOffset(), X86II::MO_SECREL);
12557 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12559 // The address of the thread local variable is the add of the thread
12560 // pointer with the offset of the variable.
12561 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12564 llvm_unreachable("TLS not implemented for this target.");
12567 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12568 /// and take a 2 x i32 value to shift plus a shift amount.
12569 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12570 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12571 MVT VT = Op.getSimpleValueType();
12572 unsigned VTBits = VT.getSizeInBits();
12574 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12575 SDValue ShOpLo = Op.getOperand(0);
12576 SDValue ShOpHi = Op.getOperand(1);
12577 SDValue ShAmt = Op.getOperand(2);
12578 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12579 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12581 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12582 DAG.getConstant(VTBits - 1, dl, MVT::i8));
12583 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12584 DAG.getConstant(VTBits - 1, dl, MVT::i8))
12585 : DAG.getConstant(0, dl, VT);
12587 SDValue Tmp2, Tmp3;
12588 if (Op.getOpcode() == ISD::SHL_PARTS) {
12589 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12590 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12592 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12593 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12596 // If the shift amount is larger or equal than the width of a part we can't
12597 // rely on the results of shld/shrd. Insert a test and select the appropriate
12598 // values for large shift amounts.
12599 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12600 DAG.getConstant(VTBits, dl, MVT::i8));
12601 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12602 AndNode, DAG.getConstant(0, dl, MVT::i8));
12605 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12606 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12607 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12609 if (Op.getOpcode() == ISD::SHL_PARTS) {
12610 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12611 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12613 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12614 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12617 SDValue Ops[2] = { Lo, Hi };
12618 return DAG.getMergeValues(Ops, dl);
12621 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12622 SelectionDAG &DAG) const {
12623 SDValue Src = Op.getOperand(0);
12624 MVT SrcVT = Src.getSimpleValueType();
12625 MVT VT = Op.getSimpleValueType();
12628 if (SrcVT.isVector()) {
12629 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12630 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12631 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12632 DAG.getUNDEF(SrcVT)));
12634 if (SrcVT.getVectorElementType() == MVT::i1) {
12635 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12636 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12637 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12642 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12643 "Unknown SINT_TO_FP to lower!");
12645 // These are really Legal; return the operand so the caller accepts it as
12647 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12649 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12650 Subtarget->is64Bit()) {
12654 unsigned Size = SrcVT.getSizeInBits()/8;
12655 MachineFunction &MF = DAG.getMachineFunction();
12656 auto PtrVT = getPointerTy(MF.getDataLayout());
12657 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12658 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12659 SDValue Chain = DAG.getStore(
12660 DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12661 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12663 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12666 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12668 SelectionDAG &DAG) const {
12672 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12674 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12676 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12678 unsigned ByteSize = SrcVT.getSizeInBits()/8;
12680 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12681 MachineMemOperand *MMO;
12683 int SSFI = FI->getIndex();
12684 MMO = DAG.getMachineFunction().getMachineMemOperand(
12685 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12686 MachineMemOperand::MOLoad, ByteSize, ByteSize);
12688 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12689 StackSlot = StackSlot.getOperand(1);
12691 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12692 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12694 Tys, Ops, SrcVT, MMO);
12697 Chain = Result.getValue(1);
12698 SDValue InFlag = Result.getValue(2);
12700 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12701 // shouldn't be necessary except that RFP cannot be live across
12702 // multiple blocks. When stackifier is fixed, they can be uncoupled.
12703 MachineFunction &MF = DAG.getMachineFunction();
12704 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12705 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12706 auto PtrVT = getPointerTy(MF.getDataLayout());
12707 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12708 Tys = DAG.getVTList(MVT::Other);
12710 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12712 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12713 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12714 MachineMemOperand::MOStore, SSFISize, SSFISize);
12716 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12717 Ops, Op.getValueType(), MMO);
12718 Result = DAG.getLoad(
12719 Op.getValueType(), DL, Chain, StackSlot,
12720 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12721 false, false, false, 0);
12727 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12728 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12729 SelectionDAG &DAG) const {
12730 // This algorithm is not obvious. Here it is what we're trying to output:
12733 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12734 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12736 haddpd %xmm0, %xmm0
12738 pshufd $0x4e, %xmm0, %xmm1
12744 LLVMContext *Context = DAG.getContext();
12746 // Build some magic constants.
12747 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12748 Constant *C0 = ConstantDataVector::get(*Context, CV0);
12749 auto PtrVT = getPointerTy(DAG.getDataLayout());
12750 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12752 SmallVector<Constant*,2> CV1;
12754 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12755 APInt(64, 0x4330000000000000ULL))));
12757 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12758 APInt(64, 0x4530000000000000ULL))));
12759 Constant *C1 = ConstantVector::get(CV1);
12760 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12762 // Load the 64-bit value into an XMM register.
12763 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12766 DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12767 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12768 false, false, false, 16);
12770 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12773 DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12774 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12775 false, false, false, 16);
12776 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12777 // TODO: Are there any fast-math-flags to propagate here?
12778 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12781 if (Subtarget->hasSSE3()) {
12782 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12783 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12785 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12786 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12788 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12789 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12792 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12793 DAG.getIntPtrConstant(0, dl));
12796 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12797 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12798 SelectionDAG &DAG) const {
12800 // FP constant to bias correct the final result.
12801 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12804 // Load the 32-bit value into an XMM register.
12805 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12808 // Zero out the upper parts of the register.
12809 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12811 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12812 DAG.getBitcast(MVT::v2f64, Load),
12813 DAG.getIntPtrConstant(0, dl));
12815 // Or the load with the bias.
12816 SDValue Or = DAG.getNode(
12817 ISD::OR, dl, MVT::v2i64,
12818 DAG.getBitcast(MVT::v2i64,
12819 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12820 DAG.getBitcast(MVT::v2i64,
12821 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12823 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12824 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12826 // Subtract the bias.
12827 // TODO: Are there any fast-math-flags to propagate here?
12828 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12830 // Handle final rounding.
12831 MVT DestVT = Op.getSimpleValueType();
12833 if (DestVT.bitsLT(MVT::f64))
12834 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12835 DAG.getIntPtrConstant(0, dl));
12836 if (DestVT.bitsGT(MVT::f64))
12837 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12839 // Handle final rounding.
12843 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12844 const X86Subtarget &Subtarget) {
12845 // The algorithm is the following:
12846 // #ifdef __SSE4_1__
12847 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12848 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12849 // (uint4) 0x53000000, 0xaa);
12851 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12852 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12854 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12855 // return (float4) lo + fhi;
12857 // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12858 // reassociate the two FADDs, and if we do that, the algorithm fails
12859 // spectacularly (PR24512).
12860 // FIXME: If we ever have some kind of Machine FMF, this should be marked
12861 // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12862 // there's also the MachineCombiner reassociations happening on Machine IR.
12863 if (DAG.getTarget().Options.UnsafeFPMath)
12867 SDValue V = Op->getOperand(0);
12868 MVT VecIntVT = V.getSimpleValueType();
12869 bool Is128 = VecIntVT == MVT::v4i32;
12870 MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12871 // If we convert to something else than the supported type, e.g., to v4f64,
12873 if (VecFloatVT != Op->getSimpleValueType(0))
12876 unsigned NumElts = VecIntVT.getVectorNumElements();
12877 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12878 "Unsupported custom type");
12879 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12881 // In the #idef/#else code, we have in common:
12882 // - The vector of constants:
12888 // Create the splat vector for 0x4b000000.
12889 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12890 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12891 CstLow, CstLow, CstLow, CstLow};
12892 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12893 makeArrayRef(&CstLowArray[0], NumElts));
12894 // Create the splat vector for 0x53000000.
12895 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12896 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12897 CstHigh, CstHigh, CstHigh, CstHigh};
12898 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12899 makeArrayRef(&CstHighArray[0], NumElts));
12901 // Create the right shift.
12902 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12903 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12904 CstShift, CstShift, CstShift, CstShift};
12905 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12906 makeArrayRef(&CstShiftArray[0], NumElts));
12907 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12910 if (Subtarget.hasSSE41()) {
12911 MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12912 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12913 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12914 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12915 // Low will be bitcasted right away, so do not bother bitcasting back to its
12917 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12918 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12919 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12920 // (uint4) 0x53000000, 0xaa);
12921 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12922 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12923 // High will be bitcasted right away, so do not bother bitcasting back to
12924 // its original type.
12925 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12926 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12928 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12929 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12930 CstMask, CstMask, CstMask);
12931 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12932 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12933 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12935 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12936 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12939 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12940 SDValue CstFAdd = DAG.getConstantFP(
12941 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12942 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12943 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12944 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12945 makeArrayRef(&CstFAddArray[0], NumElts));
12947 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12948 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12949 // TODO: Are there any fast-math-flags to propagate here?
12951 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12952 // return (float4) lo + fhi;
12953 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12954 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12957 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12958 SelectionDAG &DAG) const {
12959 SDValue N0 = Op.getOperand(0);
12960 MVT SVT = N0.getSimpleValueType();
12963 switch (SVT.SimpleTy) {
12965 llvm_unreachable("Custom UINT_TO_FP is not supported!");
12970 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12971 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12972 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12976 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12979 assert(Subtarget->hasAVX512());
12980 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12981 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12985 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12986 SelectionDAG &DAG) const {
12987 SDValue N0 = Op.getOperand(0);
12989 auto PtrVT = getPointerTy(DAG.getDataLayout());
12991 if (Op.getSimpleValueType().isVector())
12992 return lowerUINT_TO_FP_vec(Op, DAG);
12994 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12995 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12996 // the optimization here.
12997 if (DAG.SignBitIsZero(N0))
12998 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
13000 MVT SrcVT = N0.getSimpleValueType();
13001 MVT DstVT = Op.getSimpleValueType();
13003 if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
13004 (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
13005 // Conversions from unsigned i32 to f32/f64 are legal,
13006 // using VCVTUSI2SS/SD. Same for i64 in 64-bit mode.
13010 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13011 return LowerUINT_TO_FP_i64(Op, DAG);
13012 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13013 return LowerUINT_TO_FP_i32(Op, DAG);
13014 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13017 // Make a 64-bit buffer, and use it to build an FILD.
13018 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13019 if (SrcVT == MVT::i32) {
13020 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
13021 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
13022 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13023 StackSlot, MachinePointerInfo(),
13025 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
13026 OffsetSlot, MachinePointerInfo(),
13028 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13032 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13033 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13034 StackSlot, MachinePointerInfo(),
13036 // For i64 source, we need to add the appropriate power of 2 if the input
13037 // was negative. This is the same as the optimization in
13038 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13039 // we must be careful to do the computation in x87 extended precision, not
13040 // in SSE. (The generic code can't know it's OK to do this, or how to.)
13041 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13042 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
13043 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
13044 MachineMemOperand::MOLoad, 8, 8);
13046 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13047 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13048 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13051 APInt FF(32, 0x5F800000ULL);
13053 // Check whether the sign bit is set.
13054 SDValue SignSet = DAG.getSetCC(
13055 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
13056 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
13058 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13059 SDValue FudgePtr = DAG.getConstantPool(
13060 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
13062 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13063 SDValue Zero = DAG.getIntPtrConstant(0, dl);
13064 SDValue Four = DAG.getIntPtrConstant(4, dl);
13065 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13067 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
13069 // Load the value out, extending it from f32 to f80.
13070 // FIXME: Avoid the extend by constructing the right constant pool?
13071 SDValue Fudge = DAG.getExtLoad(
13072 ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
13073 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
13074 false, false, false, 4);
13075 // Extend everything to 80 bits to force it to be done on x87.
13076 // TODO: Are there any fast-math-flags to propagate here?
13077 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
13078 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
13079 DAG.getIntPtrConstant(0, dl));
13082 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
13083 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
13084 // just return an <SDValue(), SDValue()> pair.
13085 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
13086 // to i16, i32 or i64, and we lower it to a legal sequence.
13087 // If lowered to the final integer result we return a <result, SDValue()> pair.
13088 // Otherwise we lower it to a sequence ending with a FIST, return a
13089 // <FIST, StackSlot> pair, and the caller is responsible for loading
13090 // the final integer result from StackSlot.
13091 std::pair<SDValue,SDValue>
13092 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
13093 bool IsSigned, bool IsReplace) const {
13096 EVT DstTy = Op.getValueType();
13097 EVT TheVT = Op.getOperand(0).getValueType();
13098 auto PtrVT = getPointerTy(DAG.getDataLayout());
13100 if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
13101 // f16 must be promoted before using the lowering in this routine.
13102 // fp128 does not use this lowering.
13103 return std::make_pair(SDValue(), SDValue());
13106 // If using FIST to compute an unsigned i64, we'll need some fixup
13107 // to handle values above the maximum signed i64. A FIST is always
13108 // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
13109 bool UnsignedFixup = !IsSigned &&
13110 DstTy == MVT::i64 &&
13111 (!Subtarget->is64Bit() ||
13112 !isScalarFPTypeInSSEReg(TheVT));
13114 if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
13115 // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
13116 // The low 32 bits of the fist result will have the correct uint32 result.
13117 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
13121 assert(DstTy.getSimpleVT() <= MVT::i64 &&
13122 DstTy.getSimpleVT() >= MVT::i16 &&
13123 "Unknown FP_TO_INT to lower!");
13125 // These are really Legal.
13126 if (DstTy == MVT::i32 &&
13127 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13128 return std::make_pair(SDValue(), SDValue());
13129 if (Subtarget->is64Bit() &&
13130 DstTy == MVT::i64 &&
13131 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13132 return std::make_pair(SDValue(), SDValue());
13134 // We lower FP->int64 into FISTP64 followed by a load from a temporary
13136 MachineFunction &MF = DAG.getMachineFunction();
13137 unsigned MemSize = DstTy.getSizeInBits()/8;
13138 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13139 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13142 switch (DstTy.getSimpleVT().SimpleTy) {
13143 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
13144 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
13145 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
13146 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
13149 SDValue Chain = DAG.getEntryNode();
13150 SDValue Value = Op.getOperand(0);
13151 SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
13153 if (UnsignedFixup) {
13155 // Conversion to unsigned i64 is implemented with a select,
13156 // depending on whether the source value fits in the range
13157 // of a signed i64. Let Thresh be the FP equivalent of
13158 // 0x8000000000000000ULL.
13160 // Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
13161 // FistSrc = (Value < Thresh) ? Value : (Value - Thresh);
13162 // Fist-to-mem64 FistSrc
13163 // Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
13164 // to XOR'ing the high 32 bits with Adjust.
13166 // Being a power of 2, Thresh is exactly representable in all FP formats.
13167 // For X87 we'd like to use the smallest FP type for this constant, but
13168 // for DAG type consistency we have to match the FP operand type.
13170 APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
13171 LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
13172 bool LosesInfo = false;
13173 if (TheVT == MVT::f64)
13174 // The rounding mode is irrelevant as the conversion should be exact.
13175 Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
13177 else if (TheVT == MVT::f80)
13178 Status = Thresh.convert(APFloat::x87DoubleExtended,
13179 APFloat::rmNearestTiesToEven, &LosesInfo);
13181 assert(Status == APFloat::opOK && !LosesInfo &&
13182 "FP conversion should have been exact");
13184 SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
13186 SDValue Cmp = DAG.getSetCC(DL,
13187 getSetCCResultType(DAG.getDataLayout(),
13188 *DAG.getContext(), TheVT),
13189 Value, ThreshVal, ISD::SETLT);
13190 Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
13191 DAG.getConstant(0, DL, MVT::i32),
13192 DAG.getConstant(0x80000000, DL, MVT::i32));
13193 SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
13194 Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
13195 *DAG.getContext(), TheVT),
13196 Value, ThreshVal, ISD::SETLT);
13197 Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
13200 // FIXME This causes a redundant load/store if the SSE-class value is already
13201 // in memory, such as if it is on the callstack.
13202 if (isScalarFPTypeInSSEReg(TheVT)) {
13203 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
13204 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
13205 MachinePointerInfo::getFixedStack(MF, SSFI), false,
13207 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
13209 Chain, StackSlot, DAG.getValueType(TheVT)
13212 MachineMemOperand *MMO =
13213 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13214 MachineMemOperand::MOLoad, MemSize, MemSize);
13215 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
13216 Chain = Value.getValue(1);
13217 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13218 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13221 MachineMemOperand *MMO =
13222 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13223 MachineMemOperand::MOStore, MemSize, MemSize);
13225 if (UnsignedFixup) {
13227 // Insert the FIST, load its result as two i32's,
13228 // and XOR the high i32 with Adjust.
13230 SDValue FistOps[] = { Chain, Value, StackSlot };
13231 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13232 FistOps, DstTy, MMO);
13234 SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
13235 MachinePointerInfo(),
13236 false, false, false, 0);
13237 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
13238 DAG.getConstant(4, DL, PtrVT));
13240 SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
13241 MachinePointerInfo(),
13242 false, false, false, 0);
13243 High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
13245 if (Subtarget->is64Bit()) {
13246 // Join High32 and Low32 into a 64-bit result.
13247 // (High32 << 32) | Low32
13248 Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
13249 High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
13250 High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
13251 DAG.getConstant(32, DL, MVT::i8));
13252 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
13253 return std::make_pair(Result, SDValue());
13256 SDValue ResultOps[] = { Low32, High32 };
13258 SDValue pair = IsReplace
13259 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
13260 : DAG.getMergeValues(ResultOps, DL);
13261 return std::make_pair(pair, SDValue());
13263 // Build the FP_TO_INT*_IN_MEM
13264 SDValue Ops[] = { Chain, Value, StackSlot };
13265 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13267 return std::make_pair(FIST, StackSlot);
13271 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
13272 const X86Subtarget *Subtarget) {
13273 MVT VT = Op->getSimpleValueType(0);
13274 SDValue In = Op->getOperand(0);
13275 MVT InVT = In.getSimpleValueType();
13278 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13279 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
13281 // Optimize vectors in AVX mode:
13284 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
13285 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
13286 // Concat upper and lower parts.
13289 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
13290 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
13291 // Concat upper and lower parts.
13294 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13295 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13296 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13299 if (Subtarget->hasInt256())
13300 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13302 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13303 SDValue Undef = DAG.getUNDEF(InVT);
13304 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13305 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13306 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13308 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13309 VT.getVectorNumElements()/2);
13311 OpLo = DAG.getBitcast(HVT, OpLo);
13312 OpHi = DAG.getBitcast(HVT, OpHi);
13314 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13317 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13318 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13319 MVT VT = Op->getSimpleValueType(0);
13320 SDValue In = Op->getOperand(0);
13321 MVT InVT = In.getSimpleValueType();
13323 unsigned int NumElts = VT.getVectorNumElements();
13324 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13327 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13328 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13330 assert(InVT.getVectorElementType() == MVT::i1);
13331 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13333 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13335 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13337 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13338 if (VT.is512BitVector())
13340 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13343 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13344 SelectionDAG &DAG) {
13345 if (Subtarget->hasFp256())
13346 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13352 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13353 SelectionDAG &DAG) {
13355 MVT VT = Op.getSimpleValueType();
13356 SDValue In = Op.getOperand(0);
13357 MVT SVT = In.getSimpleValueType();
13359 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13360 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13362 if (Subtarget->hasFp256())
13363 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13366 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13367 VT.getVectorNumElements() != SVT.getVectorNumElements());
13371 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13373 MVT VT = Op.getSimpleValueType();
13374 SDValue In = Op.getOperand(0);
13375 MVT InVT = In.getSimpleValueType();
13377 if (VT == MVT::i1) {
13378 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13379 "Invalid scalar TRUNCATE operation");
13380 if (InVT.getSizeInBits() >= 32)
13382 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13383 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13385 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13386 "Invalid TRUNCATE operation");
13388 // move vector to mask - truncate solution for SKX
13389 if (VT.getVectorElementType() == MVT::i1) {
13390 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13391 Subtarget->hasBWI())
13392 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13393 if ((InVT.is256BitVector() || InVT.is128BitVector())
13394 && InVT.getScalarSizeInBits() <= 16 &&
13395 Subtarget->hasBWI() && Subtarget->hasVLX())
13396 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13397 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13398 Subtarget->hasDQI())
13399 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
13400 if ((InVT.is256BitVector() || InVT.is128BitVector())
13401 && InVT.getScalarSizeInBits() >= 32 &&
13402 Subtarget->hasDQI() && Subtarget->hasVLX())
13403 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
13406 if (VT.getVectorElementType() == MVT::i1) {
13407 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13408 unsigned NumElts = InVT.getVectorNumElements();
13409 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
13410 if (InVT.getSizeInBits() < 512) {
13411 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
13412 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13417 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
13418 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13419 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13422 // vpmovqb/w/d, vpmovdb/w, vpmovwb
13423 if (Subtarget->hasAVX512()) {
13424 // word to byte only under BWI
13425 if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13426 return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13427 DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13428 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13430 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13431 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13432 if (Subtarget->hasInt256()) {
13433 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13434 In = DAG.getBitcast(MVT::v8i32, In);
13435 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13437 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13438 DAG.getIntPtrConstant(0, DL));
13441 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13442 DAG.getIntPtrConstant(0, DL));
13443 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13444 DAG.getIntPtrConstant(2, DL));
13445 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13446 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13447 static const int ShufMask[] = {0, 2, 4, 6};
13448 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13451 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13452 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13453 if (Subtarget->hasInt256()) {
13454 In = DAG.getBitcast(MVT::v32i8, In);
13456 SmallVector<SDValue,32> pshufbMask;
13457 for (unsigned i = 0; i < 2; ++i) {
13458 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13459 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13460 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13461 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13462 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13463 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13464 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13465 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13466 for (unsigned j = 0; j < 8; ++j)
13467 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13469 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13470 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13471 In = DAG.getBitcast(MVT::v4i64, In);
13473 static const int ShufMask[] = {0, 2, -1, -1};
13474 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
13476 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13477 DAG.getIntPtrConstant(0, DL));
13478 return DAG.getBitcast(VT, In);
13481 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13482 DAG.getIntPtrConstant(0, DL));
13484 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13485 DAG.getIntPtrConstant(4, DL));
13487 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13488 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13490 // The PSHUFB mask:
13491 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13492 -1, -1, -1, -1, -1, -1, -1, -1};
13494 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13495 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13496 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13498 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13499 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13501 // The MOVLHPS Mask:
13502 static const int ShufMask2[] = {0, 1, 4, 5};
13503 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13504 return DAG.getBitcast(MVT::v8i16, res);
13507 // Handle truncation of V256 to V128 using shuffles.
13508 if (!VT.is128BitVector() || !InVT.is256BitVector())
13511 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13513 unsigned NumElems = VT.getVectorNumElements();
13514 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13516 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13517 // Prepare truncation shuffle mask
13518 for (unsigned i = 0; i != NumElems; ++i)
13519 MaskVec[i] = i * 2;
13520 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13521 DAG.getUNDEF(NVT), &MaskVec[0]);
13522 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13523 DAG.getIntPtrConstant(0, DL));
13526 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13527 SelectionDAG &DAG) const {
13528 assert(!Op.getSimpleValueType().isVector());
13530 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13531 /*IsSigned=*/ true, /*IsReplace=*/ false);
13532 SDValue FIST = Vals.first, StackSlot = Vals.second;
13533 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13534 if (!FIST.getNode())
13537 if (StackSlot.getNode())
13538 // Load the result.
13539 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13540 FIST, StackSlot, MachinePointerInfo(),
13541 false, false, false, 0);
13543 // The node is the result.
13547 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13548 SelectionDAG &DAG) const {
13549 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13550 /*IsSigned=*/ false, /*IsReplace=*/ false);
13551 SDValue FIST = Vals.first, StackSlot = Vals.second;
13552 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13553 if (!FIST.getNode())
13556 if (StackSlot.getNode())
13557 // Load the result.
13558 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13559 FIST, StackSlot, MachinePointerInfo(),
13560 false, false, false, 0);
13562 // The node is the result.
13566 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13568 MVT VT = Op.getSimpleValueType();
13569 SDValue In = Op.getOperand(0);
13570 MVT SVT = In.getSimpleValueType();
13572 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13574 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13575 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13576 In, DAG.getUNDEF(SVT)));
13579 /// The only differences between FABS and FNEG are the mask and the logic op.
13580 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13581 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13582 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13583 "Wrong opcode for lowering FABS or FNEG.");
13585 bool IsFABS = (Op.getOpcode() == ISD::FABS);
13587 // If this is a FABS and it has an FNEG user, bail out to fold the combination
13588 // into an FNABS. We'll lower the FABS after that if it is still in use.
13590 for (SDNode *User : Op->uses())
13591 if (User->getOpcode() == ISD::FNEG)
13595 MVT VT = Op.getSimpleValueType();
13597 bool IsF128 = (VT == MVT::f128);
13599 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13600 // decide if we should generate a 16-byte constant mask when we only need 4 or
13601 // 8 bytes for the scalar case.
13607 if (VT.isVector()) {
13609 EltVT = VT.getVectorElementType();
13610 NumElts = VT.getVectorNumElements();
13611 } else if (IsF128) {
13612 // SSE instructions are used for optimized f128 logical operations.
13613 LogicVT = MVT::f128;
13617 // There are no scalar bitwise logical SSE/AVX instructions, so we
13618 // generate a 16-byte vector constant and logic op even for the scalar case.
13619 // Using a 16-byte mask allows folding the load of the mask with
13620 // the logic op, so it can save (~4 bytes) on code size.
13621 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13623 NumElts = (VT == MVT::f64) ? 2 : 4;
13626 unsigned EltBits = EltVT.getSizeInBits();
13627 LLVMContext *Context = DAG.getContext();
13628 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13630 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13631 Constant *C = ConstantInt::get(*Context, MaskElt);
13632 C = ConstantVector::getSplat(NumElts, C);
13633 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13634 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13635 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13637 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13638 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13639 false, false, false, Alignment);
13641 SDValue Op0 = Op.getOperand(0);
13642 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13644 IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13645 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13647 if (VT.isVector() || IsF128)
13648 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13650 // For the scalar case extend to a 128-bit vector, perform the logic op,
13651 // and extract the scalar result back out.
13652 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13653 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13654 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13655 DAG.getIntPtrConstant(0, dl));
13658 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13659 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13660 LLVMContext *Context = DAG.getContext();
13661 SDValue Op0 = Op.getOperand(0);
13662 SDValue Op1 = Op.getOperand(1);
13664 MVT VT = Op.getSimpleValueType();
13665 MVT SrcVT = Op1.getSimpleValueType();
13666 bool IsF128 = (VT == MVT::f128);
13668 // If second operand is smaller, extend it first.
13669 if (SrcVT.bitsLT(VT)) {
13670 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13673 // And if it is bigger, shrink it first.
13674 if (SrcVT.bitsGT(VT)) {
13675 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13679 // At this point the operands and the result should have the same
13680 // type, and that won't be f80 since that is not custom lowered.
13681 assert((VT == MVT::f64 || VT == MVT::f32 || IsF128) &&
13682 "Unexpected type in LowerFCOPYSIGN");
13684 const fltSemantics &Sem =
13685 VT == MVT::f64 ? APFloat::IEEEdouble :
13686 (IsF128 ? APFloat::IEEEquad : APFloat::IEEEsingle);
13687 const unsigned SizeInBits = VT.getSizeInBits();
13689 SmallVector<Constant *, 4> CV(
13690 VT == MVT::f64 ? 2 : (IsF128 ? 1 : 4),
13691 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13693 // First, clear all bits but the sign bit from the second operand (sign).
13694 CV[0] = ConstantFP::get(*Context,
13695 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13696 Constant *C = ConstantVector::get(CV);
13697 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13698 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13700 // Perform all logic operations as 16-byte vectors because there are no
13701 // scalar FP logic instructions in SSE. This allows load folding of the
13702 // constants into the logic instructions.
13703 MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : (IsF128 ? MVT::f128 : MVT::v4f32);
13705 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13706 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13707 false, false, false, 16);
13709 Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13710 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13712 // Next, clear the sign bit from the first operand (magnitude).
13713 // If it's a constant, we can clear it here.
13714 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13715 APFloat APF = Op0CN->getValueAPF();
13716 // If the magnitude is a positive zero, the sign bit alone is enough.
13717 if (APF.isPosZero())
13718 return IsF128 ? SignBit :
13719 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13720 DAG.getIntPtrConstant(0, dl));
13722 CV[0] = ConstantFP::get(*Context, APF);
13724 CV[0] = ConstantFP::get(
13726 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13728 C = ConstantVector::get(CV);
13729 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13731 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13732 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13733 false, false, false, 16);
13734 // If the magnitude operand wasn't a constant, we need to AND out the sign.
13735 if (!isa<ConstantFPSDNode>(Op0)) {
13737 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13738 Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13740 // OR the magnitude value with the sign bit.
13741 Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13742 return IsF128 ? Val :
13743 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13744 DAG.getIntPtrConstant(0, dl));
13747 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13748 SDValue N0 = Op.getOperand(0);
13750 MVT VT = Op.getSimpleValueType();
13752 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13753 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13754 DAG.getConstant(1, dl, VT));
13755 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13758 // Check whether an OR'd tree is PTEST-able.
13759 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13760 SelectionDAG &DAG) {
13761 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13763 if (!Subtarget->hasSSE41())
13766 if (!Op->hasOneUse())
13769 SDNode *N = Op.getNode();
13772 SmallVector<SDValue, 8> Opnds;
13773 DenseMap<SDValue, unsigned> VecInMap;
13774 SmallVector<SDValue, 8> VecIns;
13775 EVT VT = MVT::Other;
13777 // Recognize a special case where a vector is casted into wide integer to
13779 Opnds.push_back(N->getOperand(0));
13780 Opnds.push_back(N->getOperand(1));
13782 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13783 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13784 // BFS traverse all OR'd operands.
13785 if (I->getOpcode() == ISD::OR) {
13786 Opnds.push_back(I->getOperand(0));
13787 Opnds.push_back(I->getOperand(1));
13788 // Re-evaluate the number of nodes to be traversed.
13789 e += 2; // 2 more nodes (LHS and RHS) are pushed.
13793 // Quit if a non-EXTRACT_VECTOR_ELT
13794 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13797 // Quit if without a constant index.
13798 SDValue Idx = I->getOperand(1);
13799 if (!isa<ConstantSDNode>(Idx))
13802 SDValue ExtractedFromVec = I->getOperand(0);
13803 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13804 if (M == VecInMap.end()) {
13805 VT = ExtractedFromVec.getValueType();
13806 // Quit if not 128/256-bit vector.
13807 if (!VT.is128BitVector() && !VT.is256BitVector())
13809 // Quit if not the same type.
13810 if (VecInMap.begin() != VecInMap.end() &&
13811 VT != VecInMap.begin()->first.getValueType())
13813 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13814 VecIns.push_back(ExtractedFromVec);
13816 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13819 assert((VT.is128BitVector() || VT.is256BitVector()) &&
13820 "Not extracted from 128-/256-bit vector.");
13822 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13824 for (DenseMap<SDValue, unsigned>::const_iterator
13825 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13826 // Quit if not all elements are used.
13827 if (I->second != FullMask)
13831 MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13833 // Cast all vectors into TestVT for PTEST.
13834 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13835 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13837 // If more than one full vectors are evaluated, OR them first before PTEST.
13838 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13839 // Each iteration will OR 2 nodes and append the result until there is only
13840 // 1 node left, i.e. the final OR'd value of all vectors.
13841 SDValue LHS = VecIns[Slot];
13842 SDValue RHS = VecIns[Slot + 1];
13843 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13846 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13847 VecIns.back(), VecIns.back());
13850 /// \brief return true if \c Op has a use that doesn't just read flags.
13851 static bool hasNonFlagsUse(SDValue Op) {
13852 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13854 SDNode *User = *UI;
13855 unsigned UOpNo = UI.getOperandNo();
13856 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13857 // Look pass truncate.
13858 UOpNo = User->use_begin().getOperandNo();
13859 User = *User->use_begin();
13862 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13863 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13869 /// Emit nodes that will be selected as "test Op0,Op0", or something
13871 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13872 SelectionDAG &DAG) const {
13873 if (Op.getValueType() == MVT::i1) {
13874 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13875 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13876 DAG.getConstant(0, dl, MVT::i8));
13878 // CF and OF aren't always set the way we want. Determine which
13879 // of these we need.
13880 bool NeedCF = false;
13881 bool NeedOF = false;
13884 case X86::COND_A: case X86::COND_AE:
13885 case X86::COND_B: case X86::COND_BE:
13888 case X86::COND_G: case X86::COND_GE:
13889 case X86::COND_L: case X86::COND_LE:
13890 case X86::COND_O: case X86::COND_NO: {
13891 // Check if we really need to set the
13892 // Overflow flag. If NoSignedWrap is present
13893 // that is not actually needed.
13894 switch (Op->getOpcode()) {
13899 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13900 if (BinNode->Flags.hasNoSignedWrap())
13910 // See if we can use the EFLAGS value from the operand instead of
13911 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13912 // we prove that the arithmetic won't overflow, we can't use OF or CF.
13913 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13914 // Emit a CMP with 0, which is the TEST pattern.
13915 //if (Op.getValueType() == MVT::i1)
13916 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13917 // DAG.getConstant(0, MVT::i1));
13918 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13919 DAG.getConstant(0, dl, Op.getValueType()));
13921 unsigned Opcode = 0;
13922 unsigned NumOperands = 0;
13924 // Truncate operations may prevent the merge of the SETCC instruction
13925 // and the arithmetic instruction before it. Attempt to truncate the operands
13926 // of the arithmetic instruction and use a reduced bit-width instruction.
13927 bool NeedTruncation = false;
13928 SDValue ArithOp = Op;
13929 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13930 SDValue Arith = Op->getOperand(0);
13931 // Both the trunc and the arithmetic op need to have one user each.
13932 if (Arith->hasOneUse())
13933 switch (Arith.getOpcode()) {
13940 NeedTruncation = true;
13946 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13947 // which may be the result of a CAST. We use the variable 'Op', which is the
13948 // non-casted variable when we check for possible users.
13949 switch (ArithOp.getOpcode()) {
13951 // Due to an isel shortcoming, be conservative if this add is likely to be
13952 // selected as part of a load-modify-store instruction. When the root node
13953 // in a match is a store, isel doesn't know how to remap non-chain non-flag
13954 // uses of other nodes in the match, such as the ADD in this case. This
13955 // leads to the ADD being left around and reselected, with the result being
13956 // two adds in the output. Alas, even if none our users are stores, that
13957 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
13958 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
13959 // climbing the DAG back to the root, and it doesn't seem to be worth the
13961 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13962 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13963 if (UI->getOpcode() != ISD::CopyToReg &&
13964 UI->getOpcode() != ISD::SETCC &&
13965 UI->getOpcode() != ISD::STORE)
13968 if (ConstantSDNode *C =
13969 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13970 // An add of one will be selected as an INC.
13971 if (C->isOne() && !Subtarget->slowIncDec()) {
13972 Opcode = X86ISD::INC;
13977 // An add of negative one (subtract of one) will be selected as a DEC.
13978 if (C->isAllOnesValue() && !Subtarget->slowIncDec()) {
13979 Opcode = X86ISD::DEC;
13985 // Otherwise use a regular EFLAGS-setting add.
13986 Opcode = X86ISD::ADD;
13991 // If we have a constant logical shift that's only used in a comparison
13992 // against zero turn it into an equivalent AND. This allows turning it into
13993 // a TEST instruction later.
13994 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13995 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13996 EVT VT = Op.getValueType();
13997 unsigned BitWidth = VT.getSizeInBits();
13998 unsigned ShAmt = Op->getConstantOperandVal(1);
13999 if (ShAmt >= BitWidth) // Avoid undefined shifts.
14001 APInt Mask = ArithOp.getOpcode() == ISD::SRL
14002 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14003 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14004 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14006 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14007 DAG.getConstant(Mask, dl, VT));
14008 DAG.ReplaceAllUsesWith(Op, New);
14014 // If the primary and result isn't used, don't bother using X86ISD::AND,
14015 // because a TEST instruction will be better.
14016 if (!hasNonFlagsUse(Op))
14022 // Due to the ISEL shortcoming noted above, be conservative if this op is
14023 // likely to be selected as part of a load-modify-store instruction.
14024 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14025 UE = Op.getNode()->use_end(); UI != UE; ++UI)
14026 if (UI->getOpcode() == ISD::STORE)
14029 // Otherwise use a regular EFLAGS-setting instruction.
14030 switch (ArithOp.getOpcode()) {
14031 default: llvm_unreachable("unexpected operator!");
14032 case ISD::SUB: Opcode = X86ISD::SUB; break;
14033 case ISD::XOR: Opcode = X86ISD::XOR; break;
14034 case ISD::AND: Opcode = X86ISD::AND; break;
14036 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14037 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14038 if (EFLAGS.getNode())
14041 Opcode = X86ISD::OR;
14055 return SDValue(Op.getNode(), 1);
14061 // If we found that truncation is beneficial, perform the truncation and
14063 if (NeedTruncation) {
14064 EVT VT = Op.getValueType();
14065 SDValue WideVal = Op->getOperand(0);
14066 EVT WideVT = WideVal.getValueType();
14067 unsigned ConvertedOp = 0;
14068 // Use a target machine opcode to prevent further DAGCombine
14069 // optimizations that may separate the arithmetic operations
14070 // from the setcc node.
14071 switch (WideVal.getOpcode()) {
14073 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14074 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14075 case ISD::AND: ConvertedOp = X86ISD::AND; break;
14076 case ISD::OR: ConvertedOp = X86ISD::OR; break;
14077 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14081 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14082 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14083 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14084 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14085 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14091 // Emit a CMP with 0, which is the TEST pattern.
14092 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14093 DAG.getConstant(0, dl, Op.getValueType()));
14095 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14096 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
14098 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14099 DAG.ReplaceAllUsesWith(Op, New);
14100 return SDValue(New.getNode(), 1);
14103 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14105 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14106 SDLoc dl, SelectionDAG &DAG) const {
14107 if (isNullConstant(Op1))
14108 return EmitTest(Op0, X86CC, dl, DAG);
14110 assert(!(isa<ConstantSDNode>(Op1) && Op0.getValueType() == MVT::i1) &&
14111 "Unexpected comparison operation for MVT::i1 operands");
14113 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14114 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14115 // Do the comparison at i32 if it's smaller, besides the Atom case.
14116 // This avoids subregister aliasing issues. Keep the smaller reference
14117 // if we're optimizing for size, however, as that'll allow better folding
14118 // of memory operations.
14119 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14120 !DAG.getMachineFunction().getFunction()->optForMinSize() &&
14121 !Subtarget->isAtom()) {
14122 unsigned ExtendOp =
14123 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14124 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14125 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14127 // Use SUB instead of CMP to enable CSE between SUB and CMP.
14128 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14129 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14131 return SDValue(Sub.getNode(), 1);
14133 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14136 /// Convert a comparison if required by the subtarget.
14137 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14138 SelectionDAG &DAG) const {
14139 // If the subtarget does not support the FUCOMI instruction, floating-point
14140 // comparisons have to be converted.
14141 if (Subtarget->hasCMov() ||
14142 Cmp.getOpcode() != X86ISD::CMP ||
14143 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14144 !Cmp.getOperand(1).getValueType().isFloatingPoint())
14147 // The instruction selector will select an FUCOM instruction instead of
14148 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14149 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14150 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14152 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14153 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14154 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14155 DAG.getConstant(8, dl, MVT::i8));
14156 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14158 // Some 64-bit targets lack SAHF support, but they do support FCOMI.
14159 assert(Subtarget->hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?");
14160 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14163 /// The minimum architected relative accuracy is 2^-12. We need one
14164 /// Newton-Raphson step to have a good float result (24 bits of precision).
14165 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14166 DAGCombinerInfo &DCI,
14167 unsigned &RefinementSteps,
14168 bool &UseOneConstNR) const {
14169 EVT VT = Op.getValueType();
14170 const char *RecipOp;
14172 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
14173 // TODO: Add support for AVX512 (v16f32).
14174 // It is likely not profitable to do this for f64 because a double-precision
14175 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14176 // instructions: convert to single, rsqrtss, convert back to double, refine
14177 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14178 // along with FMA, this could be a throughput win.
14179 if (VT == MVT::f32 && Subtarget->hasSSE1())
14181 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14182 (VT == MVT::v8f32 && Subtarget->hasAVX()))
14183 RecipOp = "vec-sqrtf";
14187 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14188 if (!Recips.isEnabled(RecipOp))
14191 RefinementSteps = Recips.getRefinementSteps(RecipOp);
14192 UseOneConstNR = false;
14193 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14196 /// The minimum architected relative accuracy is 2^-12. We need one
14197 /// Newton-Raphson step to have a good float result (24 bits of precision).
14198 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14199 DAGCombinerInfo &DCI,
14200 unsigned &RefinementSteps) const {
14201 EVT VT = Op.getValueType();
14202 const char *RecipOp;
14204 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14205 // TODO: Add support for AVX512 (v16f32).
14206 // It is likely not profitable to do this for f64 because a double-precision
14207 // reciprocal estimate with refinement on x86 prior to FMA requires
14208 // 15 instructions: convert to single, rcpss, convert back to double, refine
14209 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14210 // along with FMA, this could be a throughput win.
14211 if (VT == MVT::f32 && Subtarget->hasSSE1())
14213 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14214 (VT == MVT::v8f32 && Subtarget->hasAVX()))
14215 RecipOp = "vec-divf";
14219 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14220 if (!Recips.isEnabled(RecipOp))
14223 RefinementSteps = Recips.getRefinementSteps(RecipOp);
14224 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14227 /// If we have at least two divisions that use the same divisor, convert to
14228 /// multplication by a reciprocal. This may need to be adjusted for a given
14229 /// CPU if a division's cost is not at least twice the cost of a multiplication.
14230 /// This is because we still need one division to calculate the reciprocal and
14231 /// then we need two multiplies by that reciprocal as replacements for the
14232 /// original divisions.
14233 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
14237 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14238 /// if it's possible.
14239 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14240 SDLoc dl, SelectionDAG &DAG) const {
14241 SDValue Op0 = And.getOperand(0);
14242 SDValue Op1 = And.getOperand(1);
14243 if (Op0.getOpcode() == ISD::TRUNCATE)
14244 Op0 = Op0.getOperand(0);
14245 if (Op1.getOpcode() == ISD::TRUNCATE)
14246 Op1 = Op1.getOperand(0);
14249 if (Op1.getOpcode() == ISD::SHL)
14250 std::swap(Op0, Op1);
14251 if (Op0.getOpcode() == ISD::SHL) {
14252 if (isOneConstant(Op0.getOperand(0))) {
14253 // If we looked past a truncate, check that it's only truncating away
14255 unsigned BitWidth = Op0.getValueSizeInBits();
14256 unsigned AndBitWidth = And.getValueSizeInBits();
14257 if (BitWidth > AndBitWidth) {
14259 DAG.computeKnownBits(Op0, Zeros, Ones);
14260 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
14264 RHS = Op0.getOperand(1);
14266 } else if (Op1.getOpcode() == ISD::Constant) {
14267 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
14268 uint64_t AndRHSVal = AndRHS->getZExtValue();
14269 SDValue AndLHS = Op0;
14271 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
14272 LHS = AndLHS.getOperand(0);
14273 RHS = AndLHS.getOperand(1);
14276 // Use BT if the immediate can't be encoded in a TEST instruction.
14277 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
14279 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
14283 if (LHS.getNode()) {
14284 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
14285 // instruction. Since the shift amount is in-range-or-undefined, we know
14286 // that doing a bittest on the i32 value is ok. We extend to i32 because
14287 // the encoding for the i16 version is larger than the i32 version.
14288 // Also promote i16 to i32 for performance / code size reason.
14289 if (LHS.getValueType() == MVT::i8 ||
14290 LHS.getValueType() == MVT::i16)
14291 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14293 // If the operand types disagree, extend the shift amount to match. Since
14294 // BT ignores high bits (like shifts) we can use anyextend.
14295 if (LHS.getValueType() != RHS.getValueType())
14296 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14298 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14299 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14300 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14301 DAG.getConstant(Cond, dl, MVT::i8), BT);
14307 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14309 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14314 // SSE Condition code mapping:
14323 switch (SetCCOpcode) {
14324 default: llvm_unreachable("Unexpected SETCC condition");
14326 case ISD::SETEQ: SSECC = 0; break;
14328 case ISD::SETGT: Swap = true; // Fallthrough
14330 case ISD::SETOLT: SSECC = 1; break;
14332 case ISD::SETGE: Swap = true; // Fallthrough
14334 case ISD::SETOLE: SSECC = 2; break;
14335 case ISD::SETUO: SSECC = 3; break;
14337 case ISD::SETNE: SSECC = 4; break;
14338 case ISD::SETULE: Swap = true; // Fallthrough
14339 case ISD::SETUGE: SSECC = 5; break;
14340 case ISD::SETULT: Swap = true; // Fallthrough
14341 case ISD::SETUGT: SSECC = 6; break;
14342 case ISD::SETO: SSECC = 7; break;
14344 case ISD::SETONE: SSECC = 8; break;
14347 std::swap(Op0, Op1);
14352 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14353 // ones, and then concatenate the result back.
14354 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14355 MVT VT = Op.getSimpleValueType();
14357 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14358 "Unsupported value type for operation");
14360 unsigned NumElems = VT.getVectorNumElements();
14362 SDValue CC = Op.getOperand(2);
14364 // Extract the LHS vectors
14365 SDValue LHS = Op.getOperand(0);
14366 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14367 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14369 // Extract the RHS vectors
14370 SDValue RHS = Op.getOperand(1);
14371 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14372 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14374 // Issue the operation on the smaller types and concatenate the result back
14375 MVT EltVT = VT.getVectorElementType();
14376 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14377 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14378 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14379 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14382 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14383 SDValue Op0 = Op.getOperand(0);
14384 SDValue Op1 = Op.getOperand(1);
14385 SDValue CC = Op.getOperand(2);
14386 MVT VT = Op.getSimpleValueType();
14389 assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14390 "Unexpected type for boolean compare operation");
14391 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14392 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14393 DAG.getConstant(-1, dl, VT));
14394 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14395 DAG.getConstant(-1, dl, VT));
14396 switch (SetCCOpcode) {
14397 default: llvm_unreachable("Unexpected SETCC condition");
14399 // (x == y) -> ~(x ^ y)
14400 return DAG.getNode(ISD::XOR, dl, VT,
14401 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14402 DAG.getConstant(-1, dl, VT));
14404 // (x != y) -> (x ^ y)
14405 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14408 // (x > y) -> (x & ~y)
14409 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14412 // (x < y) -> (~x & y)
14413 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14416 // (x <= y) -> (~x | y)
14417 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14420 // (x >=y) -> (x | ~y)
14421 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14425 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14426 const X86Subtarget *Subtarget) {
14427 SDValue Op0 = Op.getOperand(0);
14428 SDValue Op1 = Op.getOperand(1);
14429 SDValue CC = Op.getOperand(2);
14430 MVT VT = Op.getSimpleValueType();
14433 assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14434 Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14435 "Cannot set masked compare for this operation");
14437 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14439 bool Unsigned = false;
14442 switch (SetCCOpcode) {
14443 default: llvm_unreachable("Unexpected SETCC condition");
14444 case ISD::SETNE: SSECC = 4; break;
14445 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
14446 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14447 case ISD::SETLT: Swap = true; //fall-through
14448 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
14449 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14450 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14451 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
14452 case ISD::SETULE: Unsigned = true; //fall-through
14453 case ISD::SETLE: SSECC = 2; break;
14457 std::swap(Op0, Op1);
14459 return DAG.getNode(Opc, dl, VT, Op0, Op1);
14460 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14461 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14462 DAG.getConstant(SSECC, dl, MVT::i8));
14465 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14466 /// operand \p Op1. If non-trivial (for example because it's not constant)
14467 /// return an empty value.
14468 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14470 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14474 MVT VT = Op1.getSimpleValueType();
14475 MVT EVT = VT.getVectorElementType();
14476 unsigned n = VT.getVectorNumElements();
14477 SmallVector<SDValue, 8> ULTOp1;
14479 for (unsigned i = 0; i < n; ++i) {
14480 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14481 if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14484 // Avoid underflow.
14485 APInt Val = Elt->getAPIntValue();
14489 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14492 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14495 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14496 SelectionDAG &DAG) {
14497 SDValue Op0 = Op.getOperand(0);
14498 SDValue Op1 = Op.getOperand(1);
14499 SDValue CC = Op.getOperand(2);
14500 MVT VT = Op.getSimpleValueType();
14501 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14502 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14507 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14508 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14511 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14512 unsigned Opc = X86ISD::CMPP;
14513 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14514 assert(VT.getVectorNumElements() <= 16);
14515 Opc = X86ISD::CMPM;
14517 // In the two special cases we can't handle, emit two comparisons.
14520 unsigned CombineOpc;
14521 if (SetCCOpcode == ISD::SETUEQ) {
14522 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14524 assert(SetCCOpcode == ISD::SETONE);
14525 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14528 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14529 DAG.getConstant(CC0, dl, MVT::i8));
14530 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14531 DAG.getConstant(CC1, dl, MVT::i8));
14532 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14534 // Handle all other FP comparisons here.
14535 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14536 DAG.getConstant(SSECC, dl, MVT::i8));
14539 MVT VTOp0 = Op0.getSimpleValueType();
14540 assert(VTOp0 == Op1.getSimpleValueType() &&
14541 "Expected operands with same type!");
14542 assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14543 "Invalid number of packed elements for source and destination!");
14545 if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14546 // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14547 // legalizer to a wider vector type. In the case of 'vsetcc' nodes, the
14548 // legalizer firstly checks if the first operand in input to the setcc has
14549 // a legal type. If so, then it promotes the return type to that same type.
14550 // Otherwise, the return type is promoted to the 'next legal type' which,
14551 // for a vector of MVT::i1 is always a 128-bit integer vector type.
14553 // We reach this code only if the following two conditions are met:
14554 // 1. Both return type and operand type have been promoted to wider types
14555 // by the type legalizer.
14556 // 2. The original operand type has been promoted to a 256-bit vector.
14558 // Note that condition 2. only applies for AVX targets.
14559 SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14560 return DAG.getZExtOrTrunc(NewOp, dl, VT);
14563 // The non-AVX512 code below works under the assumption that source and
14564 // destination types are the same.
14565 assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14566 "Value types for source and destination must be the same!");
14568 // Break 256-bit integer vector compare into smaller ones.
14569 if (VT.is256BitVector() && !Subtarget->hasInt256())
14570 return Lower256IntVSETCC(Op, DAG);
14572 MVT OpVT = Op1.getSimpleValueType();
14573 if (OpVT.getVectorElementType() == MVT::i1)
14574 return LowerBoolVSETCC_AVX512(Op, DAG);
14576 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14577 if (Subtarget->hasAVX512()) {
14578 if (Op1.getSimpleValueType().is512BitVector() ||
14579 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14580 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14581 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14583 // In AVX-512 architecture setcc returns mask with i1 elements,
14584 // But there is no compare instruction for i8 and i16 elements in KNL.
14585 // We are not talking about 512-bit operands in this case, these
14586 // types are illegal.
14588 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14589 OpVT.getVectorElementType().getSizeInBits() >= 8))
14590 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14591 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14594 // Lower using XOP integer comparisons.
14595 if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14596 VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14597 // Translate compare code to XOP PCOM compare mode.
14598 unsigned CmpMode = 0;
14599 switch (SetCCOpcode) {
14600 default: llvm_unreachable("Unexpected SETCC condition");
14602 case ISD::SETLT: CmpMode = 0x00; break;
14604 case ISD::SETLE: CmpMode = 0x01; break;
14606 case ISD::SETGT: CmpMode = 0x02; break;
14608 case ISD::SETGE: CmpMode = 0x03; break;
14609 case ISD::SETEQ: CmpMode = 0x04; break;
14610 case ISD::SETNE: CmpMode = 0x05; break;
14613 // Are we comparing unsigned or signed integers?
14614 unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14615 ? X86ISD::VPCOMU : X86ISD::VPCOM;
14617 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14618 DAG.getConstant(CmpMode, dl, MVT::i8));
14621 // We are handling one of the integer comparisons here. Since SSE only has
14622 // GT and EQ comparisons for integer, swapping operands and multiple
14623 // operations may be required for some comparisons.
14625 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14626 bool Subus = false;
14628 switch (SetCCOpcode) {
14629 default: llvm_unreachable("Unexpected SETCC condition");
14630 case ISD::SETNE: Invert = true;
14631 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
14632 case ISD::SETLT: Swap = true;
14633 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
14634 case ISD::SETGE: Swap = true;
14635 case ISD::SETLE: Opc = X86ISD::PCMPGT;
14636 Invert = true; break;
14637 case ISD::SETULT: Swap = true;
14638 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14639 FlipSigns = true; break;
14640 case ISD::SETUGE: Swap = true;
14641 case ISD::SETULE: Opc = X86ISD::PCMPGT;
14642 FlipSigns = true; Invert = true; break;
14645 // Special case: Use min/max operations for SETULE/SETUGE
14646 MVT VET = VT.getVectorElementType();
14648 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14649 || (Subtarget->hasSSE2() && (VET == MVT::i8));
14652 switch (SetCCOpcode) {
14654 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14655 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14658 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14661 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14662 if (!MinMax && hasSubus) {
14663 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14665 // t = psubus Op0, Op1
14666 // pcmpeq t, <0..0>
14667 switch (SetCCOpcode) {
14669 case ISD::SETULT: {
14670 // If the comparison is against a constant we can turn this into a
14671 // setule. With psubus, setule does not require a swap. This is
14672 // beneficial because the constant in the register is no longer
14673 // destructed as the destination so it can be hoisted out of a loop.
14674 // Only do this pre-AVX since vpcmp* is no longer destructive.
14675 if (Subtarget->hasAVX())
14677 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14678 if (ULEOp1.getNode()) {
14680 Subus = true; Invert = false; Swap = false;
14684 // Psubus is better than flip-sign because it requires no inversion.
14685 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
14686 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14690 Opc = X86ISD::SUBUS;
14696 std::swap(Op0, Op1);
14698 // Check that the operation in question is available (most are plain SSE2,
14699 // but PCMPGTQ and PCMPEQQ have different requirements).
14700 if (VT == MVT::v2i64) {
14701 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14702 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14704 // First cast everything to the right type.
14705 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14706 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14708 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14709 // bits of the inputs before performing those operations. The lower
14710 // compare is always unsigned.
14713 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14715 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14716 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14717 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14718 Sign, Zero, Sign, Zero);
14720 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14721 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14723 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14724 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14725 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14727 // Create masks for only the low parts/high parts of the 64 bit integers.
14728 static const int MaskHi[] = { 1, 1, 3, 3 };
14729 static const int MaskLo[] = { 0, 0, 2, 2 };
14730 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14731 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14732 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14734 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14735 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14738 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14740 return DAG.getBitcast(VT, Result);
14743 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14744 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14745 // pcmpeqd + pshufd + pand.
14746 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14748 // First cast everything to the right type.
14749 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14750 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14753 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14755 // Make sure the lower and upper halves are both all-ones.
14756 static const int Mask[] = { 1, 0, 3, 2 };
14757 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14758 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14761 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14763 return DAG.getBitcast(VT, Result);
14767 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14768 // bits of the inputs before performing those operations.
14770 MVT EltVT = VT.getVectorElementType();
14771 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14773 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14774 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14777 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14779 // If the logical-not of the result is required, perform that now.
14781 Result = DAG.getNOT(dl, Result, VT);
14784 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14787 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14788 getZeroVector(VT, Subtarget, DAG, dl));
14793 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14795 MVT VT = Op.getSimpleValueType();
14797 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14799 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14800 && "SetCC type must be 8-bit or 1-bit integer");
14801 SDValue Op0 = Op.getOperand(0);
14802 SDValue Op1 = Op.getOperand(1);
14804 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14806 // Optimize to BT if possible.
14807 // Lower (X & (1 << N)) == 0 to BT(X, N).
14808 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14809 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14810 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14811 isNullConstant(Op1) &&
14812 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14813 if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
14815 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14820 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
14822 if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
14823 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14825 // If the input is a setcc, then reuse the input setcc or use a new one with
14826 // the inverted condition.
14827 if (Op0.getOpcode() == X86ISD::SETCC) {
14828 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14829 bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
14833 CCode = X86::GetOppositeBranchCondition(CCode);
14834 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14835 DAG.getConstant(CCode, dl, MVT::i8),
14836 Op0.getOperand(1));
14838 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14842 if ((Op0.getValueType() == MVT::i1) && isOneConstant(Op1) &&
14843 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14845 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14846 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14849 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14850 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14851 if (X86CC == X86::COND_INVALID)
14854 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14855 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14856 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14857 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14859 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14863 SDValue X86TargetLowering::LowerSETCCE(SDValue Op, SelectionDAG &DAG) const {
14864 SDValue LHS = Op.getOperand(0);
14865 SDValue RHS = Op.getOperand(1);
14866 SDValue Carry = Op.getOperand(2);
14867 SDValue Cond = Op.getOperand(3);
14870 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
14871 X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
14873 assert(Carry.getOpcode() != ISD::CARRY_FALSE);
14874 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14875 SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry);
14876 return DAG.getNode(X86ISD::SETCC, DL, Op.getValueType(),
14877 DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
14880 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14881 static bool isX86LogicalCmp(SDValue Op) {
14882 unsigned Opc = Op.getNode()->getOpcode();
14883 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14884 Opc == X86ISD::SAHF)
14886 if (Op.getResNo() == 1 &&
14887 (Opc == X86ISD::ADD ||
14888 Opc == X86ISD::SUB ||
14889 Opc == X86ISD::ADC ||
14890 Opc == X86ISD::SBB ||
14891 Opc == X86ISD::SMUL ||
14892 Opc == X86ISD::UMUL ||
14893 Opc == X86ISD::INC ||
14894 Opc == X86ISD::DEC ||
14895 Opc == X86ISD::OR ||
14896 Opc == X86ISD::XOR ||
14897 Opc == X86ISD::AND))
14900 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14906 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14907 if (V.getOpcode() != ISD::TRUNCATE)
14910 SDValue VOp0 = V.getOperand(0);
14911 unsigned InBits = VOp0.getValueSizeInBits();
14912 unsigned Bits = V.getValueSizeInBits();
14913 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14916 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14917 bool addTest = true;
14918 SDValue Cond = Op.getOperand(0);
14919 SDValue Op1 = Op.getOperand(1);
14920 SDValue Op2 = Op.getOperand(2);
14922 MVT VT = Op1.getSimpleValueType();
14925 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14926 // are available or VBLENDV if AVX is available.
14927 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14928 if (Cond.getOpcode() == ISD::SETCC &&
14929 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14930 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14931 VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
14932 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14933 int SSECC = translateX86FSETCC(
14934 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14937 if (Subtarget->hasAVX512()) {
14938 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14939 DAG.getConstant(SSECC, DL, MVT::i8));
14940 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14943 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14944 DAG.getConstant(SSECC, DL, MVT::i8));
14946 // If we have AVX, we can use a variable vector select (VBLENDV) instead
14947 // of 3 logic instructions for size savings and potentially speed.
14948 // Unfortunately, there is no scalar form of VBLENDV.
14950 // If either operand is a constant, don't try this. We can expect to
14951 // optimize away at least one of the logic instructions later in that
14952 // case, so that sequence would be faster than a variable blend.
14954 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14955 // uses XMM0 as the selection register. That may need just as many
14956 // instructions as the AND/ANDN/OR sequence due to register moves, so
14959 if (Subtarget->hasAVX() &&
14960 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14962 // Convert to vectors, do a VSELECT, and convert back to scalar.
14963 // All of the conversions should be optimized away.
14965 MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14966 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14967 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14968 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14970 MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14971 VCmp = DAG.getBitcast(VCmpVT, VCmp);
14973 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14975 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14976 VSel, DAG.getIntPtrConstant(0, DL));
14978 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14979 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14980 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14984 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
14986 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14987 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14988 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14989 Op1Scalar = Op1.getOperand(0);
14991 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14992 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14993 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14994 Op2Scalar = Op2.getOperand(0);
14995 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14996 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14997 Op1Scalar.getValueType(),
14998 Cond, Op1Scalar, Op2Scalar);
14999 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
15000 return DAG.getBitcast(VT, newSelect);
15001 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
15002 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
15003 DAG.getIntPtrConstant(0, DL));
15007 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
15008 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
15009 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15010 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
15011 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15012 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
15013 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
15015 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
15018 if (Cond.getOpcode() == ISD::SETCC) {
15019 SDValue NewCond = LowerSETCC(Cond, DAG);
15020 if (NewCond.getNode())
15024 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15025 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15026 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15027 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15028 if (Cond.getOpcode() == X86ISD::SETCC &&
15029 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15030 isNullConstant(Cond.getOperand(1).getOperand(1))) {
15031 SDValue Cmp = Cond.getOperand(1);
15033 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15035 if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15036 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15037 SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
15039 SDValue CmpOp0 = Cmp.getOperand(0);
15040 // Apply further optimizations for special cases
15041 // (select (x != 0), -1, 0) -> neg & sbb
15042 // (select (x == 0), 0, -1) -> neg & sbb
15043 if (isNullConstant(Y) &&
15044 (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
15045 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15046 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15047 DAG.getConstant(0, DL,
15048 CmpOp0.getValueType()),
15050 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15051 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15052 SDValue(Neg.getNode(), 1));
15056 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15057 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
15058 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15060 SDValue Res = // Res = 0 or -1.
15061 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15062 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
15064 if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
15065 Res = DAG.getNOT(DL, Res, Res.getValueType());
15067 if (!isNullConstant(Op2))
15068 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15073 // Look past (and (setcc_carry (cmp ...)), 1).
15074 if (Cond.getOpcode() == ISD::AND &&
15075 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15076 isOneConstant(Cond.getOperand(1)))
15077 Cond = Cond.getOperand(0);
15079 // If condition flag is set by a X86ISD::CMP, then use it as the condition
15080 // setting operand in place of the X86ISD::SETCC.
15081 unsigned CondOpcode = Cond.getOpcode();
15082 if (CondOpcode == X86ISD::SETCC ||
15083 CondOpcode == X86ISD::SETCC_CARRY) {
15084 CC = Cond.getOperand(0);
15086 SDValue Cmp = Cond.getOperand(1);
15087 unsigned Opc = Cmp.getOpcode();
15088 MVT VT = Op.getSimpleValueType();
15090 bool IllegalFPCMov = false;
15091 if (VT.isFloatingPoint() && !VT.isVector() &&
15092 !isScalarFPTypeInSSEReg(VT)) // FPStack?
15093 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15095 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15096 Opc == X86ISD::BT) { // FIXME
15100 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15101 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15102 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15103 Cond.getOperand(0).getValueType() != MVT::i8)) {
15104 SDValue LHS = Cond.getOperand(0);
15105 SDValue RHS = Cond.getOperand(1);
15106 unsigned X86Opcode;
15109 switch (CondOpcode) {
15110 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15111 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15112 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15113 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15114 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15115 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15116 default: llvm_unreachable("unexpected overflowing operator");
15118 if (CondOpcode == ISD::UMULO)
15119 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15122 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15124 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15126 if (CondOpcode == ISD::UMULO)
15127 Cond = X86Op.getValue(2);
15129 Cond = X86Op.getValue(1);
15131 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
15136 // Look past the truncate if the high bits are known zero.
15137 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15138 Cond = Cond.getOperand(0);
15140 // We know the result of AND is compared against zero. Try to match
15142 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15143 if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
15144 CC = NewSetCC.getOperand(0);
15145 Cond = NewSetCC.getOperand(1);
15152 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
15153 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15156 // a < b ? -1 : 0 -> RES = ~setcc_carry
15157 // a < b ? 0 : -1 -> RES = setcc_carry
15158 // a >= b ? -1 : 0 -> RES = setcc_carry
15159 // a >= b ? 0 : -1 -> RES = ~setcc_carry
15160 if (Cond.getOpcode() == X86ISD::SUB) {
15161 Cond = ConvertCmpIfNecessary(Cond, DAG);
15162 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15164 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15165 (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15166 (isNullConstant(Op1) || isNullConstant(Op2))) {
15167 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15168 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15170 if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
15171 return DAG.getNOT(DL, Res, Res.getValueType());
15176 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15177 // widen the cmov and push the truncate through. This avoids introducing a new
15178 // branch during isel and doesn't add any extensions.
15179 if (Op.getValueType() == MVT::i8 &&
15180 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15181 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15182 if (T1.getValueType() == T2.getValueType() &&
15183 // Blacklist CopyFromReg to avoid partial register stalls.
15184 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15185 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15186 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15187 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15191 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15192 // condition is true.
15193 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15194 SDValue Ops[] = { Op2, Op1, CC, Cond };
15195 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15198 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
15199 const X86Subtarget *Subtarget,
15200 SelectionDAG &DAG) {
15201 MVT VT = Op->getSimpleValueType(0);
15202 SDValue In = Op->getOperand(0);
15203 MVT InVT = In.getSimpleValueType();
15204 MVT VTElt = VT.getVectorElementType();
15205 MVT InVTElt = InVT.getVectorElementType();
15209 if ((InVTElt == MVT::i1) &&
15210 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15211 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15213 ((Subtarget->hasBWI() && VT.is512BitVector() &&
15214 VTElt.getSizeInBits() <= 16)) ||
15216 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15217 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15219 ((Subtarget->hasDQI() && VT.is512BitVector() &&
15220 VTElt.getSizeInBits() >= 32))))
15221 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15223 unsigned int NumElts = VT.getVectorNumElements();
15225 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
15228 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15229 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15230 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15231 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15234 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15235 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
15237 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
15240 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
15242 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
15243 if (VT.is512BitVector())
15245 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
15248 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
15249 const X86Subtarget *Subtarget,
15250 SelectionDAG &DAG) {
15251 SDValue In = Op->getOperand(0);
15252 MVT VT = Op->getSimpleValueType(0);
15253 MVT InVT = In.getSimpleValueType();
15254 assert(VT.getSizeInBits() == InVT.getSizeInBits());
15256 MVT InSVT = InVT.getVectorElementType();
15257 assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
15259 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
15261 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
15266 // SSE41 targets can use the pmovsx* instructions directly.
15267 if (Subtarget->hasSSE41())
15268 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15270 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
15274 // As SRAI is only available on i16/i32 types, we expand only up to i32
15275 // and handle i64 separately.
15276 while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
15277 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
15278 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
15279 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
15280 Curr = DAG.getBitcast(CurrVT, Curr);
15283 SDValue SignExt = Curr;
15284 if (CurrVT != InVT) {
15285 unsigned SignExtShift =
15286 CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
15287 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15288 DAG.getConstant(SignExtShift, dl, MVT::i8));
15294 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
15295 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15296 DAG.getConstant(31, dl, MVT::i8));
15297 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
15298 return DAG.getBitcast(VT, Ext);
15304 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15305 SelectionDAG &DAG) {
15306 MVT VT = Op->getSimpleValueType(0);
15307 SDValue In = Op->getOperand(0);
15308 MVT InVT = In.getSimpleValueType();
15311 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15312 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15314 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15315 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15316 (VT != MVT::v16i16 || InVT != MVT::v16i8))
15319 if (Subtarget->hasInt256())
15320 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15322 // Optimize vectors in AVX mode
15323 // Sign extend v8i16 to v8i32 and
15326 // Divide input vector into two parts
15327 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15328 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15329 // concat the vectors to original VT
15331 unsigned NumElems = InVT.getVectorNumElements();
15332 SDValue Undef = DAG.getUNDEF(InVT);
15334 SmallVector<int,8> ShufMask1(NumElems, -1);
15335 for (unsigned i = 0; i != NumElems/2; ++i)
15338 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15340 SmallVector<int,8> ShufMask2(NumElems, -1);
15341 for (unsigned i = 0; i != NumElems/2; ++i)
15342 ShufMask2[i] = i + NumElems/2;
15344 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15346 MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15347 VT.getVectorNumElements()/2);
15349 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15350 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15352 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15355 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15356 // may emit an illegal shuffle but the expansion is still better than scalar
15357 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15358 // we'll emit a shuffle and a arithmetic shift.
15359 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15360 // TODO: It is possible to support ZExt by zeroing the undef values during
15361 // the shuffle phase or after the shuffle.
15362 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15363 SelectionDAG &DAG) {
15364 MVT RegVT = Op.getSimpleValueType();
15365 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15366 assert(RegVT.isInteger() &&
15367 "We only custom lower integer vector sext loads.");
15369 // Nothing useful we can do without SSE2 shuffles.
15370 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15372 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15374 EVT MemVT = Ld->getMemoryVT();
15375 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15376 unsigned RegSz = RegVT.getSizeInBits();
15378 ISD::LoadExtType Ext = Ld->getExtensionType();
15380 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15381 && "Only anyext and sext are currently implemented.");
15382 assert(MemVT != RegVT && "Cannot extend to the same type");
15383 assert(MemVT.isVector() && "Must load a vector from memory");
15385 unsigned NumElems = RegVT.getVectorNumElements();
15386 unsigned MemSz = MemVT.getSizeInBits();
15387 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15389 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15390 // The only way in which we have a legal 256-bit vector result but not the
15391 // integer 256-bit operations needed to directly lower a sextload is if we
15392 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15393 // a 128-bit vector and a normal sign_extend to 256-bits that should get
15394 // correctly legalized. We do this late to allow the canonical form of
15395 // sextload to persist throughout the rest of the DAG combiner -- it wants
15396 // to fold together any extensions it can, and so will fuse a sign_extend
15397 // of an sextload into a sextload targeting a wider value.
15399 if (MemSz == 128) {
15400 // Just switch this to a normal load.
15401 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15402 "it must be a legal 128-bit vector "
15404 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15405 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15406 Ld->isInvariant(), Ld->getAlignment());
15408 assert(MemSz < 128 &&
15409 "Can't extend a type wider than 128 bits to a 256 bit vector!");
15410 // Do an sext load to a 128-bit vector type. We want to use the same
15411 // number of elements, but elements half as wide. This will end up being
15412 // recursively lowered by this routine, but will succeed as we definitely
15413 // have all the necessary features if we're using AVX1.
15415 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15416 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15418 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15419 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15420 Ld->isNonTemporal(), Ld->isInvariant(),
15421 Ld->getAlignment());
15424 // Replace chain users with the new chain.
15425 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15426 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15428 // Finally, do a normal sign-extend to the desired register.
15429 return DAG.getSExtOrTrunc(Load, dl, RegVT);
15432 // All sizes must be a power of two.
15433 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15434 "Non-power-of-two elements are not custom lowered!");
15436 // Attempt to load the original value using scalar loads.
15437 // Find the largest scalar type that divides the total loaded size.
15438 MVT SclrLoadTy = MVT::i8;
15439 for (MVT Tp : MVT::integer_valuetypes()) {
15440 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15445 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15446 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15448 SclrLoadTy = MVT::f64;
15450 // Calculate the number of scalar loads that we need to perform
15451 // in order to load our vector from memory.
15452 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15454 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15455 "Can only lower sext loads with a single scalar load!");
15457 unsigned loadRegZize = RegSz;
15458 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15461 // Represent our vector as a sequence of elements which are the
15462 // largest scalar that we can load.
15463 EVT LoadUnitVecVT = EVT::getVectorVT(
15464 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15466 // Represent the data using the same element type that is stored in
15467 // memory. In practice, we ''widen'' MemVT.
15469 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15470 loadRegZize / MemVT.getScalarSizeInBits());
15472 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15473 "Invalid vector type");
15475 // We can't shuffle using an illegal type.
15476 assert(TLI.isTypeLegal(WideVecVT) &&
15477 "We only lower types that form legal widened vector types");
15479 SmallVector<SDValue, 8> Chains;
15480 SDValue Ptr = Ld->getBasePtr();
15481 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15482 TLI.getPointerTy(DAG.getDataLayout()));
15483 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15485 for (unsigned i = 0; i < NumLoads; ++i) {
15486 // Perform a single load.
15487 SDValue ScalarLoad =
15488 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15489 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15490 Ld->getAlignment());
15491 Chains.push_back(ScalarLoad.getValue(1));
15492 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15493 // another round of DAGCombining.
15495 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15497 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15498 ScalarLoad, DAG.getIntPtrConstant(i, dl));
15500 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15503 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15505 // Bitcast the loaded value to a vector of the original element type, in
15506 // the size of the target vector type.
15507 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15508 unsigned SizeRatio = RegSz / MemSz;
15510 if (Ext == ISD::SEXTLOAD) {
15511 // If we have SSE4.1, we can directly emit a VSEXT node.
15512 if (Subtarget->hasSSE41()) {
15513 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15514 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15518 // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15520 assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15521 "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15523 SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15524 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15528 // Redistribute the loaded elements into the different locations.
15529 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15530 for (unsigned i = 0; i != NumElems; ++i)
15531 ShuffleVec[i * SizeRatio] = i;
15533 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15534 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15536 // Bitcast to the requested type.
15537 Shuff = DAG.getBitcast(RegVT, Shuff);
15538 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15542 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15543 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15544 // from the AND / OR.
15545 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15546 Opc = Op.getOpcode();
15547 if (Opc != ISD::OR && Opc != ISD::AND)
15549 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15550 Op.getOperand(0).hasOneUse() &&
15551 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15552 Op.getOperand(1).hasOneUse());
15555 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15556 // 1 and that the SETCC node has a single use.
15557 static bool isXor1OfSetCC(SDValue Op) {
15558 if (Op.getOpcode() != ISD::XOR)
15560 if (isOneConstant(Op.getOperand(1)))
15561 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15562 Op.getOperand(0).hasOneUse();
15566 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15567 bool addTest = true;
15568 SDValue Chain = Op.getOperand(0);
15569 SDValue Cond = Op.getOperand(1);
15570 SDValue Dest = Op.getOperand(2);
15573 bool Inverted = false;
15575 if (Cond.getOpcode() == ISD::SETCC) {
15576 // Check for setcc([su]{add,sub,mul}o == 0).
15577 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15578 isNullConstant(Cond.getOperand(1)) &&
15579 Cond.getOperand(0).getResNo() == 1 &&
15580 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15581 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15582 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15583 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15584 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15585 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15587 Cond = Cond.getOperand(0);
15589 SDValue NewCond = LowerSETCC(Cond, DAG);
15590 if (NewCond.getNode())
15595 // FIXME: LowerXALUO doesn't handle these!!
15596 else if (Cond.getOpcode() == X86ISD::ADD ||
15597 Cond.getOpcode() == X86ISD::SUB ||
15598 Cond.getOpcode() == X86ISD::SMUL ||
15599 Cond.getOpcode() == X86ISD::UMUL)
15600 Cond = LowerXALUO(Cond, DAG);
15603 // Look pass (and (setcc_carry (cmp ...)), 1).
15604 if (Cond.getOpcode() == ISD::AND &&
15605 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15606 isOneConstant(Cond.getOperand(1)))
15607 Cond = Cond.getOperand(0);
15609 // If condition flag is set by a X86ISD::CMP, then use it as the condition
15610 // setting operand in place of the X86ISD::SETCC.
15611 unsigned CondOpcode = Cond.getOpcode();
15612 if (CondOpcode == X86ISD::SETCC ||
15613 CondOpcode == X86ISD::SETCC_CARRY) {
15614 CC = Cond.getOperand(0);
15616 SDValue Cmp = Cond.getOperand(1);
15617 unsigned Opc = Cmp.getOpcode();
15618 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15619 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15623 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15627 // These can only come from an arithmetic instruction with overflow,
15628 // e.g. SADDO, UADDO.
15629 Cond = Cond.getNode()->getOperand(1);
15635 CondOpcode = Cond.getOpcode();
15636 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15637 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15638 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15639 Cond.getOperand(0).getValueType() != MVT::i8)) {
15640 SDValue LHS = Cond.getOperand(0);
15641 SDValue RHS = Cond.getOperand(1);
15642 unsigned X86Opcode;
15645 // Keep this in sync with LowerXALUO, otherwise we might create redundant
15646 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15648 switch (CondOpcode) {
15649 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15651 if (isOneConstant(RHS)) {
15652 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15655 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15656 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15658 if (isOneConstant(RHS)) {
15659 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15662 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15663 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15664 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15665 default: llvm_unreachable("unexpected overflowing operator");
15668 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15669 if (CondOpcode == ISD::UMULO)
15670 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15673 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15675 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15677 if (CondOpcode == ISD::UMULO)
15678 Cond = X86Op.getValue(2);
15680 Cond = X86Op.getValue(1);
15682 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15686 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15687 SDValue Cmp = Cond.getOperand(0).getOperand(1);
15688 if (CondOpc == ISD::OR) {
15689 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15690 // two branches instead of an explicit OR instruction with a
15692 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15693 isX86LogicalCmp(Cmp)) {
15694 CC = Cond.getOperand(0).getOperand(0);
15695 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15696 Chain, Dest, CC, Cmp);
15697 CC = Cond.getOperand(1).getOperand(0);
15701 } else { // ISD::AND
15702 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15703 // two branches instead of an explicit AND instruction with a
15704 // separate test. However, we only do this if this block doesn't
15705 // have a fall-through edge, because this requires an explicit
15706 // jmp when the condition is false.
15707 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15708 isX86LogicalCmp(Cmp) &&
15709 Op.getNode()->hasOneUse()) {
15710 X86::CondCode CCode =
15711 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15712 CCode = X86::GetOppositeBranchCondition(CCode);
15713 CC = DAG.getConstant(CCode, dl, MVT::i8);
15714 SDNode *User = *Op.getNode()->use_begin();
15715 // Look for an unconditional branch following this conditional branch.
15716 // We need this because we need to reverse the successors in order
15717 // to implement FCMP_OEQ.
15718 if (User->getOpcode() == ISD::BR) {
15719 SDValue FalseBB = User->getOperand(1);
15721 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15722 assert(NewBR == User);
15726 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15727 Chain, Dest, CC, Cmp);
15728 X86::CondCode CCode =
15729 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15730 CCode = X86::GetOppositeBranchCondition(CCode);
15731 CC = DAG.getConstant(CCode, dl, MVT::i8);
15737 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15738 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15739 // It should be transformed during dag combiner except when the condition
15740 // is set by a arithmetics with overflow node.
15741 X86::CondCode CCode =
15742 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15743 CCode = X86::GetOppositeBranchCondition(CCode);
15744 CC = DAG.getConstant(CCode, dl, MVT::i8);
15745 Cond = Cond.getOperand(0).getOperand(1);
15747 } else if (Cond.getOpcode() == ISD::SETCC &&
15748 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15749 // For FCMP_OEQ, we can emit
15750 // two branches instead of an explicit AND instruction with a
15751 // separate test. However, we only do this if this block doesn't
15752 // have a fall-through edge, because this requires an explicit
15753 // jmp when the condition is false.
15754 if (Op.getNode()->hasOneUse()) {
15755 SDNode *User = *Op.getNode()->use_begin();
15756 // Look for an unconditional branch following this conditional branch.
15757 // We need this because we need to reverse the successors in order
15758 // to implement FCMP_OEQ.
15759 if (User->getOpcode() == ISD::BR) {
15760 SDValue FalseBB = User->getOperand(1);
15762 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15763 assert(NewBR == User);
15767 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15768 Cond.getOperand(0), Cond.getOperand(1));
15769 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15770 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15771 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15772 Chain, Dest, CC, Cmp);
15773 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15778 } else if (Cond.getOpcode() == ISD::SETCC &&
15779 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15780 // For FCMP_UNE, we can emit
15781 // two branches instead of an explicit AND instruction with a
15782 // separate test. However, we only do this if this block doesn't
15783 // have a fall-through edge, because this requires an explicit
15784 // jmp when the condition is false.
15785 if (Op.getNode()->hasOneUse()) {
15786 SDNode *User = *Op.getNode()->use_begin();
15787 // Look for an unconditional branch following this conditional branch.
15788 // We need this because we need to reverse the successors in order
15789 // to implement FCMP_UNE.
15790 if (User->getOpcode() == ISD::BR) {
15791 SDValue FalseBB = User->getOperand(1);
15793 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15794 assert(NewBR == User);
15797 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15798 Cond.getOperand(0), Cond.getOperand(1));
15799 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15800 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15801 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15802 Chain, Dest, CC, Cmp);
15803 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15813 // Look pass the truncate if the high bits are known zero.
15814 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15815 Cond = Cond.getOperand(0);
15817 // We know the result of AND is compared against zero. Try to match
15819 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15820 if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
15821 CC = NewSetCC.getOperand(0);
15822 Cond = NewSetCC.getOperand(1);
15829 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15830 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15831 Cond = EmitTest(Cond, X86Cond, dl, DAG);
15833 Cond = ConvertCmpIfNecessary(Cond, DAG);
15834 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15835 Chain, Dest, CC, Cond);
15838 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15839 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15840 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15841 // that the guard pages used by the OS virtual memory manager are allocated in
15842 // correct sequence.
15844 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15845 SelectionDAG &DAG) const {
15846 MachineFunction &MF = DAG.getMachineFunction();
15847 bool SplitStack = MF.shouldSplitStack();
15848 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15853 SDNode *Node = Op.getNode();
15854 SDValue Chain = Op.getOperand(0);
15855 SDValue Size = Op.getOperand(1);
15856 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15857 EVT VT = Node->getValueType(0);
15859 // Chain the dynamic stack allocation so that it doesn't modify the stack
15860 // pointer when other instructions are using the stack.
15861 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl);
15863 bool Is64Bit = Subtarget->is64Bit();
15864 MVT SPTy = getPointerTy(DAG.getDataLayout());
15868 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15869 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15870 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15871 " not tell us which reg is the stack pointer!");
15872 EVT VT = Node->getValueType(0);
15873 SDValue Tmp3 = Node->getOperand(2);
15875 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15876 Chain = SP.getValue(1);
15877 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15878 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15879 unsigned StackAlign = TFI.getStackAlignment();
15880 Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15881 if (Align > StackAlign)
15882 Result = DAG.getNode(ISD::AND, dl, VT, Result,
15883 DAG.getConstant(-(uint64_t)Align, dl, VT));
15884 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
15885 } else if (SplitStack) {
15886 MachineRegisterInfo &MRI = MF.getRegInfo();
15889 // The 64 bit implementation of segmented stacks needs to clobber both r10
15890 // r11. This makes it impossible to use it along with nested parameters.
15891 const Function *F = MF.getFunction();
15893 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15895 if (I->hasNestAttr())
15896 report_fatal_error("Cannot use segmented stacks with functions that "
15897 "have nested arguments.");
15900 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15901 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15902 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15903 Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15904 DAG.getRegister(Vreg, SPTy));
15907 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15909 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15910 Flag = Chain.getValue(1);
15911 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15913 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15915 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15916 unsigned SPReg = RegInfo->getStackRegister();
15917 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15918 Chain = SP.getValue(1);
15921 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15922 DAG.getConstant(-(uint64_t)Align, dl, VT));
15923 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15929 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15930 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
15932 SDValue Ops[2] = {Result, Chain};
15933 return DAG.getMergeValues(Ops, dl);
15936 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15937 MachineFunction &MF = DAG.getMachineFunction();
15938 auto PtrVT = getPointerTy(MF.getDataLayout());
15939 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15941 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15944 if (!Subtarget->is64Bit() ||
15945 Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15946 // vastart just stores the address of the VarArgsFrameIndex slot into the
15947 // memory location argument.
15948 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15949 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15950 MachinePointerInfo(SV), false, false, 0);
15954 // gp_offset (0 - 6 * 8)
15955 // fp_offset (48 - 48 + 8 * 16)
15956 // overflow_arg_area (point to parameters coming in memory).
15958 SmallVector<SDValue, 8> MemOps;
15959 SDValue FIN = Op.getOperand(1);
15961 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15962 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15964 FIN, MachinePointerInfo(SV), false, false, 0);
15965 MemOps.push_back(Store);
15968 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15969 Store = DAG.getStore(Op.getOperand(0), DL,
15970 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15972 FIN, MachinePointerInfo(SV, 4), false, false, 0);
15973 MemOps.push_back(Store);
15975 // Store ptr to overflow_arg_area
15976 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15977 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15978 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15979 MachinePointerInfo(SV, 8),
15981 MemOps.push_back(Store);
15983 // Store ptr to reg_save_area.
15984 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15985 Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15986 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15987 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15988 SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15989 MemOps.push_back(Store);
15990 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15993 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15994 assert(Subtarget->is64Bit() &&
15995 "LowerVAARG only handles 64-bit va_arg!");
15996 assert(Op.getNode()->getNumOperands() == 4);
15998 MachineFunction &MF = DAG.getMachineFunction();
15999 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
16000 // The Win64 ABI uses char* instead of a structure.
16001 return DAG.expandVAArg(Op.getNode());
16003 SDValue Chain = Op.getOperand(0);
16004 SDValue SrcPtr = Op.getOperand(1);
16005 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16006 unsigned Align = Op.getConstantOperandVal(3);
16009 EVT ArgVT = Op.getNode()->getValueType(0);
16010 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16011 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
16014 // Decide which area this value should be read from.
16015 // TODO: Implement the AMD64 ABI in its entirety. This simple
16016 // selection mechanism works only for the basic types.
16017 if (ArgVT == MVT::f80) {
16018 llvm_unreachable("va_arg for f80 not yet implemented");
16019 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16020 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
16021 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16022 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
16024 llvm_unreachable("Unhandled argument type in LowerVAARG");
16027 if (ArgMode == 2) {
16028 // Sanity Check: Make sure using fp_offset makes sense.
16029 assert(!Subtarget->useSoftFloat() &&
16030 !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
16031 Subtarget->hasSSE1());
16034 // Insert VAARG_64 node into the DAG
16035 // VAARG_64 returns two values: Variable Argument Address, Chain
16036 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
16037 DAG.getConstant(ArgMode, dl, MVT::i8),
16038 DAG.getConstant(Align, dl, MVT::i32)};
16039 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
16040 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16041 VTs, InstOps, MVT::i64,
16042 MachinePointerInfo(SV),
16044 /*Volatile=*/false,
16046 /*WriteMem=*/true);
16047 Chain = VAARG.getValue(1);
16049 // Load the next argument and return it
16050 return DAG.getLoad(ArgVT, dl,
16053 MachinePointerInfo(),
16054 false, false, false, 0);
16057 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16058 SelectionDAG &DAG) {
16059 // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
16060 // where a va_list is still an i8*.
16061 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16062 if (Subtarget->isCallingConvWin64(
16063 DAG.getMachineFunction().getFunction()->getCallingConv()))
16064 // Probably a Win64 va_copy.
16065 return DAG.expandVACopy(Op.getNode());
16067 SDValue Chain = Op.getOperand(0);
16068 SDValue DstPtr = Op.getOperand(1);
16069 SDValue SrcPtr = Op.getOperand(2);
16070 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16071 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16074 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16075 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
16077 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16080 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16081 // amount is a constant. Takes immediate version of shift as input.
16082 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16083 SDValue SrcOp, uint64_t ShiftAmt,
16084 SelectionDAG &DAG) {
16085 MVT ElementType = VT.getVectorElementType();
16087 // Fold this packed shift into its first operand if ShiftAmt is 0.
16091 // Check for ShiftAmt >= element width
16092 if (ShiftAmt >= ElementType.getSizeInBits()) {
16093 if (Opc == X86ISD::VSRAI)
16094 ShiftAmt = ElementType.getSizeInBits() - 1;
16096 return DAG.getConstant(0, dl, VT);
16099 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16100 && "Unknown target vector shift-by-constant node");
16102 // Fold this packed vector shift into a build vector if SrcOp is a
16103 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16104 if (VT == SrcOp.getSimpleValueType() &&
16105 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16106 SmallVector<SDValue, 8> Elts;
16107 unsigned NumElts = SrcOp->getNumOperands();
16108 ConstantSDNode *ND;
16111 default: llvm_unreachable(nullptr);
16112 case X86ISD::VSHLI:
16113 for (unsigned i=0; i!=NumElts; ++i) {
16114 SDValue CurrentOp = SrcOp->getOperand(i);
16115 if (CurrentOp->getOpcode() == ISD::UNDEF) {
16116 Elts.push_back(CurrentOp);
16119 ND = cast<ConstantSDNode>(CurrentOp);
16120 const APInt &C = ND->getAPIntValue();
16121 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
16124 case X86ISD::VSRLI:
16125 for (unsigned i=0; i!=NumElts; ++i) {
16126 SDValue CurrentOp = SrcOp->getOperand(i);
16127 if (CurrentOp->getOpcode() == ISD::UNDEF) {
16128 Elts.push_back(CurrentOp);
16131 ND = cast<ConstantSDNode>(CurrentOp);
16132 const APInt &C = ND->getAPIntValue();
16133 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
16136 case X86ISD::VSRAI:
16137 for (unsigned i=0; i!=NumElts; ++i) {
16138 SDValue CurrentOp = SrcOp->getOperand(i);
16139 if (CurrentOp->getOpcode() == ISD::UNDEF) {
16140 Elts.push_back(CurrentOp);
16143 ND = cast<ConstantSDNode>(CurrentOp);
16144 const APInt &C = ND->getAPIntValue();
16145 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
16150 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16153 return DAG.getNode(Opc, dl, VT, SrcOp,
16154 DAG.getConstant(ShiftAmt, dl, MVT::i8));
16157 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16158 // may or may not be a constant. Takes immediate version of shift as input.
16159 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16160 SDValue SrcOp, SDValue ShAmt,
16161 SelectionDAG &DAG) {
16162 MVT SVT = ShAmt.getSimpleValueType();
16163 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
16165 // Catch shift-by-constant.
16166 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16167 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16168 CShAmt->getZExtValue(), DAG);
16170 // Change opcode to non-immediate version
16172 default: llvm_unreachable("Unknown target vector shift node");
16173 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16174 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16175 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16178 const X86Subtarget &Subtarget =
16179 static_cast<const X86Subtarget &>(DAG.getSubtarget());
16180 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16181 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16182 // Let the shuffle legalizer expand this shift amount node.
16183 SDValue Op0 = ShAmt.getOperand(0);
16184 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16185 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16187 // Need to build a vector containing shift amount.
16188 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16189 SmallVector<SDValue, 4> ShOps;
16190 ShOps.push_back(ShAmt);
16191 if (SVT == MVT::i32) {
16192 ShOps.push_back(DAG.getConstant(0, dl, SVT));
16193 ShOps.push_back(DAG.getUNDEF(SVT));
16195 ShOps.push_back(DAG.getUNDEF(SVT));
16197 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16198 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16201 // The return type has to be a 128-bit type with the same element
16202 // type as the input type.
16203 MVT EltVT = VT.getVectorElementType();
16204 MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16206 ShAmt = DAG.getBitcast(ShVT, ShAmt);
16207 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16210 /// \brief Return Mask with the necessary casting or extending
16211 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
16212 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
16213 const X86Subtarget *Subtarget,
16214 SelectionDAG &DAG, SDLoc dl) {
16216 if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
16217 // Mask should be extended
16218 Mask = DAG.getNode(ISD::ANY_EXTEND, dl,
16219 MVT::getIntegerVT(MaskVT.getSizeInBits()), Mask);
16222 if (Mask.getSimpleValueType() == MVT::i64 && Subtarget->is32Bit()) {
16223 if (MaskVT == MVT::v64i1) {
16224 assert(Subtarget->hasBWI() && "Expected AVX512BW target!");
16225 // In case 32bit mode, bitcast i64 is illegal, extend/split it.
16227 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16228 DAG.getConstant(0, dl, MVT::i32));
16229 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16230 DAG.getConstant(1, dl, MVT::i32));
16232 Lo = DAG.getBitcast(MVT::v32i1, Lo);
16233 Hi = DAG.getBitcast(MVT::v32i1, Hi);
16235 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
16237 // MaskVT require < 64bit. Truncate mask (should succeed in any case),
16239 MVT TruncVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
16240 return DAG.getBitcast(MaskVT,
16241 DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Mask));
16245 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16246 Mask.getSimpleValueType().getSizeInBits());
16247 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16248 // are extracted by EXTRACT_SUBVECTOR.
16249 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16250 DAG.getBitcast(BitcastVT, Mask),
16251 DAG.getIntPtrConstant(0, dl));
16255 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16256 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16257 /// necessary casting or extending for \p Mask when lowering masking intrinsics
16258 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16259 SDValue PreservedSrc,
16260 const X86Subtarget *Subtarget,
16261 SelectionDAG &DAG) {
16262 MVT VT = Op.getSimpleValueType();
16263 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16264 unsigned OpcodeSelect = ISD::VSELECT;
16267 if (isAllOnesConstant(Mask))
16270 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16272 switch (Op.getOpcode()) {
16274 case X86ISD::PCMPEQM:
16275 case X86ISD::PCMPGTM:
16277 case X86ISD::CMPMU:
16278 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16279 case X86ISD::VFPCLASS:
16280 case X86ISD::VFPCLASSS:
16281 return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
16282 case X86ISD::VTRUNC:
16283 case X86ISD::VTRUNCS:
16284 case X86ISD::VTRUNCUS:
16285 // We can't use ISD::VSELECT here because it is not always "Legal"
16286 // for the destination type. For example vpmovqb require only AVX512
16287 // and vselect that can operate on byte element type require BWI
16288 OpcodeSelect = X86ISD::SELECT;
16291 if (PreservedSrc.getOpcode() == ISD::UNDEF)
16292 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16293 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
16296 /// \brief Creates an SDNode for a predicated scalar operation.
16297 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16298 /// The mask is coming as MVT::i8 and it should be truncated
16299 /// to MVT::i1 while lowering masking intrinsics.
16300 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16301 /// "X86select" instead of "vselect". We just can't create the "vselect" node
16302 /// for a scalar instruction.
16303 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16304 SDValue PreservedSrc,
16305 const X86Subtarget *Subtarget,
16306 SelectionDAG &DAG) {
16307 if (isAllOnesConstant(Mask))
16310 MVT VT = Op.getSimpleValueType();
16312 // The mask should be of type MVT::i1
16313 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16315 if (Op.getOpcode() == X86ISD::FSETCC)
16316 return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16317 if (Op.getOpcode() == X86ISD::VFPCLASS ||
16318 Op.getOpcode() == X86ISD::VFPCLASSS)
16319 return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16321 if (PreservedSrc.getOpcode() == ISD::UNDEF)
16322 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16323 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16326 static int getSEHRegistrationNodeSize(const Function *Fn) {
16327 if (!Fn->hasPersonalityFn())
16328 report_fatal_error(
16329 "querying registration node size for function without personality");
16330 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16331 // WinEHStatePass for the full struct definition.
16332 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16333 case EHPersonality::MSVC_X86SEH: return 24;
16334 case EHPersonality::MSVC_CXX: return 16;
16337 report_fatal_error(
16338 "can only recover FP for 32-bit MSVC EH personality functions");
16341 /// When the MSVC runtime transfers control to us, either to an outlined
16342 /// function or when returning to a parent frame after catching an exception, we
16343 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16344 /// Here's the math:
16345 /// RegNodeBase = EntryEBP - RegNodeSize
16346 /// ParentFP = RegNodeBase - ParentFrameOffset
16347 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16348 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16349 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16350 SDValue EntryEBP) {
16351 MachineFunction &MF = DAG.getMachineFunction();
16354 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16355 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16357 // It's possible that the parent function no longer has a personality function
16358 // if the exceptional code was optimized away, in which case we just return
16359 // the incoming EBP.
16360 if (!Fn->hasPersonalityFn())
16363 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16364 // registration, or the .set_setframe offset.
16365 MCSymbol *OffsetSym =
16366 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16367 GlobalValue::getRealLinkageName(Fn->getName()));
16368 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16369 SDValue ParentFrameOffset =
16370 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16372 // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
16373 // prologue to RBP in the parent function.
16374 const X86Subtarget &Subtarget =
16375 static_cast<const X86Subtarget &>(DAG.getSubtarget());
16376 if (Subtarget.is64Bit())
16377 return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
16379 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16380 // RegNodeBase = EntryEBP - RegNodeSize
16381 // ParentFP = RegNodeBase - ParentFrameOffset
16382 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16383 DAG.getConstant(RegNodeSize, dl, PtrVT));
16384 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
16387 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16388 SelectionDAG &DAG) {
16390 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16391 MVT VT = Op.getSimpleValueType();
16392 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16394 switch(IntrData->Type) {
16395 case INTR_TYPE_1OP:
16396 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16397 case INTR_TYPE_2OP:
16398 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16400 case INTR_TYPE_2OP_IMM8:
16401 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16402 DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16403 case INTR_TYPE_3OP:
16404 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16405 Op.getOperand(2), Op.getOperand(3));
16406 case INTR_TYPE_4OP:
16407 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16408 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16409 case INTR_TYPE_1OP_MASK_RM: {
16410 SDValue Src = Op.getOperand(1);
16411 SDValue PassThru = Op.getOperand(2);
16412 SDValue Mask = Op.getOperand(3);
16413 SDValue RoundingMode;
16414 // We allways add rounding mode to the Node.
16415 // If the rounding mode is not specified, we add the
16416 // "current direction" mode.
16417 if (Op.getNumOperands() == 4)
16419 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16421 RoundingMode = Op.getOperand(4);
16422 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16423 if (IntrWithRoundingModeOpcode != 0)
16424 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16425 X86::STATIC_ROUNDING::CUR_DIRECTION)
16426 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16427 dl, Op.getValueType(), Src, RoundingMode),
16428 Mask, PassThru, Subtarget, DAG);
16429 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16431 Mask, PassThru, Subtarget, DAG);
16433 case INTR_TYPE_1OP_MASK: {
16434 SDValue Src = Op.getOperand(1);
16435 SDValue PassThru = Op.getOperand(2);
16436 SDValue Mask = Op.getOperand(3);
16437 // We add rounding mode to the Node when
16438 // - RM Opcode is specified and
16439 // - RM is not "current direction".
16440 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16441 if (IntrWithRoundingModeOpcode != 0) {
16442 SDValue Rnd = Op.getOperand(4);
16443 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16444 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16445 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16446 dl, Op.getValueType(),
16448 Mask, PassThru, Subtarget, DAG);
16451 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16452 Mask, PassThru, Subtarget, DAG);
16454 case INTR_TYPE_SCALAR_MASK: {
16455 SDValue Src1 = Op.getOperand(1);
16456 SDValue Src2 = Op.getOperand(2);
16457 SDValue passThru = Op.getOperand(3);
16458 SDValue Mask = Op.getOperand(4);
16459 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16460 Mask, passThru, Subtarget, DAG);
16462 case INTR_TYPE_SCALAR_MASK_RM: {
16463 SDValue Src1 = Op.getOperand(1);
16464 SDValue Src2 = Op.getOperand(2);
16465 SDValue Src0 = Op.getOperand(3);
16466 SDValue Mask = Op.getOperand(4);
16467 // There are 2 kinds of intrinsics in this group:
16468 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16469 // (2) With rounding mode and sae - 7 operands.
16470 if (Op.getNumOperands() == 6) {
16471 SDValue Sae = Op.getOperand(5);
16472 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16473 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16475 Mask, Src0, Subtarget, DAG);
16477 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16478 SDValue RoundingMode = Op.getOperand(5);
16479 SDValue Sae = Op.getOperand(6);
16480 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16481 RoundingMode, Sae),
16482 Mask, Src0, Subtarget, DAG);
16484 case INTR_TYPE_2OP_MASK:
16485 case INTR_TYPE_2OP_IMM8_MASK: {
16486 SDValue Src1 = Op.getOperand(1);
16487 SDValue Src2 = Op.getOperand(2);
16488 SDValue PassThru = Op.getOperand(3);
16489 SDValue Mask = Op.getOperand(4);
16491 if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16492 Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16494 // We specify 2 possible opcodes for intrinsics with rounding modes.
16495 // First, we check if the intrinsic may have non-default rounding mode,
16496 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16497 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16498 if (IntrWithRoundingModeOpcode != 0) {
16499 SDValue Rnd = Op.getOperand(5);
16500 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16501 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16502 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16503 dl, Op.getValueType(),
16505 Mask, PassThru, Subtarget, DAG);
16508 // TODO: Intrinsics should have fast-math-flags to propagate.
16509 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16510 Mask, PassThru, Subtarget, DAG);
16512 case INTR_TYPE_2OP_MASK_RM: {
16513 SDValue Src1 = Op.getOperand(1);
16514 SDValue Src2 = Op.getOperand(2);
16515 SDValue PassThru = Op.getOperand(3);
16516 SDValue Mask = Op.getOperand(4);
16517 // We specify 2 possible modes for intrinsics, with/without rounding
16519 // First, we check if the intrinsic have rounding mode (6 operands),
16520 // if not, we set rounding mode to "current".
16522 if (Op.getNumOperands() == 6)
16523 Rnd = Op.getOperand(5);
16525 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16526 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16528 Mask, PassThru, Subtarget, DAG);
16530 case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16531 SDValue Src1 = Op.getOperand(1);
16532 SDValue Src2 = Op.getOperand(2);
16533 SDValue Src3 = Op.getOperand(3);
16534 SDValue PassThru = Op.getOperand(4);
16535 SDValue Mask = Op.getOperand(5);
16536 SDValue Sae = Op.getOperand(6);
16538 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16540 Mask, PassThru, Subtarget, DAG);
16542 case INTR_TYPE_3OP_MASK_RM: {
16543 SDValue Src1 = Op.getOperand(1);
16544 SDValue Src2 = Op.getOperand(2);
16545 SDValue Imm = Op.getOperand(3);
16546 SDValue PassThru = Op.getOperand(4);
16547 SDValue Mask = Op.getOperand(5);
16548 // We specify 2 possible modes for intrinsics, with/without rounding
16550 // First, we check if the intrinsic have rounding mode (7 operands),
16551 // if not, we set rounding mode to "current".
16553 if (Op.getNumOperands() == 7)
16554 Rnd = Op.getOperand(6);
16556 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16557 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16558 Src1, Src2, Imm, Rnd),
16559 Mask, PassThru, Subtarget, DAG);
16561 case INTR_TYPE_3OP_IMM8_MASK:
16562 case INTR_TYPE_3OP_MASK:
16563 case INSERT_SUBVEC: {
16564 SDValue Src1 = Op.getOperand(1);
16565 SDValue Src2 = Op.getOperand(2);
16566 SDValue Src3 = Op.getOperand(3);
16567 SDValue PassThru = Op.getOperand(4);
16568 SDValue Mask = Op.getOperand(5);
16570 if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16571 Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16572 else if (IntrData->Type == INSERT_SUBVEC) {
16573 // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16574 assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16575 unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16576 Imm *= Src2.getSimpleValueType().getVectorNumElements();
16577 Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16580 // We specify 2 possible opcodes for intrinsics with rounding modes.
16581 // First, we check if the intrinsic may have non-default rounding mode,
16582 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16583 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16584 if (IntrWithRoundingModeOpcode != 0) {
16585 SDValue Rnd = Op.getOperand(6);
16586 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16587 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16588 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16589 dl, Op.getValueType(),
16590 Src1, Src2, Src3, Rnd),
16591 Mask, PassThru, Subtarget, DAG);
16594 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16596 Mask, PassThru, Subtarget, DAG);
16598 case VPERM_3OP_MASKZ:
16599 case VPERM_3OP_MASK:{
16600 // Src2 is the PassThru
16601 SDValue Src1 = Op.getOperand(1);
16602 SDValue Src2 = Op.getOperand(2);
16603 SDValue Src3 = Op.getOperand(3);
16604 SDValue Mask = Op.getOperand(4);
16605 MVT VT = Op.getSimpleValueType();
16606 SDValue PassThru = SDValue();
16608 // set PassThru element
16609 if (IntrData->Type == VPERM_3OP_MASKZ)
16610 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16612 PassThru = DAG.getBitcast(VT, Src2);
16614 // Swap Src1 and Src2 in the node creation
16615 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16616 dl, Op.getValueType(),
16618 Mask, PassThru, Subtarget, DAG);
16622 case FMA_OP_MASK: {
16623 SDValue Src1 = Op.getOperand(1);
16624 SDValue Src2 = Op.getOperand(2);
16625 SDValue Src3 = Op.getOperand(3);
16626 SDValue Mask = Op.getOperand(4);
16627 MVT VT = Op.getSimpleValueType();
16628 SDValue PassThru = SDValue();
16630 // set PassThru element
16631 if (IntrData->Type == FMA_OP_MASKZ)
16632 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16633 else if (IntrData->Type == FMA_OP_MASK3)
16638 // We specify 2 possible opcodes for intrinsics with rounding modes.
16639 // First, we check if the intrinsic may have non-default rounding mode,
16640 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16641 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16642 if (IntrWithRoundingModeOpcode != 0) {
16643 SDValue Rnd = Op.getOperand(5);
16644 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16645 X86::STATIC_ROUNDING::CUR_DIRECTION)
16646 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16647 dl, Op.getValueType(),
16648 Src1, Src2, Src3, Rnd),
16649 Mask, PassThru, Subtarget, DAG);
16651 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16652 dl, Op.getValueType(),
16654 Mask, PassThru, Subtarget, DAG);
16656 case TERLOG_OP_MASK:
16657 case TERLOG_OP_MASKZ: {
16658 SDValue Src1 = Op.getOperand(1);
16659 SDValue Src2 = Op.getOperand(2);
16660 SDValue Src3 = Op.getOperand(3);
16661 SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16662 SDValue Mask = Op.getOperand(5);
16663 MVT VT = Op.getSimpleValueType();
16664 SDValue PassThru = Src1;
16665 // Set PassThru element.
16666 if (IntrData->Type == TERLOG_OP_MASKZ)
16667 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16669 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16670 Src1, Src2, Src3, Src4),
16671 Mask, PassThru, Subtarget, DAG);
16674 // FPclass intrinsics with mask
16675 SDValue Src1 = Op.getOperand(1);
16676 MVT VT = Src1.getSimpleValueType();
16677 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16678 SDValue Imm = Op.getOperand(2);
16679 SDValue Mask = Op.getOperand(3);
16680 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16681 Mask.getSimpleValueType().getSizeInBits());
16682 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16683 SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16684 DAG.getTargetConstant(0, dl, MaskVT),
16686 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16687 DAG.getUNDEF(BitcastVT), FPclassMask,
16688 DAG.getIntPtrConstant(0, dl));
16689 return DAG.getBitcast(Op.getValueType(), Res);
16692 SDValue Src1 = Op.getOperand(1);
16693 SDValue Imm = Op.getOperand(2);
16694 SDValue Mask = Op.getOperand(3);
16695 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16696 SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16697 DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16698 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16701 case CMP_MASK_CC: {
16702 // Comparison intrinsics with masks.
16703 // Example of transformation:
16704 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16705 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16707 // (v8i1 (insert_subvector undef,
16708 // (v2i1 (and (PCMPEQM %a, %b),
16709 // (extract_subvector
16710 // (v8i1 (bitcast %mask)), 0))), 0))))
16711 MVT VT = Op.getOperand(1).getSimpleValueType();
16712 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16713 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16714 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16715 Mask.getSimpleValueType().getSizeInBits());
16717 if (IntrData->Type == CMP_MASK_CC) {
16718 SDValue CC = Op.getOperand(3);
16719 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16720 // We specify 2 possible opcodes for intrinsics with rounding modes.
16721 // First, we check if the intrinsic may have non-default rounding mode,
16722 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16723 if (IntrData->Opc1 != 0) {
16724 SDValue Rnd = Op.getOperand(5);
16725 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16726 X86::STATIC_ROUNDING::CUR_DIRECTION)
16727 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16728 Op.getOperand(2), CC, Rnd);
16730 //default rounding mode
16732 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16733 Op.getOperand(2), CC);
16736 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16737 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16740 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16741 DAG.getTargetConstant(0, dl,
16744 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16745 DAG.getUNDEF(BitcastVT), CmpMask,
16746 DAG.getIntPtrConstant(0, dl));
16747 return DAG.getBitcast(Op.getValueType(), Res);
16749 case CMP_MASK_SCALAR_CC: {
16750 SDValue Src1 = Op.getOperand(1);
16751 SDValue Src2 = Op.getOperand(2);
16752 SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16753 SDValue Mask = Op.getOperand(4);
16756 if (IntrData->Opc1 != 0) {
16757 SDValue Rnd = Op.getOperand(5);
16758 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16759 X86::STATIC_ROUNDING::CUR_DIRECTION)
16760 Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16762 //default rounding mode
16764 Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16766 SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16767 DAG.getTargetConstant(0, dl,
16771 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16772 DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16773 DAG.getValueType(MVT::i1));
16775 case COMI: { // Comparison intrinsics
16776 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16777 SDValue LHS = Op.getOperand(1);
16778 SDValue RHS = Op.getOperand(2);
16779 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16780 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16781 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16782 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16783 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16784 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16786 case COMI_RM: { // Comparison intrinsics with Sae
16787 SDValue LHS = Op.getOperand(1);
16788 SDValue RHS = Op.getOperand(2);
16789 SDValue CC = Op.getOperand(3);
16790 SDValue Sae = Op.getOperand(4);
16791 auto ComiType = TranslateX86ConstCondToX86CC(CC);
16792 // choose between ordered and unordered (comi/ucomi)
16793 unsigned comiOp = std::get<0>(ComiType) ? IntrData->Opc0 : IntrData->Opc1;
16795 if (cast<ConstantSDNode>(Sae)->getZExtValue() !=
16796 X86::STATIC_ROUNDING::CUR_DIRECTION)
16797 Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS, Sae);
16799 Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS);
16800 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16801 DAG.getConstant(std::get<1>(ComiType), dl, MVT::i8), Cond);
16802 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16805 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16806 Op.getOperand(1), Op.getOperand(2), DAG);
16808 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16809 Op.getSimpleValueType(),
16811 Op.getOperand(2), DAG),
16812 Op.getOperand(4), Op.getOperand(3), Subtarget,
16814 case COMPRESS_EXPAND_IN_REG: {
16815 SDValue Mask = Op.getOperand(3);
16816 SDValue DataToCompress = Op.getOperand(1);
16817 SDValue PassThru = Op.getOperand(2);
16818 if (isAllOnesConstant(Mask)) // return data as is
16819 return Op.getOperand(1);
16821 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16823 Mask, PassThru, Subtarget, DAG);
16826 SDValue Mask = Op.getOperand(1);
16827 MVT MaskVT = MVT::getVectorVT(MVT::i1, Mask.getSimpleValueType().getSizeInBits());
16828 Mask = DAG.getBitcast(MaskVT, Mask);
16829 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Mask);
16832 SDValue Mask = Op.getOperand(3);
16833 MVT VT = Op.getSimpleValueType();
16834 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16835 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16836 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16840 MVT VT = Op.getSimpleValueType();
16841 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits()/2);
16843 SDValue Src1 = getMaskNode(Op.getOperand(1), MaskVT, Subtarget, DAG, dl);
16844 SDValue Src2 = getMaskNode(Op.getOperand(2), MaskVT, Subtarget, DAG, dl);
16845 // Arguments should be swapped.
16846 SDValue Res = DAG.getNode(IntrData->Opc0, dl,
16847 MVT::getVectorVT(MVT::i1, VT.getSizeInBits()),
16849 return DAG.getBitcast(VT, Res);
16857 default: return SDValue(); // Don't custom lower most intrinsics.
16859 case Intrinsic::x86_avx2_permd:
16860 case Intrinsic::x86_avx2_permps:
16861 // Operands intentionally swapped. Mask is last operand to intrinsic,
16862 // but second operand for node/instruction.
16863 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16864 Op.getOperand(2), Op.getOperand(1));
16866 // ptest and testp intrinsics. The intrinsic these come from are designed to
16867 // return an integer value, not just an instruction so lower it to the ptest
16868 // or testp pattern and a setcc for the result.
16869 case Intrinsic::x86_sse41_ptestz:
16870 case Intrinsic::x86_sse41_ptestc:
16871 case Intrinsic::x86_sse41_ptestnzc:
16872 case Intrinsic::x86_avx_ptestz_256:
16873 case Intrinsic::x86_avx_ptestc_256:
16874 case Intrinsic::x86_avx_ptestnzc_256:
16875 case Intrinsic::x86_avx_vtestz_ps:
16876 case Intrinsic::x86_avx_vtestc_ps:
16877 case Intrinsic::x86_avx_vtestnzc_ps:
16878 case Intrinsic::x86_avx_vtestz_pd:
16879 case Intrinsic::x86_avx_vtestc_pd:
16880 case Intrinsic::x86_avx_vtestnzc_pd:
16881 case Intrinsic::x86_avx_vtestz_ps_256:
16882 case Intrinsic::x86_avx_vtestc_ps_256:
16883 case Intrinsic::x86_avx_vtestnzc_ps_256:
16884 case Intrinsic::x86_avx_vtestz_pd_256:
16885 case Intrinsic::x86_avx_vtestc_pd_256:
16886 case Intrinsic::x86_avx_vtestnzc_pd_256: {
16887 bool IsTestPacked = false;
16890 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16891 case Intrinsic::x86_avx_vtestz_ps:
16892 case Intrinsic::x86_avx_vtestz_pd:
16893 case Intrinsic::x86_avx_vtestz_ps_256:
16894 case Intrinsic::x86_avx_vtestz_pd_256:
16895 IsTestPacked = true; // Fallthrough
16896 case Intrinsic::x86_sse41_ptestz:
16897 case Intrinsic::x86_avx_ptestz_256:
16899 X86CC = X86::COND_E;
16901 case Intrinsic::x86_avx_vtestc_ps:
16902 case Intrinsic::x86_avx_vtestc_pd:
16903 case Intrinsic::x86_avx_vtestc_ps_256:
16904 case Intrinsic::x86_avx_vtestc_pd_256:
16905 IsTestPacked = true; // Fallthrough
16906 case Intrinsic::x86_sse41_ptestc:
16907 case Intrinsic::x86_avx_ptestc_256:
16909 X86CC = X86::COND_B;
16911 case Intrinsic::x86_avx_vtestnzc_ps:
16912 case Intrinsic::x86_avx_vtestnzc_pd:
16913 case Intrinsic::x86_avx_vtestnzc_ps_256:
16914 case Intrinsic::x86_avx_vtestnzc_pd_256:
16915 IsTestPacked = true; // Fallthrough
16916 case Intrinsic::x86_sse41_ptestnzc:
16917 case Intrinsic::x86_avx_ptestnzc_256:
16919 X86CC = X86::COND_A;
16923 SDValue LHS = Op.getOperand(1);
16924 SDValue RHS = Op.getOperand(2);
16925 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16926 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16927 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16928 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16929 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16931 case Intrinsic::x86_avx512_kortestz_w:
16932 case Intrinsic::x86_avx512_kortestc_w: {
16933 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16934 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16935 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16936 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16937 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16938 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16939 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16942 case Intrinsic::x86_sse42_pcmpistria128:
16943 case Intrinsic::x86_sse42_pcmpestria128:
16944 case Intrinsic::x86_sse42_pcmpistric128:
16945 case Intrinsic::x86_sse42_pcmpestric128:
16946 case Intrinsic::x86_sse42_pcmpistrio128:
16947 case Intrinsic::x86_sse42_pcmpestrio128:
16948 case Intrinsic::x86_sse42_pcmpistris128:
16949 case Intrinsic::x86_sse42_pcmpestris128:
16950 case Intrinsic::x86_sse42_pcmpistriz128:
16951 case Intrinsic::x86_sse42_pcmpestriz128: {
16955 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16956 case Intrinsic::x86_sse42_pcmpistria128:
16957 Opcode = X86ISD::PCMPISTRI;
16958 X86CC = X86::COND_A;
16960 case Intrinsic::x86_sse42_pcmpestria128:
16961 Opcode = X86ISD::PCMPESTRI;
16962 X86CC = X86::COND_A;
16964 case Intrinsic::x86_sse42_pcmpistric128:
16965 Opcode = X86ISD::PCMPISTRI;
16966 X86CC = X86::COND_B;
16968 case Intrinsic::x86_sse42_pcmpestric128:
16969 Opcode = X86ISD::PCMPESTRI;
16970 X86CC = X86::COND_B;
16972 case Intrinsic::x86_sse42_pcmpistrio128:
16973 Opcode = X86ISD::PCMPISTRI;
16974 X86CC = X86::COND_O;
16976 case Intrinsic::x86_sse42_pcmpestrio128:
16977 Opcode = X86ISD::PCMPESTRI;
16978 X86CC = X86::COND_O;
16980 case Intrinsic::x86_sse42_pcmpistris128:
16981 Opcode = X86ISD::PCMPISTRI;
16982 X86CC = X86::COND_S;
16984 case Intrinsic::x86_sse42_pcmpestris128:
16985 Opcode = X86ISD::PCMPESTRI;
16986 X86CC = X86::COND_S;
16988 case Intrinsic::x86_sse42_pcmpistriz128:
16989 Opcode = X86ISD::PCMPISTRI;
16990 X86CC = X86::COND_E;
16992 case Intrinsic::x86_sse42_pcmpestriz128:
16993 Opcode = X86ISD::PCMPESTRI;
16994 X86CC = X86::COND_E;
16997 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16998 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16999 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17000 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17001 DAG.getConstant(X86CC, dl, MVT::i8),
17002 SDValue(PCMP.getNode(), 1));
17003 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17006 case Intrinsic::x86_sse42_pcmpistri128:
17007 case Intrinsic::x86_sse42_pcmpestri128: {
17009 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17010 Opcode = X86ISD::PCMPISTRI;
17012 Opcode = X86ISD::PCMPESTRI;
17014 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17015 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17016 return DAG.getNode(Opcode, dl, VTs, NewOps);
17019 case Intrinsic::x86_seh_lsda: {
17020 // Compute the symbol for the LSDA. We know it'll get emitted later.
17021 MachineFunction &MF = DAG.getMachineFunction();
17022 SDValue Op1 = Op.getOperand(1);
17023 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
17024 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
17025 GlobalValue::getRealLinkageName(Fn->getName()));
17027 // Generate a simple absolute symbol reference. This intrinsic is only
17028 // supported on 32-bit Windows, which isn't PIC.
17029 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
17030 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
17033 case Intrinsic::x86_seh_recoverfp: {
17034 SDValue FnOp = Op.getOperand(1);
17035 SDValue IncomingFPOp = Op.getOperand(2);
17036 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
17037 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
17039 report_fatal_error(
17040 "llvm.x86.seh.recoverfp must take a function as the first argument");
17041 return recoverFramePointer(DAG, Fn, IncomingFPOp);
17044 case Intrinsic::localaddress: {
17045 // Returns one of the stack, base, or frame pointer registers, depending on
17046 // which is used to reference local variables.
17047 MachineFunction &MF = DAG.getMachineFunction();
17048 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17050 if (RegInfo->hasBasePointer(MF))
17051 Reg = RegInfo->getBaseRegister();
17052 else // This function handles the SP or FP case.
17053 Reg = RegInfo->getPtrSizedFrameRegister(MF);
17054 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
17059 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17060 SDValue Src, SDValue Mask, SDValue Base,
17061 SDValue Index, SDValue ScaleOp, SDValue Chain,
17062 const X86Subtarget * Subtarget) {
17064 auto *C = cast<ConstantSDNode>(ScaleOp);
17065 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17066 MVT MaskVT = MVT::getVectorVT(MVT::i1,
17067 Index.getSimpleValueType().getVectorNumElements());
17069 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17071 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17073 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17074 Mask.getSimpleValueType().getSizeInBits());
17076 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17077 // are extracted by EXTRACT_SUBVECTOR.
17078 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17079 DAG.getBitcast(BitcastVT, Mask),
17080 DAG.getIntPtrConstant(0, dl));
17082 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17083 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17084 SDValue Segment = DAG.getRegister(0, MVT::i32);
17085 if (Src.getOpcode() == ISD::UNDEF)
17086 Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
17087 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17088 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17089 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17090 return DAG.getMergeValues(RetOps, dl);
17093 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17094 SDValue Src, SDValue Mask, SDValue Base,
17095 SDValue Index, SDValue ScaleOp, SDValue Chain) {
17097 auto *C = cast<ConstantSDNode>(ScaleOp);
17098 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17099 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17100 SDValue Segment = DAG.getRegister(0, MVT::i32);
17101 MVT MaskVT = MVT::getVectorVT(MVT::i1,
17102 Index.getSimpleValueType().getVectorNumElements());
17104 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17106 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17108 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17109 Mask.getSimpleValueType().getSizeInBits());
17111 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17112 // are extracted by EXTRACT_SUBVECTOR.
17113 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17114 DAG.getBitcast(BitcastVT, Mask),
17115 DAG.getIntPtrConstant(0, dl));
17117 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17118 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
17119 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17120 return SDValue(Res, 1);
17123 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17124 SDValue Mask, SDValue Base, SDValue Index,
17125 SDValue ScaleOp, SDValue Chain) {
17127 auto *C = cast<ConstantSDNode>(ScaleOp);
17128 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17129 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17130 SDValue Segment = DAG.getRegister(0, MVT::i32);
17132 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17134 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17136 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17138 MaskInReg = DAG.getBitcast(MaskVT, Mask);
17139 //SDVTList VTs = DAG.getVTList(MVT::Other);
17140 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17141 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17142 return SDValue(Res, 0);
17145 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17146 // read performance monitor counters (x86_rdpmc).
17147 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17148 SelectionDAG &DAG, const X86Subtarget *Subtarget,
17149 SmallVectorImpl<SDValue> &Results) {
17150 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17151 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17154 // The ECX register is used to select the index of the performance counter
17156 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17158 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17160 // Reads the content of a 64-bit performance counter and returns it in the
17161 // registers EDX:EAX.
17162 if (Subtarget->is64Bit()) {
17163 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17164 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17167 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17168 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17171 Chain = HI.getValue(1);
17173 if (Subtarget->is64Bit()) {
17174 // The EAX register is loaded with the low-order 32 bits. The EDX register
17175 // is loaded with the supported high-order bits of the counter.
17176 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17177 DAG.getConstant(32, DL, MVT::i8));
17178 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17179 Results.push_back(Chain);
17183 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17184 SDValue Ops[] = { LO, HI };
17185 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17186 Results.push_back(Pair);
17187 Results.push_back(Chain);
17190 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17191 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17192 // also used to custom lower READCYCLECOUNTER nodes.
17193 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17194 SelectionDAG &DAG, const X86Subtarget *Subtarget,
17195 SmallVectorImpl<SDValue> &Results) {
17196 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17197 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17200 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17201 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17202 // and the EAX register is loaded with the low-order 32 bits.
17203 if (Subtarget->is64Bit()) {
17204 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17205 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17208 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17209 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17212 SDValue Chain = HI.getValue(1);
17214 if (Opcode == X86ISD::RDTSCP_DAG) {
17215 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17217 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17218 // the ECX register. Add 'ecx' explicitly to the chain.
17219 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17221 // Explicitly store the content of ECX at the location passed in input
17222 // to the 'rdtscp' intrinsic.
17223 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17224 MachinePointerInfo(), false, false, 0);
17227 if (Subtarget->is64Bit()) {
17228 // The EDX register is loaded with the high-order 32 bits of the MSR, and
17229 // the EAX register is loaded with the low-order 32 bits.
17230 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17231 DAG.getConstant(32, DL, MVT::i8));
17232 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17233 Results.push_back(Chain);
17237 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17238 SDValue Ops[] = { LO, HI };
17239 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17240 Results.push_back(Pair);
17241 Results.push_back(Chain);
17244 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17245 SelectionDAG &DAG) {
17246 SmallVector<SDValue, 2> Results;
17248 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17250 return DAG.getMergeValues(Results, DL);
17253 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
17254 MachineFunction &MF = DAG.getMachineFunction();
17255 SDValue Chain = Op.getOperand(0);
17256 SDValue RegNode = Op.getOperand(2);
17257 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
17259 report_fatal_error("EH registrations only live in functions using WinEH");
17261 // Cast the operand to an alloca, and remember the frame index.
17262 auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
17264 report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
17265 EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
17267 // Return the chain operand without making any DAG nodes.
17271 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
17272 /// return truncate Store/MaskedStore Node
17273 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
17277 SDValue Mask = Op.getOperand(4);
17278 SDValue DataToTruncate = Op.getOperand(3);
17279 SDValue Addr = Op.getOperand(2);
17280 SDValue Chain = Op.getOperand(0);
17282 MVT VT = DataToTruncate.getSimpleValueType();
17283 MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
17285 if (isAllOnesConstant(Mask)) // return just a truncate store
17286 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
17287 MachinePointerInfo(), SVT, false, false,
17288 SVT.getScalarSizeInBits()/8);
17290 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17291 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17292 Mask.getSimpleValueType().getSizeInBits());
17293 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17294 // are extracted by EXTRACT_SUBVECTOR.
17295 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17296 DAG.getBitcast(BitcastVT, Mask),
17297 DAG.getIntPtrConstant(0, dl));
17299 MachineMemOperand *MMO = DAG.getMachineFunction().
17300 getMachineMemOperand(MachinePointerInfo(),
17301 MachineMemOperand::MOStore, SVT.getStoreSize(),
17302 SVT.getScalarSizeInBits()/8);
17304 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
17305 VMask, SVT, MMO, true);
17308 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17309 SelectionDAG &DAG) {
17310 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17312 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17314 if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
17315 return MarkEHRegistrationNode(Op, DAG);
17320 switch(IntrData->Type) {
17321 default: llvm_unreachable("Unknown Intrinsic Type");
17324 // Emit the node with the right value type.
17325 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17326 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17328 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17329 // Otherwise return the value from Rand, which is always 0, casted to i32.
17330 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17331 DAG.getConstant(1, dl, Op->getValueType(1)),
17332 DAG.getConstant(X86::COND_B, dl, MVT::i32),
17333 SDValue(Result.getNode(), 1) };
17334 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17335 DAG.getVTList(Op->getValueType(1), MVT::Glue),
17338 // Return { result, isValid, chain }.
17339 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17340 SDValue(Result.getNode(), 2));
17343 //gather(v1, mask, index, base, scale);
17344 SDValue Chain = Op.getOperand(0);
17345 SDValue Src = Op.getOperand(2);
17346 SDValue Base = Op.getOperand(3);
17347 SDValue Index = Op.getOperand(4);
17348 SDValue Mask = Op.getOperand(5);
17349 SDValue Scale = Op.getOperand(6);
17350 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17354 //scatter(base, mask, index, v1, scale);
17355 SDValue Chain = Op.getOperand(0);
17356 SDValue Base = Op.getOperand(2);
17357 SDValue Mask = Op.getOperand(3);
17358 SDValue Index = Op.getOperand(4);
17359 SDValue Src = Op.getOperand(5);
17360 SDValue Scale = Op.getOperand(6);
17361 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17365 SDValue Hint = Op.getOperand(6);
17366 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17367 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17368 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17369 SDValue Chain = Op.getOperand(0);
17370 SDValue Mask = Op.getOperand(2);
17371 SDValue Index = Op.getOperand(3);
17372 SDValue Base = Op.getOperand(4);
17373 SDValue Scale = Op.getOperand(5);
17374 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17376 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17378 SmallVector<SDValue, 2> Results;
17379 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17381 return DAG.getMergeValues(Results, dl);
17383 // Read Performance Monitoring Counters.
17385 SmallVector<SDValue, 2> Results;
17386 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17387 return DAG.getMergeValues(Results, dl);
17389 // XTEST intrinsics.
17391 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17392 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17393 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17394 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17396 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17397 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17398 Ret, SDValue(InTrans.getNode(), 1));
17402 SmallVector<SDValue, 2> Results;
17403 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17404 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17405 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17406 DAG.getConstant(-1, dl, MVT::i8));
17407 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17408 Op.getOperand(4), GenCF.getValue(1));
17409 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17410 Op.getOperand(5), MachinePointerInfo(),
17412 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17413 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17415 Results.push_back(SetCC);
17416 Results.push_back(Store);
17417 return DAG.getMergeValues(Results, dl);
17419 case COMPRESS_TO_MEM: {
17421 SDValue Mask = Op.getOperand(4);
17422 SDValue DataToCompress = Op.getOperand(3);
17423 SDValue Addr = Op.getOperand(2);
17424 SDValue Chain = Op.getOperand(0);
17426 MVT VT = DataToCompress.getSimpleValueType();
17427 if (isAllOnesConstant(Mask)) // return just a store
17428 return DAG.getStore(Chain, dl, DataToCompress, Addr,
17429 MachinePointerInfo(), false, false,
17430 VT.getScalarSizeInBits()/8);
17432 SDValue Compressed =
17433 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17434 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17435 return DAG.getStore(Chain, dl, Compressed, Addr,
17436 MachinePointerInfo(), false, false,
17437 VT.getScalarSizeInBits()/8);
17439 case TRUNCATE_TO_MEM_VI8:
17440 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17441 case TRUNCATE_TO_MEM_VI16:
17442 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17443 case TRUNCATE_TO_MEM_VI32:
17444 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17445 case EXPAND_FROM_MEM: {
17447 SDValue Mask = Op.getOperand(4);
17448 SDValue PassThru = Op.getOperand(3);
17449 SDValue Addr = Op.getOperand(2);
17450 SDValue Chain = Op.getOperand(0);
17451 MVT VT = Op.getSimpleValueType();
17453 if (isAllOnesConstant(Mask)) // return just a load
17454 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17455 false, VT.getScalarSizeInBits()/8);
17457 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17458 false, false, false,
17459 VT.getScalarSizeInBits()/8);
17461 SDValue Results[] = {
17462 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17463 Mask, PassThru, Subtarget, DAG), Chain};
17464 return DAG.getMergeValues(Results, dl);
17469 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17470 SelectionDAG &DAG) const {
17471 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17472 MFI->setReturnAddressIsTaken(true);
17474 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17477 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17479 EVT PtrVT = getPointerTy(DAG.getDataLayout());
17482 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17483 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17484 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17485 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17486 DAG.getNode(ISD::ADD, dl, PtrVT,
17487 FrameAddr, Offset),
17488 MachinePointerInfo(), false, false, false, 0);
17491 // Just load the return address.
17492 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17493 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17494 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17497 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17498 MachineFunction &MF = DAG.getMachineFunction();
17499 MachineFrameInfo *MFI = MF.getFrameInfo();
17500 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17501 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17502 EVT VT = Op.getValueType();
17504 MFI->setFrameAddressIsTaken(true);
17506 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17507 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
17508 // is not possible to crawl up the stack without looking at the unwind codes
17510 int FrameAddrIndex = FuncInfo->getFAIndex();
17511 if (!FrameAddrIndex) {
17512 // Set up a frame object for the return address.
17513 unsigned SlotSize = RegInfo->getSlotSize();
17514 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17515 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17516 FuncInfo->setFAIndex(FrameAddrIndex);
17518 return DAG.getFrameIndex(FrameAddrIndex, VT);
17521 unsigned FrameReg =
17522 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17523 SDLoc dl(Op); // FIXME probably not meaningful
17524 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17525 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17526 (FrameReg == X86::EBP && VT == MVT::i32)) &&
17527 "Invalid Frame Register!");
17528 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17530 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17531 MachinePointerInfo(),
17532 false, false, false, 0);
17536 // FIXME? Maybe this could be a TableGen attribute on some registers and
17537 // this table could be generated automatically from RegInfo.
17538 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17539 SelectionDAG &DAG) const {
17540 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17541 const MachineFunction &MF = DAG.getMachineFunction();
17543 unsigned Reg = StringSwitch<unsigned>(RegName)
17544 .Case("esp", X86::ESP)
17545 .Case("rsp", X86::RSP)
17546 .Case("ebp", X86::EBP)
17547 .Case("rbp", X86::RBP)
17550 if (Reg == X86::EBP || Reg == X86::RBP) {
17551 if (!TFI.hasFP(MF))
17552 report_fatal_error("register " + StringRef(RegName) +
17553 " is allocatable: function has no frame pointer");
17556 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17557 unsigned FrameReg =
17558 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17559 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17560 "Invalid Frame Register!");
17568 report_fatal_error("Invalid register name global variable");
17571 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17572 SelectionDAG &DAG) const {
17573 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17574 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17577 unsigned X86TargetLowering::getExceptionPointerRegister(
17578 const Constant *PersonalityFn) const {
17579 if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17580 return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17582 return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17585 unsigned X86TargetLowering::getExceptionSelectorRegister(
17586 const Constant *PersonalityFn) const {
17587 // Funclet personalities don't use selectors (the runtime does the selection).
17588 assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17589 return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17592 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17593 SDValue Chain = Op.getOperand(0);
17594 SDValue Offset = Op.getOperand(1);
17595 SDValue Handler = Op.getOperand(2);
17598 EVT PtrVT = getPointerTy(DAG.getDataLayout());
17599 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17600 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17601 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17602 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17603 "Invalid Frame Register!");
17604 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17605 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17607 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17608 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17610 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17611 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17613 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17615 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17616 DAG.getRegister(StoreAddrReg, PtrVT));
17619 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17620 SelectionDAG &DAG) const {
17622 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17623 DAG.getVTList(MVT::i32, MVT::Other),
17624 Op.getOperand(0), Op.getOperand(1));
17627 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17628 SelectionDAG &DAG) const {
17630 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17631 Op.getOperand(0), Op.getOperand(1));
17634 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17635 return Op.getOperand(0);
17638 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17639 SelectionDAG &DAG) const {
17640 SDValue Root = Op.getOperand(0);
17641 SDValue Trmp = Op.getOperand(1); // trampoline
17642 SDValue FPtr = Op.getOperand(2); // nested function
17643 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17646 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17647 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17649 if (Subtarget->is64Bit()) {
17650 SDValue OutChains[6];
17652 // Large code-model.
17653 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
17654 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17656 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17657 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17659 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17661 // Load the pointer to the nested function into R11.
17662 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17663 SDValue Addr = Trmp;
17664 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17665 Addr, MachinePointerInfo(TrmpAddr),
17668 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17669 DAG.getConstant(2, dl, MVT::i64));
17670 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17671 MachinePointerInfo(TrmpAddr, 2),
17674 // Load the 'nest' parameter value into R10.
17675 // R10 is specified in X86CallingConv.td
17676 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17677 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17678 DAG.getConstant(10, dl, MVT::i64));
17679 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17680 Addr, MachinePointerInfo(TrmpAddr, 10),
17683 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17684 DAG.getConstant(12, dl, MVT::i64));
17685 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17686 MachinePointerInfo(TrmpAddr, 12),
17689 // Jump to the nested function.
17690 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17691 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17692 DAG.getConstant(20, dl, MVT::i64));
17693 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17694 Addr, MachinePointerInfo(TrmpAddr, 20),
17697 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17698 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17699 DAG.getConstant(22, dl, MVT::i64));
17700 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17701 Addr, MachinePointerInfo(TrmpAddr, 22),
17704 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17706 const Function *Func =
17707 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17708 CallingConv::ID CC = Func->getCallingConv();
17713 llvm_unreachable("Unsupported calling convention");
17714 case CallingConv::C:
17715 case CallingConv::X86_StdCall: {
17716 // Pass 'nest' parameter in ECX.
17717 // Must be kept in sync with X86CallingConv.td
17718 NestReg = X86::ECX;
17720 // Check that ECX wasn't needed by an 'inreg' parameter.
17721 FunctionType *FTy = Func->getFunctionType();
17722 const AttributeSet &Attrs = Func->getAttributes();
17724 if (!Attrs.isEmpty() && !Func->isVarArg()) {
17725 unsigned InRegCount = 0;
17728 for (FunctionType::param_iterator I = FTy->param_begin(),
17729 E = FTy->param_end(); I != E; ++I, ++Idx)
17730 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17731 auto &DL = DAG.getDataLayout();
17732 // FIXME: should only count parameters that are lowered to integers.
17733 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17736 if (InRegCount > 2) {
17737 report_fatal_error("Nest register in use - reduce number of inreg"
17743 case CallingConv::X86_FastCall:
17744 case CallingConv::X86_ThisCall:
17745 case CallingConv::Fast:
17746 // Pass 'nest' parameter in EAX.
17747 // Must be kept in sync with X86CallingConv.td
17748 NestReg = X86::EAX;
17752 SDValue OutChains[4];
17753 SDValue Addr, Disp;
17755 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17756 DAG.getConstant(10, dl, MVT::i32));
17757 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17759 // This is storing the opcode for MOV32ri.
17760 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17761 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17762 OutChains[0] = DAG.getStore(Root, dl,
17763 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17764 Trmp, MachinePointerInfo(TrmpAddr),
17767 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17768 DAG.getConstant(1, dl, MVT::i32));
17769 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17770 MachinePointerInfo(TrmpAddr, 1),
17773 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17774 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17775 DAG.getConstant(5, dl, MVT::i32));
17776 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17777 Addr, MachinePointerInfo(TrmpAddr, 5),
17780 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17781 DAG.getConstant(6, dl, MVT::i32));
17782 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17783 MachinePointerInfo(TrmpAddr, 6),
17786 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17790 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17791 SelectionDAG &DAG) const {
17793 The rounding mode is in bits 11:10 of FPSR, and has the following
17795 00 Round to nearest
17800 FLT_ROUNDS, on the other hand, expects the following:
17807 To perform the conversion, we do:
17808 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17811 MachineFunction &MF = DAG.getMachineFunction();
17812 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17813 unsigned StackAlignment = TFI.getStackAlignment();
17814 MVT VT = Op.getSimpleValueType();
17817 // Save FP Control Word to stack slot
17818 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17819 SDValue StackSlot =
17820 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17822 MachineMemOperand *MMO =
17823 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17824 MachineMemOperand::MOStore, 2, 2);
17826 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17827 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17828 DAG.getVTList(MVT::Other),
17829 Ops, MVT::i16, MMO);
17831 // Load FP Control Word from stack slot
17832 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17833 MachinePointerInfo(), false, false, false, 0);
17835 // Transform as necessary
17837 DAG.getNode(ISD::SRL, DL, MVT::i16,
17838 DAG.getNode(ISD::AND, DL, MVT::i16,
17839 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17840 DAG.getConstant(11, DL, MVT::i8));
17842 DAG.getNode(ISD::SRL, DL, MVT::i16,
17843 DAG.getNode(ISD::AND, DL, MVT::i16,
17844 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17845 DAG.getConstant(9, DL, MVT::i8));
17848 DAG.getNode(ISD::AND, DL, MVT::i16,
17849 DAG.getNode(ISD::ADD, DL, MVT::i16,
17850 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17851 DAG.getConstant(1, DL, MVT::i16)),
17852 DAG.getConstant(3, DL, MVT::i16));
17854 return DAG.getNode((VT.getSizeInBits() < 16 ?
17855 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17858 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
17860 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
17861 // to 512-bit vector.
17862 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
17863 // ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
17864 // split the vector, perform operation on it's Lo a Hi part and
17865 // concatenate the results.
17866 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
17868 MVT VT = Op.getSimpleValueType();
17869 MVT EltVT = VT.getVectorElementType();
17870 unsigned NumElems = VT.getVectorNumElements();
17872 if (EltVT == MVT::i64 || EltVT == MVT::i32) {
17873 // Extend to 512 bit vector.
17874 assert((VT.is256BitVector() || VT.is128BitVector()) &&
17875 "Unsupported value type for operation");
17877 MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
17878 SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
17879 DAG.getUNDEF(NewVT),
17881 DAG.getIntPtrConstant(0, dl));
17882 SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
17884 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
17885 DAG.getIntPtrConstant(0, dl));
17888 assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
17889 "Unsupported element type");
17891 if (16 < NumElems) {
17892 // Split vector, it's Lo and Hi parts will be handled in next iteration.
17894 std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
17895 MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
17897 Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
17898 Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
17900 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
17903 MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
17905 assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
17906 "Unsupported value type for operation");
17908 // Use native supported vector instruction vplzcntd.
17909 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
17910 SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
17911 SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
17912 SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
17914 return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
17917 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
17918 SelectionDAG &DAG) {
17919 MVT VT = Op.getSimpleValueType();
17921 unsigned NumBits = VT.getSizeInBits();
17924 if (VT.isVector() && Subtarget->hasAVX512())
17925 return LowerVectorCTLZ_AVX512(Op, DAG);
17927 Op = Op.getOperand(0);
17928 if (VT == MVT::i8) {
17929 // Zero extend to i32 since there is not an i8 bsr.
17931 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17934 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17935 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17936 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17938 // If src is zero (i.e. bsr sets ZF), returns NumBits.
17941 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17942 DAG.getConstant(X86::COND_E, dl, MVT::i8),
17945 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17947 // Finally xor with NumBits-1.
17948 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17949 DAG.getConstant(NumBits - 1, dl, OpVT));
17952 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17956 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
17957 SelectionDAG &DAG) {
17958 MVT VT = Op.getSimpleValueType();
17960 unsigned NumBits = VT.getSizeInBits();
17963 if (VT.isVector() && Subtarget->hasAVX512())
17964 return LowerVectorCTLZ_AVX512(Op, DAG);
17966 Op = Op.getOperand(0);
17967 if (VT == MVT::i8) {
17968 // Zero extend to i32 since there is not an i8 bsr.
17970 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17973 // Issue a bsr (scan bits in reverse).
17974 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17975 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17977 // And xor with NumBits-1.
17978 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17979 DAG.getConstant(NumBits - 1, dl, OpVT));
17982 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17986 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17987 MVT VT = Op.getSimpleValueType();
17988 unsigned NumBits = VT.getScalarSizeInBits();
17991 if (VT.isVector()) {
17992 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17994 SDValue N0 = Op.getOperand(0);
17995 SDValue Zero = DAG.getConstant(0, dl, VT);
17997 // lsb(x) = (x & -x)
17998 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17999 DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
18001 // cttz_undef(x) = (width - 1) - ctlz(lsb)
18002 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
18003 TLI.isOperationLegal(ISD::CTLZ, VT)) {
18004 SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
18005 return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
18006 DAG.getNode(ISD::CTLZ, dl, VT, LSB));
18009 // cttz(x) = ctpop(lsb - 1)
18010 SDValue One = DAG.getConstant(1, dl, VT);
18011 return DAG.getNode(ISD::CTPOP, dl, VT,
18012 DAG.getNode(ISD::SUB, dl, VT, LSB, One));
18015 assert(Op.getOpcode() == ISD::CTTZ &&
18016 "Only scalar CTTZ requires custom lowering");
18018 // Issue a bsf (scan bits forward) which also sets EFLAGS.
18019 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18020 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
18022 // If src is zero (i.e. bsf sets ZF), returns NumBits.
18025 DAG.getConstant(NumBits, dl, VT),
18026 DAG.getConstant(X86::COND_E, dl, MVT::i8),
18029 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
18032 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
18033 // ones, and then concatenate the result back.
18034 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
18035 MVT VT = Op.getSimpleValueType();
18037 assert(VT.is256BitVector() && VT.isInteger() &&
18038 "Unsupported value type for operation");
18040 unsigned NumElems = VT.getVectorNumElements();
18043 // Extract the LHS vectors
18044 SDValue LHS = Op.getOperand(0);
18045 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18046 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18048 // Extract the RHS vectors
18049 SDValue RHS = Op.getOperand(1);
18050 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
18051 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
18053 MVT EltVT = VT.getVectorElementType();
18054 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18056 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18057 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18058 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18061 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18062 if (Op.getValueType() == MVT::i1)
18063 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18064 Op.getOperand(0), Op.getOperand(1));
18065 assert(Op.getSimpleValueType().is256BitVector() &&
18066 Op.getSimpleValueType().isInteger() &&
18067 "Only handle AVX 256-bit vector integer operation");
18068 return Lower256IntArith(Op, DAG);
18071 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
18072 if (Op.getValueType() == MVT::i1)
18073 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18074 Op.getOperand(0), Op.getOperand(1));
18075 assert(Op.getSimpleValueType().is256BitVector() &&
18076 Op.getSimpleValueType().isInteger() &&
18077 "Only handle AVX 256-bit vector integer operation");
18078 return Lower256IntArith(Op, DAG);
18081 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
18082 assert(Op.getSimpleValueType().is256BitVector() &&
18083 Op.getSimpleValueType().isInteger() &&
18084 "Only handle AVX 256-bit vector integer operation");
18085 return Lower256IntArith(Op, DAG);
18088 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18089 SelectionDAG &DAG) {
18091 MVT VT = Op.getSimpleValueType();
18094 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
18096 // Decompose 256-bit ops into smaller 128-bit ops.
18097 if (VT.is256BitVector() && !Subtarget->hasInt256())
18098 return Lower256IntArith(Op, DAG);
18100 SDValue A = Op.getOperand(0);
18101 SDValue B = Op.getOperand(1);
18103 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
18104 // pairs, multiply and truncate.
18105 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
18106 if (Subtarget->hasInt256()) {
18107 if (VT == MVT::v32i8) {
18108 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
18109 SDValue Lo = DAG.getIntPtrConstant(0, dl);
18110 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
18111 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
18112 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
18113 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
18114 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
18115 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18116 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
18117 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
18120 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
18121 return DAG.getNode(
18122 ISD::TRUNCATE, dl, VT,
18123 DAG.getNode(ISD::MUL, dl, ExVT,
18124 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
18125 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
18128 assert(VT == MVT::v16i8 &&
18129 "Pre-AVX2 support only supports v16i8 multiplication");
18130 MVT ExVT = MVT::v8i16;
18132 // Extract the lo parts and sign extend to i16
18134 if (Subtarget->hasSSE41()) {
18135 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
18136 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
18138 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
18139 -1, 4, -1, 5, -1, 6, -1, 7};
18140 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18141 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18142 ALo = DAG.getBitcast(ExVT, ALo);
18143 BLo = DAG.getBitcast(ExVT, BLo);
18144 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
18145 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
18148 // Extract the hi parts and sign extend to i16
18150 if (Subtarget->hasSSE41()) {
18151 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
18152 -1, -1, -1, -1, -1, -1, -1, -1};
18153 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18154 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18155 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
18156 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
18158 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
18159 -1, 12, -1, 13, -1, 14, -1, 15};
18160 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18161 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18162 AHi = DAG.getBitcast(ExVT, AHi);
18163 BHi = DAG.getBitcast(ExVT, BHi);
18164 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
18165 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
18168 // Multiply, mask the lower 8bits of the lo/hi results and pack
18169 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
18170 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
18171 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
18172 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
18173 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18176 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18177 if (VT == MVT::v4i32) {
18178 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18179 "Should not custom lower when pmuldq is available!");
18181 // Extract the odd parts.
18182 static const int UnpackMask[] = { 1, -1, 3, -1 };
18183 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18184 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18186 // Multiply the even parts.
18187 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18188 // Now multiply odd parts.
18189 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18191 Evens = DAG.getBitcast(VT, Evens);
18192 Odds = DAG.getBitcast(VT, Odds);
18194 // Merge the two vectors back together with a shuffle. This expands into 2
18196 static const int ShufMask[] = { 0, 4, 2, 6 };
18197 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18200 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18201 "Only know how to lower V2I64/V4I64/V8I64 multiply");
18203 // Ahi = psrlqi(a, 32);
18204 // Bhi = psrlqi(b, 32);
18206 // AloBlo = pmuludq(a, b);
18207 // AloBhi = pmuludq(a, Bhi);
18208 // AhiBlo = pmuludq(Ahi, b);
18210 // AloBhi = psllqi(AloBhi, 32);
18211 // AhiBlo = psllqi(AhiBlo, 32);
18212 // return AloBlo + AloBhi + AhiBlo;
18214 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18215 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18217 SDValue AhiBlo = Ahi;
18218 SDValue AloBhi = Bhi;
18219 // Bit cast to 32-bit vectors for MULUDQ
18220 MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18221 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18222 A = DAG.getBitcast(MulVT, A);
18223 B = DAG.getBitcast(MulVT, B);
18224 Ahi = DAG.getBitcast(MulVT, Ahi);
18225 Bhi = DAG.getBitcast(MulVT, Bhi);
18227 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18228 // After shifting right const values the result may be all-zero.
18229 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
18230 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18231 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18233 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
18234 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18235 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18238 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18239 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18242 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18243 assert(Subtarget->isTargetWin64() && "Unexpected target");
18244 EVT VT = Op.getValueType();
18245 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18246 "Unexpected return type for lowering");
18250 switch (Op->getOpcode()) {
18251 default: llvm_unreachable("Unexpected request for libcall!");
18252 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
18253 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
18254 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
18255 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
18256 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
18257 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18261 SDValue InChain = DAG.getEntryNode();
18263 TargetLowering::ArgListTy Args;
18264 TargetLowering::ArgListEntry Entry;
18265 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18266 EVT ArgVT = Op->getOperand(i).getValueType();
18267 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18268 "Unexpected argument type for lowering");
18269 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18270 Entry.Node = StackPtr;
18271 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18273 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18274 Entry.Ty = PointerType::get(ArgTy,0);
18275 Entry.isSExt = false;
18276 Entry.isZExt = false;
18277 Args.push_back(Entry);
18280 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18281 getPointerTy(DAG.getDataLayout()));
18283 TargetLowering::CallLoweringInfo CLI(DAG);
18284 CLI.setDebugLoc(dl).setChain(InChain)
18285 .setCallee(getLibcallCallingConv(LC),
18286 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18287 Callee, std::move(Args), 0)
18288 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18290 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18291 return DAG.getBitcast(VT, CallInfo.first);
18294 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18295 SelectionDAG &DAG) {
18296 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18297 MVT VT = Op0.getSimpleValueType();
18300 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18301 (VT == MVT::v8i32 && Subtarget->hasInt256()));
18303 // PMULxD operations multiply each even value (starting at 0) of LHS with
18304 // the related value of RHS and produce a widen result.
18305 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18306 // => <2 x i64> <ae|cg>
18308 // In other word, to have all the results, we need to perform two PMULxD:
18309 // 1. one with the even values.
18310 // 2. one with the odd values.
18311 // To achieve #2, with need to place the odd values at an even position.
18313 // Place the odd value at an even position (basically, shift all values 1
18314 // step to the left):
18315 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18316 // <a|b|c|d> => <b|undef|d|undef>
18317 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18318 // <e|f|g|h> => <f|undef|h|undef>
18319 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18321 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18323 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18324 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18326 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18327 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18328 // => <2 x i64> <ae|cg>
18329 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18330 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18331 // => <2 x i64> <bf|dh>
18332 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18334 // Shuffle it back into the right order.
18335 SDValue Highs, Lows;
18336 if (VT == MVT::v8i32) {
18337 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18338 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18339 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18340 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18342 const int HighMask[] = {1, 5, 3, 7};
18343 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18344 const int LowMask[] = {0, 4, 2, 6};
18345 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18348 // If we have a signed multiply but no PMULDQ fix up the high parts of a
18349 // unsigned multiply.
18350 if (IsSigned && !Subtarget->hasSSE41()) {
18351 SDValue ShAmt = DAG.getConstant(
18353 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18354 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18355 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18356 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18357 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18359 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18360 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18363 // The first result of MUL_LOHI is actually the low value, followed by the
18365 SDValue Ops[] = {Lows, Highs};
18366 return DAG.getMergeValues(Ops, dl);
18369 // Return true if the required (according to Opcode) shift-imm form is natively
18370 // supported by the Subtarget
18371 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18373 if (VT.getScalarSizeInBits() < 16)
18376 if (VT.is512BitVector() &&
18377 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18380 bool LShift = VT.is128BitVector() ||
18381 (VT.is256BitVector() && Subtarget->hasInt256());
18383 bool AShift = LShift && (Subtarget->hasVLX() ||
18384 (VT != MVT::v2i64 && VT != MVT::v4i64));
18385 return (Opcode == ISD::SRA) ? AShift : LShift;
18388 // The shift amount is a variable, but it is the same for all vector lanes.
18389 // These instructions are defined together with shift-immediate.
18391 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18393 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18396 // Return true if the required (according to Opcode) variable-shift form is
18397 // natively supported by the Subtarget
18398 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18401 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18404 // vXi16 supported only on AVX-512, BWI
18405 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18408 if (VT.is512BitVector() || Subtarget->hasVLX())
18411 bool LShift = VT.is128BitVector() || VT.is256BitVector();
18412 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
18413 return (Opcode == ISD::SRA) ? AShift : LShift;
18416 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18417 const X86Subtarget *Subtarget) {
18418 MVT VT = Op.getSimpleValueType();
18420 SDValue R = Op.getOperand(0);
18421 SDValue Amt = Op.getOperand(1);
18423 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18424 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18426 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18427 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18428 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18429 SDValue Ex = DAG.getBitcast(ExVT, R);
18431 if (ShiftAmt >= 32) {
18432 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18434 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18435 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18436 ShiftAmt - 32, DAG);
18437 if (VT == MVT::v2i64)
18438 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18439 if (VT == MVT::v4i64)
18440 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18441 {9, 1, 11, 3, 13, 5, 15, 7});
18443 // SRA upper i32, SHL whole i64 and select lower i32.
18444 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18447 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18448 Lower = DAG.getBitcast(ExVT, Lower);
18449 if (VT == MVT::v2i64)
18450 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18451 if (VT == MVT::v4i64)
18452 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18453 {8, 1, 10, 3, 12, 5, 14, 7});
18455 return DAG.getBitcast(VT, Ex);
18458 // Optimize shl/srl/sra with constant shift amount.
18459 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18460 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18461 uint64_t ShiftAmt = ShiftConst->getZExtValue();
18463 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18464 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18466 // i64 SRA needs to be performed as partial shifts.
18467 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18468 Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18469 return ArithmeticShiftRight64(ShiftAmt);
18471 if (VT == MVT::v16i8 ||
18472 (Subtarget->hasInt256() && VT == MVT::v32i8) ||
18473 VT == MVT::v64i8) {
18474 unsigned NumElts = VT.getVectorNumElements();
18475 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18477 // Simple i8 add case
18478 if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18479 return DAG.getNode(ISD::ADD, dl, VT, R, R);
18481 // ashr(R, 7) === cmp_slt(R, 0)
18482 if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18483 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18484 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18487 // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18488 if (VT == MVT::v16i8 && Subtarget->hasXOP())
18491 if (Op.getOpcode() == ISD::SHL) {
18492 // Make a large shift.
18493 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18495 SHL = DAG.getBitcast(VT, SHL);
18496 // Zero out the rightmost bits.
18497 return DAG.getNode(ISD::AND, dl, VT, SHL,
18498 DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, VT));
18500 if (Op.getOpcode() == ISD::SRL) {
18501 // Make a large shift.
18502 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18504 SRL = DAG.getBitcast(VT, SRL);
18505 // Zero out the leftmost bits.
18506 return DAG.getNode(ISD::AND, dl, VT, SRL,
18507 DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
18509 if (Op.getOpcode() == ISD::SRA) {
18510 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18511 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18513 SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
18514 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18515 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18518 llvm_unreachable("Unknown shift opcode.");
18523 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18524 if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18525 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18527 // Peek through any splat that was introduced for i64 shift vectorization.
18528 int SplatIndex = -1;
18529 if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18530 if (SVN->isSplat()) {
18531 SplatIndex = SVN->getSplatIndex();
18532 Amt = Amt.getOperand(0);
18533 assert(SplatIndex < (int)VT.getVectorNumElements() &&
18534 "Splat shuffle referencing second operand");
18537 if (Amt.getOpcode() != ISD::BITCAST ||
18538 Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18541 Amt = Amt.getOperand(0);
18542 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18543 VT.getVectorNumElements();
18544 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18545 uint64_t ShiftAmt = 0;
18546 unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18547 for (unsigned i = 0; i != Ratio; ++i) {
18548 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18552 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18555 // Check remaining shift amounts (if not a splat).
18556 if (SplatIndex < 0) {
18557 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18558 uint64_t ShAmt = 0;
18559 for (unsigned j = 0; j != Ratio; ++j) {
18560 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18564 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18566 if (ShAmt != ShiftAmt)
18571 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18572 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18574 if (Op.getOpcode() == ISD::SRA)
18575 return ArithmeticShiftRight64(ShiftAmt);
18581 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18582 const X86Subtarget* Subtarget) {
18583 MVT VT = Op.getSimpleValueType();
18585 SDValue R = Op.getOperand(0);
18586 SDValue Amt = Op.getOperand(1);
18588 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18589 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18591 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18592 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18594 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18596 MVT EltVT = VT.getVectorElementType();
18598 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18599 // Check if this build_vector node is doing a splat.
18600 // If so, then set BaseShAmt equal to the splat value.
18601 BaseShAmt = BV->getSplatValue();
18602 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18603 BaseShAmt = SDValue();
18605 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18606 Amt = Amt.getOperand(0);
18608 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18609 if (SVN && SVN->isSplat()) {
18610 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18611 SDValue InVec = Amt.getOperand(0);
18612 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18613 assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18614 "Unexpected shuffle index found!");
18615 BaseShAmt = InVec.getOperand(SplatIdx);
18616 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18617 if (ConstantSDNode *C =
18618 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18619 if (C->getZExtValue() == SplatIdx)
18620 BaseShAmt = InVec.getOperand(1);
18625 // Avoid introducing an extract element from a shuffle.
18626 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18627 DAG.getIntPtrConstant(SplatIdx, dl));
18631 if (BaseShAmt.getNode()) {
18632 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18633 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18634 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18635 else if (EltVT.bitsLT(MVT::i32))
18636 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18638 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18642 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18643 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
18644 Amt.getOpcode() == ISD::BITCAST &&
18645 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18646 Amt = Amt.getOperand(0);
18647 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18648 VT.getVectorNumElements();
18649 std::vector<SDValue> Vals(Ratio);
18650 for (unsigned i = 0; i != Ratio; ++i)
18651 Vals[i] = Amt.getOperand(i);
18652 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18653 for (unsigned j = 0; j != Ratio; ++j)
18654 if (Vals[j] != Amt.getOperand(i + j))
18658 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18659 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18664 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18665 SelectionDAG &DAG) {
18666 MVT VT = Op.getSimpleValueType();
18668 SDValue R = Op.getOperand(0);
18669 SDValue Amt = Op.getOperand(1);
18671 assert(VT.isVector() && "Custom lowering only for vector shifts!");
18672 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18674 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18677 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18680 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18683 // XOP has 128-bit variable logical/arithmetic shifts.
18684 // +ve/-ve Amt = shift left/right.
18685 if (Subtarget->hasXOP() &&
18686 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18687 VT == MVT::v8i16 || VT == MVT::v16i8)) {
18688 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18689 SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18690 Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18692 if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18693 return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18694 if (Op.getOpcode() == ISD::SRA)
18695 return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18698 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18699 // shifts per-lane and then shuffle the partial results back together.
18700 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18701 // Splat the shift amounts so the scalar shifts above will catch it.
18702 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18703 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18704 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18705 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18706 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18709 // i64 vector arithmetic shift can be emulated with the transform:
18710 // M = lshr(SIGN_BIT, Amt)
18711 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18712 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18713 Op.getOpcode() == ISD::SRA) {
18714 SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18715 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18716 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18717 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18718 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18722 // If possible, lower this packed shift into a vector multiply instead of
18723 // expanding it into a sequence of scalar shifts.
18724 // Do this only if the vector shift count is a constant build_vector.
18725 if (Op.getOpcode() == ISD::SHL &&
18726 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18727 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18728 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18729 SmallVector<SDValue, 8> Elts;
18730 MVT SVT = VT.getVectorElementType();
18731 unsigned SVTBits = SVT.getSizeInBits();
18732 APInt One(SVTBits, 1);
18733 unsigned NumElems = VT.getVectorNumElements();
18735 for (unsigned i=0; i !=NumElems; ++i) {
18736 SDValue Op = Amt->getOperand(i);
18737 if (Op->getOpcode() == ISD::UNDEF) {
18738 Elts.push_back(Op);
18742 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18743 APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18744 uint64_t ShAmt = C.getZExtValue();
18745 if (ShAmt >= SVTBits) {
18746 Elts.push_back(DAG.getUNDEF(SVT));
18749 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18751 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18752 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18755 // Lower SHL with variable shift amount.
18756 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18757 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18759 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18760 DAG.getConstant(0x3f800000U, dl, VT));
18761 Op = DAG.getBitcast(MVT::v4f32, Op);
18762 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18763 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18766 // If possible, lower this shift as a sequence of two shifts by
18767 // constant plus a MOVSS/MOVSD instead of scalarizing it.
18769 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18771 // Could be rewritten as:
18772 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18774 // The advantage is that the two shifts from the example would be
18775 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18776 // the vector shift into four scalar shifts plus four pairs of vector
18778 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18779 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18780 unsigned TargetOpcode = X86ISD::MOVSS;
18781 bool CanBeSimplified;
18782 // The splat value for the first packed shift (the 'X' from the example).
18783 SDValue Amt1 = Amt->getOperand(0);
18784 // The splat value for the second packed shift (the 'Y' from the example).
18785 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18786 Amt->getOperand(2);
18788 // See if it is possible to replace this node with a sequence of
18789 // two shifts followed by a MOVSS/MOVSD
18790 if (VT == MVT::v4i32) {
18791 // Check if it is legal to use a MOVSS.
18792 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18793 Amt2 == Amt->getOperand(3);
18794 if (!CanBeSimplified) {
18795 // Otherwise, check if we can still simplify this node using a MOVSD.
18796 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18797 Amt->getOperand(2) == Amt->getOperand(3);
18798 TargetOpcode = X86ISD::MOVSD;
18799 Amt2 = Amt->getOperand(2);
18802 // Do similar checks for the case where the machine value type
18804 CanBeSimplified = Amt1 == Amt->getOperand(1);
18805 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18806 CanBeSimplified = Amt2 == Amt->getOperand(i);
18808 if (!CanBeSimplified) {
18809 TargetOpcode = X86ISD::MOVSD;
18810 CanBeSimplified = true;
18811 Amt2 = Amt->getOperand(4);
18812 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18813 CanBeSimplified = Amt1 == Amt->getOperand(i);
18814 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18815 CanBeSimplified = Amt2 == Amt->getOperand(j);
18819 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18820 isa<ConstantSDNode>(Amt2)) {
18821 // Replace this node with two shifts followed by a MOVSS/MOVSD.
18822 MVT CastVT = MVT::v4i32;
18824 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18825 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18827 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18828 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18829 if (TargetOpcode == X86ISD::MOVSD)
18830 CastVT = MVT::v2i64;
18831 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18832 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18833 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18835 return DAG.getBitcast(VT, Result);
18839 // v4i32 Non Uniform Shifts.
18840 // If the shift amount is constant we can shift each lane using the SSE2
18841 // immediate shifts, else we need to zero-extend each lane to the lower i64
18842 // and shift using the SSE2 variable shifts.
18843 // The separate results can then be blended together.
18844 if (VT == MVT::v4i32) {
18845 unsigned Opc = Op.getOpcode();
18846 SDValue Amt0, Amt1, Amt2, Amt3;
18847 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18848 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18849 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18850 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18851 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18853 // ISD::SHL is handled above but we include it here for completeness.
18856 llvm_unreachable("Unknown target vector shift node");
18858 Opc = X86ISD::VSHL;
18861 Opc = X86ISD::VSRL;
18864 Opc = X86ISD::VSRA;
18867 // The SSE2 shifts use the lower i64 as the same shift amount for
18868 // all lanes and the upper i64 is ignored. These shuffle masks
18869 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18870 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18871 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18872 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18873 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18874 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18877 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18878 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18879 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18880 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18881 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18882 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18883 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18886 if (VT == MVT::v16i8 ||
18887 (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18888 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18889 unsigned ShiftOpcode = Op->getOpcode();
18891 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18892 // On SSE41 targets we make use of the fact that VSELECT lowers
18893 // to PBLENDVB which selects bytes based just on the sign bit.
18894 if (Subtarget->hasSSE41()) {
18895 V0 = DAG.getBitcast(VT, V0);
18896 V1 = DAG.getBitcast(VT, V1);
18897 Sel = DAG.getBitcast(VT, Sel);
18898 return DAG.getBitcast(SelVT,
18899 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18901 // On pre-SSE41 targets we test for the sign bit by comparing to
18902 // zero - a negative value will set all bits of the lanes to true
18903 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18904 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18905 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18906 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18909 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18910 // We can safely do this using i16 shifts as we're only interested in
18911 // the 3 lower bits of each byte.
18912 Amt = DAG.getBitcast(ExtVT, Amt);
18913 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18914 Amt = DAG.getBitcast(VT, Amt);
18916 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18917 // r = VSELECT(r, shift(r, 4), a);
18919 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18920 R = SignBitSelect(VT, Amt, M, R);
18923 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18925 // r = VSELECT(r, shift(r, 2), a);
18926 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18927 R = SignBitSelect(VT, Amt, M, R);
18930 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18932 // return VSELECT(r, shift(r, 1), a);
18933 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18934 R = SignBitSelect(VT, Amt, M, R);
18938 if (Op->getOpcode() == ISD::SRA) {
18939 // For SRA we need to unpack each byte to the higher byte of a i16 vector
18940 // so we can correctly sign extend. We don't care what happens to the
18942 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18943 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18944 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18945 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18946 ALo = DAG.getBitcast(ExtVT, ALo);
18947 AHi = DAG.getBitcast(ExtVT, AHi);
18948 RLo = DAG.getBitcast(ExtVT, RLo);
18949 RHi = DAG.getBitcast(ExtVT, RHi);
18951 // r = VSELECT(r, shift(r, 4), a);
18952 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18953 DAG.getConstant(4, dl, ExtVT));
18954 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18955 DAG.getConstant(4, dl, ExtVT));
18956 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18957 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18960 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18961 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18963 // r = VSELECT(r, shift(r, 2), a);
18964 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18965 DAG.getConstant(2, dl, ExtVT));
18966 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18967 DAG.getConstant(2, dl, ExtVT));
18968 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18969 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18972 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18973 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18975 // r = VSELECT(r, shift(r, 1), a);
18976 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18977 DAG.getConstant(1, dl, ExtVT));
18978 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18979 DAG.getConstant(1, dl, ExtVT));
18980 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18981 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18983 // Logical shift the result back to the lower byte, leaving a zero upper
18985 // meaning that we can safely pack with PACKUSWB.
18987 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18989 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18990 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18994 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18995 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18996 // solution better.
18997 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18998 MVT ExtVT = MVT::v8i32;
19000 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
19001 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
19002 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
19003 return DAG.getNode(ISD::TRUNCATE, dl, VT,
19004 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
19007 if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
19008 MVT ExtVT = MVT::v8i32;
19009 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
19010 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
19011 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
19012 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
19013 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
19014 ALo = DAG.getBitcast(ExtVT, ALo);
19015 AHi = DAG.getBitcast(ExtVT, AHi);
19016 RLo = DAG.getBitcast(ExtVT, RLo);
19017 RHi = DAG.getBitcast(ExtVT, RHi);
19018 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
19019 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
19020 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
19021 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
19022 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
19025 if (VT == MVT::v8i16) {
19026 unsigned ShiftOpcode = Op->getOpcode();
19028 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
19029 // On SSE41 targets we make use of the fact that VSELECT lowers
19030 // to PBLENDVB which selects bytes based just on the sign bit.
19031 if (Subtarget->hasSSE41()) {
19032 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
19033 V0 = DAG.getBitcast(ExtVT, V0);
19034 V1 = DAG.getBitcast(ExtVT, V1);
19035 Sel = DAG.getBitcast(ExtVT, Sel);
19036 return DAG.getBitcast(
19037 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
19039 // On pre-SSE41 targets we splat the sign bit - a negative value will
19040 // set all bits of the lanes to true and VSELECT uses that in
19041 // its OR(AND(V0,C),AND(V1,~C)) lowering.
19043 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
19044 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
19047 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
19048 if (Subtarget->hasSSE41()) {
19049 // On SSE41 targets we need to replicate the shift mask in both
19050 // bytes for PBLENDVB.
19053 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
19054 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
19056 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
19059 // r = VSELECT(r, shift(r, 8), a);
19060 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
19061 R = SignBitSelect(Amt, M, R);
19064 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19066 // r = VSELECT(r, shift(r, 4), a);
19067 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19068 R = SignBitSelect(Amt, M, R);
19071 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19073 // r = VSELECT(r, shift(r, 2), a);
19074 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19075 R = SignBitSelect(Amt, M, R);
19078 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19080 // return VSELECT(r, shift(r, 1), a);
19081 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19082 R = SignBitSelect(Amt, M, R);
19086 // Decompose 256-bit shifts into smaller 128-bit shifts.
19087 if (VT.is256BitVector()) {
19088 unsigned NumElems = VT.getVectorNumElements();
19089 MVT EltVT = VT.getVectorElementType();
19090 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
19092 // Extract the two vectors
19093 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
19094 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
19096 // Recreate the shift amount vectors
19097 SDValue Amt1, Amt2;
19098 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
19099 // Constant shift amount
19100 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
19101 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
19102 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
19104 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
19105 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
19107 // Variable shift amount
19108 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
19109 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
19112 // Issue new vector shifts for the smaller types
19113 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
19114 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
19116 // Concatenate the result back
19117 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
19123 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
19124 SelectionDAG &DAG) {
19125 MVT VT = Op.getSimpleValueType();
19127 SDValue R = Op.getOperand(0);
19128 SDValue Amt = Op.getOperand(1);
19130 assert(VT.isVector() && "Custom lowering only for vector rotates!");
19131 assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
19132 assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
19134 // XOP has 128-bit vector variable + immediate rotates.
19135 // +ve/-ve Amt = rotate left/right.
19137 // Split 256-bit integers.
19138 if (VT.is256BitVector())
19139 return Lower256IntArith(Op, DAG);
19141 assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
19143 // Attempt to rotate by immediate.
19144 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
19145 if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
19146 uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
19147 assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
19148 return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
19149 DAG.getConstant(RotateAmt, DL, MVT::i8));
19153 // Use general rotate by variable (per-element).
19154 return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
19157 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
19158 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
19159 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
19160 // looks for this combo and may remove the "setcc" instruction if the "setcc"
19161 // has only one use.
19162 SDNode *N = Op.getNode();
19163 SDValue LHS = N->getOperand(0);
19164 SDValue RHS = N->getOperand(1);
19165 unsigned BaseOp = 0;
19168 switch (Op.getOpcode()) {
19169 default: llvm_unreachable("Unknown ovf instruction!");
19171 // A subtract of one will be selected as a INC. Note that INC doesn't
19172 // set CF, so we can't do this for UADDO.
19173 if (isOneConstant(RHS)) {
19174 BaseOp = X86ISD::INC;
19175 Cond = X86::COND_O;
19178 BaseOp = X86ISD::ADD;
19179 Cond = X86::COND_O;
19182 BaseOp = X86ISD::ADD;
19183 Cond = X86::COND_B;
19186 // A subtract of one will be selected as a DEC. Note that DEC doesn't
19187 // set CF, so we can't do this for USUBO.
19188 if (isOneConstant(RHS)) {
19189 BaseOp = X86ISD::DEC;
19190 Cond = X86::COND_O;
19193 BaseOp = X86ISD::SUB;
19194 Cond = X86::COND_O;
19197 BaseOp = X86ISD::SUB;
19198 Cond = X86::COND_B;
19201 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
19202 Cond = X86::COND_O;
19204 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
19205 if (N->getValueType(0) == MVT::i8) {
19206 BaseOp = X86ISD::UMUL8;
19207 Cond = X86::COND_O;
19210 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
19212 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
19215 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19216 DAG.getConstant(X86::COND_O, DL, MVT::i32),
19217 SDValue(Sum.getNode(), 2));
19219 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19223 // Also sets EFLAGS.
19224 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
19225 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
19228 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
19229 DAG.getConstant(Cond, DL, MVT::i32),
19230 SDValue(Sum.getNode(), 1));
19232 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19235 /// Returns true if the operand type is exactly twice the native width, and
19236 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
19237 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
19238 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
19239 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
19240 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
19243 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
19244 else if (OpWidth == 128)
19245 return Subtarget->hasCmpxchg16b();
19250 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
19251 return needsCmpXchgNb(SI->getValueOperand()->getType());
19254 // Note: this turns large loads into lock cmpxchg8b/16b.
19255 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
19256 TargetLowering::AtomicExpansionKind
19257 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
19258 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
19259 return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
19260 : AtomicExpansionKind::None;
19263 TargetLowering::AtomicExpansionKind
19264 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
19265 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19266 Type *MemType = AI->getType();
19268 // If the operand is too big, we must see if cmpxchg8/16b is available
19269 // and default to library calls otherwise.
19270 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
19271 return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
19272 : AtomicExpansionKind::None;
19275 AtomicRMWInst::BinOp Op = AI->getOperation();
19278 llvm_unreachable("Unknown atomic operation");
19279 case AtomicRMWInst::Xchg:
19280 case AtomicRMWInst::Add:
19281 case AtomicRMWInst::Sub:
19282 // It's better to use xadd, xsub or xchg for these in all cases.
19283 return AtomicExpansionKind::None;
19284 case AtomicRMWInst::Or:
19285 case AtomicRMWInst::And:
19286 case AtomicRMWInst::Xor:
19287 // If the atomicrmw's result isn't actually used, we can just add a "lock"
19288 // prefix to a normal instruction for these operations.
19289 return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
19290 : AtomicExpansionKind::None;
19291 case AtomicRMWInst::Nand:
19292 case AtomicRMWInst::Max:
19293 case AtomicRMWInst::Min:
19294 case AtomicRMWInst::UMax:
19295 case AtomicRMWInst::UMin:
19296 // These always require a non-trivial set of data operations on x86. We must
19297 // use a cmpxchg loop.
19298 return AtomicExpansionKind::CmpXChg;
19302 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19303 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19304 // no-sse2). There isn't any reason to disable it if the target processor
19306 return Subtarget.hasSSE2() || Subtarget.is64Bit();
19310 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19311 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19312 Type *MemType = AI->getType();
19313 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19314 // there is no benefit in turning such RMWs into loads, and it is actually
19315 // harmful as it introduces a mfence.
19316 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19319 auto Builder = IRBuilder<>(AI);
19320 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19321 auto SynchScope = AI->getSynchScope();
19322 // We must restrict the ordering to avoid generating loads with Release or
19323 // ReleaseAcquire orderings.
19324 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19325 auto Ptr = AI->getPointerOperand();
19327 // Before the load we need a fence. Here is an example lifted from
19328 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19331 // x.store(1, relaxed);
19332 // r1 = y.fetch_add(0, release);
19334 // y.fetch_add(42, acquire);
19335 // r2 = x.load(relaxed);
19336 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19337 // lowered to just a load without a fence. A mfence flushes the store buffer,
19338 // making the optimization clearly correct.
19339 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19340 // otherwise, we might be able to be more aggressive on relaxed idempotent
19341 // rmw. In practice, they do not look useful, so we don't try to be
19342 // especially clever.
19343 if (SynchScope == SingleThread)
19344 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19345 // the IR level, so we must wrap it in an intrinsic.
19348 if (!hasMFENCE(*Subtarget))
19349 // FIXME: it might make sense to use a locked operation here but on a
19350 // different cache-line to prevent cache-line bouncing. In practice it
19351 // is probably a small win, and x86 processors without mfence are rare
19352 // enough that we do not bother.
19356 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19357 Builder.CreateCall(MFence, {});
19359 // Finally we can emit the atomic load.
19360 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19361 AI->getType()->getPrimitiveSizeInBits());
19362 Loaded->setAtomic(Order, SynchScope);
19363 AI->replaceAllUsesWith(Loaded);
19364 AI->eraseFromParent();
19368 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19369 SelectionDAG &DAG) {
19371 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19372 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19373 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19374 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19376 // The only fence that needs an instruction is a sequentially-consistent
19377 // cross-thread fence.
19378 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19379 if (hasMFENCE(*Subtarget))
19380 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19382 SDValue Chain = Op.getOperand(0);
19383 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19385 DAG.getRegister(X86::ESP, MVT::i32), // Base
19386 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
19387 DAG.getRegister(0, MVT::i32), // Index
19388 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
19389 DAG.getRegister(0, MVT::i32), // Segment.
19393 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19394 return SDValue(Res, 0);
19397 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19398 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19401 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19402 SelectionDAG &DAG) {
19403 MVT T = Op.getSimpleValueType();
19407 switch(T.SimpleTy) {
19408 default: llvm_unreachable("Invalid value type!");
19409 case MVT::i8: Reg = X86::AL; size = 1; break;
19410 case MVT::i16: Reg = X86::AX; size = 2; break;
19411 case MVT::i32: Reg = X86::EAX; size = 4; break;
19413 assert(Subtarget->is64Bit() && "Node not type legal!");
19414 Reg = X86::RAX; size = 8;
19417 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19418 Op.getOperand(2), SDValue());
19419 SDValue Ops[] = { cpIn.getValue(0),
19422 DAG.getTargetConstant(size, DL, MVT::i8),
19423 cpIn.getValue(1) };
19424 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19425 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19426 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19430 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19431 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19432 MVT::i32, cpOut.getValue(2));
19433 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19434 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19437 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19438 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19439 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19443 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19444 SelectionDAG &DAG) {
19445 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19446 MVT DstVT = Op.getSimpleValueType();
19448 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19449 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19450 if (DstVT != MVT::f64)
19451 // This conversion needs to be expanded.
19454 SDValue InVec = Op->getOperand(0);
19456 unsigned NumElts = SrcVT.getVectorNumElements();
19457 MVT SVT = SrcVT.getVectorElementType();
19459 // Widen the vector in input in the case of MVT::v2i32.
19460 // Example: from MVT::v2i32 to MVT::v4i32.
19461 SmallVector<SDValue, 16> Elts;
19462 for (unsigned i = 0, e = NumElts; i != e; ++i)
19463 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19464 DAG.getIntPtrConstant(i, dl)));
19466 // Explicitly mark the extra elements as Undef.
19467 Elts.append(NumElts, DAG.getUNDEF(SVT));
19469 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19470 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19471 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19472 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19473 DAG.getIntPtrConstant(0, dl));
19476 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19477 Subtarget->hasMMX() && "Unexpected custom BITCAST");
19478 assert((DstVT == MVT::i64 ||
19479 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19480 "Unexpected custom BITCAST");
19481 // i64 <=> MMX conversions are Legal.
19482 if (SrcVT==MVT::i64 && DstVT.isVector())
19484 if (DstVT==MVT::i64 && SrcVT.isVector())
19486 // MMX <=> MMX conversions are Legal.
19487 if (SrcVT.isVector() && DstVT.isVector())
19489 // All other conversions need to be expanded.
19493 /// Compute the horizontal sum of bytes in V for the elements of VT.
19495 /// Requires V to be a byte vector and VT to be an integer vector type with
19496 /// wider elements than V's type. The width of the elements of VT determines
19497 /// how many bytes of V are summed horizontally to produce each element of the
19499 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19500 const X86Subtarget *Subtarget,
19501 SelectionDAG &DAG) {
19503 MVT ByteVecVT = V.getSimpleValueType();
19504 MVT EltVT = VT.getVectorElementType();
19505 int NumElts = VT.getVectorNumElements();
19506 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19507 "Expected value to have byte element type.");
19508 assert(EltVT != MVT::i8 &&
19509 "Horizontal byte sum only makes sense for wider elements!");
19510 unsigned VecSize = VT.getSizeInBits();
19511 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19513 // PSADBW instruction horizontally add all bytes and leave the result in i64
19514 // chunks, thus directly computes the pop count for v2i64 and v4i64.
19515 if (EltVT == MVT::i64) {
19516 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19517 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19518 V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
19519 return DAG.getBitcast(VT, V);
19522 if (EltVT == MVT::i32) {
19523 // We unpack the low half and high half into i32s interleaved with zeros so
19524 // that we can use PSADBW to horizontally sum them. The most useful part of
19525 // this is that it lines up the results of two PSADBW instructions to be
19526 // two v2i64 vectors which concatenated are the 4 population counts. We can
19527 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19528 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19529 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19530 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19532 // Do the horizontal sums into two v2i64s.
19533 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19534 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19535 Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19536 DAG.getBitcast(ByteVecVT, Low), Zeros);
19537 High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19538 DAG.getBitcast(ByteVecVT, High), Zeros);
19540 // Merge them together.
19541 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19542 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19543 DAG.getBitcast(ShortVecVT, Low),
19544 DAG.getBitcast(ShortVecVT, High));
19546 return DAG.getBitcast(VT, V);
19549 // The only element type left is i16.
19550 assert(EltVT == MVT::i16 && "Unknown how to handle type");
19552 // To obtain pop count for each i16 element starting from the pop count for
19553 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19554 // right by 8. It is important to shift as i16s as i8 vector shift isn't
19555 // directly supported.
19556 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19557 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19558 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19559 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19560 DAG.getBitcast(ByteVecVT, V));
19561 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19564 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19565 const X86Subtarget *Subtarget,
19566 SelectionDAG &DAG) {
19567 MVT VT = Op.getSimpleValueType();
19568 MVT EltVT = VT.getVectorElementType();
19569 unsigned VecSize = VT.getSizeInBits();
19571 // Implement a lookup table in register by using an algorithm based on:
19572 // http://wm.ite.pl/articles/sse-popcount.html
19574 // The general idea is that every lower byte nibble in the input vector is an
19575 // index into a in-register pre-computed pop count table. We then split up the
19576 // input vector in two new ones: (1) a vector with only the shifted-right
19577 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19578 // masked out higher ones) for each byte. PSHUB is used separately with both
19579 // to index the in-register table. Next, both are added and the result is a
19580 // i8 vector where each element contains the pop count for input byte.
19582 // To obtain the pop count for elements != i8, we follow up with the same
19583 // approach and use additional tricks as described below.
19585 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19586 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19587 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19588 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19590 int NumByteElts = VecSize / 8;
19591 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19592 SDValue In = DAG.getBitcast(ByteVecVT, Op);
19593 SmallVector<SDValue, 16> LUTVec;
19594 for (int i = 0; i < NumByteElts; ++i)
19595 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19596 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19597 SmallVector<SDValue, 16> Mask0F(NumByteElts,
19598 DAG.getConstant(0x0F, DL, MVT::i8));
19599 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19602 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19603 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19604 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19607 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19609 // The input vector is used as the shuffle mask that index elements into the
19610 // LUT. After counting low and high nibbles, add the vector to obtain the
19611 // final pop count per i8 element.
19612 SDValue HighPopCnt =
19613 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19614 SDValue LowPopCnt =
19615 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19616 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19618 if (EltVT == MVT::i8)
19621 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19624 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19625 const X86Subtarget *Subtarget,
19626 SelectionDAG &DAG) {
19627 MVT VT = Op.getSimpleValueType();
19628 assert(VT.is128BitVector() &&
19629 "Only 128-bit vector bitmath lowering supported.");
19631 int VecSize = VT.getSizeInBits();
19632 MVT EltVT = VT.getVectorElementType();
19633 int Len = EltVT.getSizeInBits();
19635 // This is the vectorized version of the "best" algorithm from
19636 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19637 // with a minor tweak to use a series of adds + shifts instead of vector
19638 // multiplications. Implemented for all integer vector types. We only use
19639 // this when we don't have SSSE3 which allows a LUT-based lowering that is
19640 // much faster, even faster than using native popcnt instructions.
19642 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19643 MVT VT = V.getSimpleValueType();
19644 SmallVector<SDValue, 32> Shifters(
19645 VT.getVectorNumElements(),
19646 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19647 return DAG.getNode(OpCode, DL, VT, V,
19648 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19650 auto GetMask = [&](SDValue V, APInt Mask) {
19651 MVT VT = V.getSimpleValueType();
19652 SmallVector<SDValue, 32> Masks(
19653 VT.getVectorNumElements(),
19654 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19655 return DAG.getNode(ISD::AND, DL, VT, V,
19656 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19659 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19660 // x86, so set the SRL type to have elements at least i16 wide. This is
19661 // correct because all of our SRLs are followed immediately by a mask anyways
19662 // that handles any bits that sneak into the high bits of the byte elements.
19663 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19667 // v = v - ((v >> 1) & 0x55555555...)
19669 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19670 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19671 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19673 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19674 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19675 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19676 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19677 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19679 // v = (v + (v >> 4)) & 0x0F0F0F0F...
19680 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19681 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19682 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19684 // At this point, V contains the byte-wise population count, and we are
19685 // merely doing a horizontal sum if necessary to get the wider element
19687 if (EltVT == MVT::i8)
19690 return LowerHorizontalByteSum(
19691 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19695 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19696 SelectionDAG &DAG) {
19697 MVT VT = Op.getSimpleValueType();
19698 // FIXME: Need to add AVX-512 support here!
19699 assert((VT.is256BitVector() || VT.is128BitVector()) &&
19700 "Unknown CTPOP type to handle");
19701 SDLoc DL(Op.getNode());
19702 SDValue Op0 = Op.getOperand(0);
19704 if (!Subtarget->hasSSSE3()) {
19705 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19706 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19707 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19710 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19711 unsigned NumElems = VT.getVectorNumElements();
19713 // Extract each 128-bit vector, compute pop count and concat the result.
19714 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19715 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19717 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19718 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19719 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19722 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19725 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19726 SelectionDAG &DAG) {
19727 assert(Op.getSimpleValueType().isVector() &&
19728 "We only do custom lowering for vector population count.");
19729 return LowerVectorCTPOP(Op, Subtarget, DAG);
19732 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19733 SDNode *Node = Op.getNode();
19735 EVT T = Node->getValueType(0);
19736 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19737 DAG.getConstant(0, dl, T), Node->getOperand(2));
19738 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19739 cast<AtomicSDNode>(Node)->getMemoryVT(),
19740 Node->getOperand(0),
19741 Node->getOperand(1), negOp,
19742 cast<AtomicSDNode>(Node)->getMemOperand(),
19743 cast<AtomicSDNode>(Node)->getOrdering(),
19744 cast<AtomicSDNode>(Node)->getSynchScope());
19747 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19748 SDNode *Node = Op.getNode();
19750 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19752 // Convert seq_cst store -> xchg
19753 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19754 // FIXME: On 32-bit, store -> fist or movq would be more efficient
19755 // (The only way to get a 16-byte store is cmpxchg16b)
19756 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19757 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19758 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19759 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19760 cast<AtomicSDNode>(Node)->getMemoryVT(),
19761 Node->getOperand(0),
19762 Node->getOperand(1), Node->getOperand(2),
19763 cast<AtomicSDNode>(Node)->getMemOperand(),
19764 cast<AtomicSDNode>(Node)->getOrdering(),
19765 cast<AtomicSDNode>(Node)->getSynchScope());
19766 return Swap.getValue(1);
19768 // Other atomic stores have a simple pattern.
19772 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19773 MVT VT = Op.getNode()->getSimpleValueType(0);
19775 // Let legalize expand this if it isn't a legal type yet.
19776 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19779 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19782 bool ExtraOp = false;
19783 switch (Op.getOpcode()) {
19784 default: llvm_unreachable("Invalid code");
19785 case ISD::ADDC: Opc = X86ISD::ADD; break;
19786 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19787 case ISD::SUBC: Opc = X86ISD::SUB; break;
19788 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19792 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19794 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19795 Op.getOperand(1), Op.getOperand(2));
19798 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19799 SelectionDAG &DAG) {
19800 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19802 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19803 // which returns the values as { float, float } (in XMM0) or
19804 // { double, double } (which is returned in XMM0, XMM1).
19806 SDValue Arg = Op.getOperand(0);
19807 EVT ArgVT = Arg.getValueType();
19808 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19810 TargetLowering::ArgListTy Args;
19811 TargetLowering::ArgListEntry Entry;
19815 Entry.isSExt = false;
19816 Entry.isZExt = false;
19817 Args.push_back(Entry);
19819 bool isF64 = ArgVT == MVT::f64;
19820 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19821 // the small struct {f32, f32} is returned in (eax, edx). For f64,
19822 // the results are returned via SRet in memory.
19823 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
19824 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19826 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19828 Type *RetTy = isF64
19829 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19830 : (Type*)VectorType::get(ArgTy, 4);
19832 TargetLowering::CallLoweringInfo CLI(DAG);
19833 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19834 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19836 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19839 // Returned in xmm0 and xmm1.
19840 return CallResult.first;
19842 // Returned in bits 0:31 and 32:64 xmm0.
19843 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19844 CallResult.first, DAG.getIntPtrConstant(0, dl));
19845 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19846 CallResult.first, DAG.getIntPtrConstant(1, dl));
19847 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19848 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19851 /// Widen a vector input to a vector of NVT. The
19852 /// input vector must have the same element type as NVT.
19853 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
19854 bool FillWithZeroes = false) {
19855 // Check if InOp already has the right width.
19856 MVT InVT = InOp.getSimpleValueType();
19860 if (InOp.isUndef())
19861 return DAG.getUNDEF(NVT);
19863 assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
19864 "input and widen element type must match");
19866 unsigned InNumElts = InVT.getVectorNumElements();
19867 unsigned WidenNumElts = NVT.getVectorNumElements();
19868 assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
19869 "Unexpected request for vector widening");
19871 EVT EltVT = NVT.getVectorElementType();
19874 if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
19875 InOp.getNumOperands() == 2) {
19876 SDValue N1 = InOp.getOperand(1);
19877 if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
19879 InOp = InOp.getOperand(0);
19880 InVT = InOp.getSimpleValueType();
19881 InNumElts = InVT.getVectorNumElements();
19884 if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
19885 ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
19886 SmallVector<SDValue, 16> Ops;
19887 for (unsigned i = 0; i < InNumElts; ++i)
19888 Ops.push_back(InOp.getOperand(i));
19890 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
19891 DAG.getUNDEF(EltVT);
19892 for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
19893 Ops.push_back(FillVal);
19894 return DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Ops);
19896 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
19898 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
19899 InOp, DAG.getIntPtrConstant(0, dl));
19902 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19903 SelectionDAG &DAG) {
19904 assert(Subtarget->hasAVX512() &&
19905 "MGATHER/MSCATTER are supported on AVX-512 arch only");
19907 // X86 scatter kills mask register, so its type should be added to
19908 // the list of return values.
19909 // If the "scatter" has 2 return values, it is already handled.
19910 if (Op.getNode()->getNumValues() == 2)
19913 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19914 SDValue Src = N->getValue();
19915 MVT VT = Src.getSimpleValueType();
19916 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19919 SDValue NewScatter;
19920 SDValue Index = N->getIndex();
19921 SDValue Mask = N->getMask();
19922 SDValue Chain = N->getChain();
19923 SDValue BasePtr = N->getBasePtr();
19924 MVT MemVT = N->getMemoryVT().getSimpleVT();
19925 MVT IndexVT = Index.getSimpleValueType();
19926 MVT MaskVT = Mask.getSimpleValueType();
19928 if (MemVT.getScalarSizeInBits() < VT.getScalarSizeInBits()) {
19929 // The v2i32 value was promoted to v2i64.
19930 // Now we "redo" the type legalizer's work and widen the original
19931 // v2i32 value to v4i32. The original v2i32 is retrieved from v2i64
19933 assert((MemVT == MVT::v2i32 && VT == MVT::v2i64) &&
19934 "Unexpected memory type");
19935 int ShuffleMask[] = {0, 2, -1, -1};
19936 Src = DAG.getVectorShuffle(MVT::v4i32, dl, DAG.getBitcast(MVT::v4i32, Src),
19937 DAG.getUNDEF(MVT::v4i32), ShuffleMask);
19938 // Now we have 4 elements instead of 2.
19939 // Expand the index.
19940 MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), 4);
19941 Index = ExtendToType(Index, NewIndexVT, DAG);
19943 // Expand the mask with zeroes
19944 // Mask may be <2 x i64> or <2 x i1> at this moment
19945 assert((MaskVT == MVT::v2i1 || MaskVT == MVT::v2i64) &&
19946 "Unexpected mask type");
19947 MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), 4);
19948 Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
19952 unsigned NumElts = VT.getVectorNumElements();
19953 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19954 !Index.getSimpleValueType().is512BitVector()) {
19955 // AVX512F supports only 512-bit vectors. Or data or index should
19956 // be 512 bit wide. If now the both index and data are 256-bit, but
19957 // the vector contains 8 elements, we just sign-extend the index
19958 if (IndexVT == MVT::v8i32)
19959 // Just extend index
19960 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19962 // The minimal number of elts in scatter is 8
19965 MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
19966 // Use original index here, do not modify the index twice
19967 Index = ExtendToType(N->getIndex(), NewIndexVT, DAG);
19968 if (IndexVT.getScalarType() == MVT::i32)
19969 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19972 // At this point we have promoted mask operand
19973 assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
19974 MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
19975 // Use the original mask here, do not modify the mask twice
19976 Mask = ExtendToType(N->getMask(), ExtMaskVT, DAG, true);
19978 // The value that should be stored
19979 MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
19980 Src = ExtendToType(Src, NewVT, DAG);
19983 // If the mask is "wide" at this point - truncate it to i1 vector
19984 MVT BitMaskVT = MVT::getVectorVT(MVT::i1, NumElts);
19985 Mask = DAG.getNode(ISD::TRUNCATE, dl, BitMaskVT, Mask);
19987 // The mask is killed by scatter, add it to the values
19988 SDVTList VTs = DAG.getVTList(BitMaskVT, MVT::Other);
19989 SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index};
19990 NewScatter = DAG.getMaskedScatter(VTs, N->getMemoryVT(), dl, Ops,
19991 N->getMemOperand());
19992 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19993 return SDValue(NewScatter.getNode(), 0);
19996 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget *Subtarget,
19997 SelectionDAG &DAG) {
19999 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
20000 MVT VT = Op.getSimpleValueType();
20001 SDValue Mask = N->getMask();
20004 if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20005 !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20006 // This operation is legal for targets with VLX, but without
20007 // VLX the vector should be widened to 512 bit
20008 unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20009 MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20010 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20011 SDValue Src0 = N->getSrc0();
20012 Src0 = ExtendToType(Src0, WideDataVT, DAG);
20013 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20014 SDValue NewLoad = DAG.getMaskedLoad(WideDataVT, dl, N->getChain(),
20015 N->getBasePtr(), Mask, Src0,
20016 N->getMemoryVT(), N->getMemOperand(),
20017 N->getExtensionType());
20019 SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20020 NewLoad.getValue(0),
20021 DAG.getIntPtrConstant(0, dl));
20022 SDValue RetOps[] = {Exract, NewLoad.getValue(1)};
20023 return DAG.getMergeValues(RetOps, dl);
20028 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget *Subtarget,
20029 SelectionDAG &DAG) {
20030 MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
20031 SDValue DataToStore = N->getValue();
20032 MVT VT = DataToStore.getSimpleValueType();
20033 SDValue Mask = N->getMask();
20036 if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20037 !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20038 // This operation is legal for targets with VLX, but without
20039 // VLX the vector should be widened to 512 bit
20040 unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20041 MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20042 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20043 DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
20044 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20045 return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
20046 Mask, N->getMemoryVT(), N->getMemOperand(),
20047 N->isTruncatingStore());
20052 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
20053 SelectionDAG &DAG) {
20054 assert(Subtarget->hasAVX512() &&
20055 "MGATHER/MSCATTER are supported on AVX-512 arch only");
20057 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
20059 MVT VT = Op.getSimpleValueType();
20060 SDValue Index = N->getIndex();
20061 SDValue Mask = N->getMask();
20062 SDValue Src0 = N->getValue();
20063 MVT IndexVT = Index.getSimpleValueType();
20064 MVT MaskVT = Mask.getSimpleValueType();
20066 unsigned NumElts = VT.getVectorNumElements();
20067 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
20069 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20070 !Index.getSimpleValueType().is512BitVector()) {
20071 // AVX512F supports only 512-bit vectors. Or data or index should
20072 // be 512 bit wide. If now the both index and data are 256-bit, but
20073 // the vector contains 8 elements, we just sign-extend the index
20074 if (NumElts == 8) {
20075 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20076 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
20077 N->getOperand(3), Index };
20078 DAG.UpdateNodeOperands(N, Ops);
20082 // Minimal number of elements in Gather
20085 MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20086 Index = ExtendToType(Index, NewIndexVT, DAG);
20087 if (IndexVT.getScalarType() == MVT::i32)
20088 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20091 MVT MaskBitVT = MVT::getVectorVT(MVT::i1, NumElts);
20092 // At this point we have promoted mask operand
20093 assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20094 MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20095 Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20096 Mask = DAG.getNode(ISD::TRUNCATE, dl, MaskBitVT, Mask);
20098 // The pass-thru value
20099 MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20100 Src0 = ExtendToType(Src0, NewVT, DAG);
20102 SDValue Ops[] = { N->getChain(), Src0, Mask, N->getBasePtr(), Index };
20103 SDValue NewGather = DAG.getMaskedGather(DAG.getVTList(NewVT, MVT::Other),
20104 N->getMemoryVT(), dl, Ops,
20105 N->getMemOperand());
20106 SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20107 NewGather.getValue(0),
20108 DAG.getIntPtrConstant(0, dl));
20109 SDValue RetOps[] = {Exract, NewGather.getValue(1)};
20110 return DAG.getMergeValues(RetOps, dl);
20115 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
20116 SelectionDAG &DAG) const {
20117 // TODO: Eventually, the lowering of these nodes should be informed by or
20118 // deferred to the GC strategy for the function in which they appear. For
20119 // now, however, they must be lowered to something. Since they are logically
20120 // no-ops in the case of a null GC strategy (or a GC strategy which does not
20121 // require special handling for these nodes), lower them as literal NOOPs for
20123 SmallVector<SDValue, 2> Ops;
20125 Ops.push_back(Op.getOperand(0));
20126 if (Op->getGluedNode())
20127 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20130 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20131 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20136 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
20137 SelectionDAG &DAG) const {
20138 // TODO: Eventually, the lowering of these nodes should be informed by or
20139 // deferred to the GC strategy for the function in which they appear. For
20140 // now, however, they must be lowered to something. Since they are logically
20141 // no-ops in the case of a null GC strategy (or a GC strategy which does not
20142 // require special handling for these nodes), lower them as literal NOOPs for
20144 SmallVector<SDValue, 2> Ops;
20146 Ops.push_back(Op.getOperand(0));
20147 if (Op->getGluedNode())
20148 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20151 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20152 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20157 /// LowerOperation - Provide custom lowering hooks for some operations.
20159 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
20160 switch (Op.getOpcode()) {
20161 default: llvm_unreachable("Should not custom lower this!");
20162 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
20163 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
20164 return LowerCMP_SWAP(Op, Subtarget, DAG);
20165 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
20166 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
20167 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
20168 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
20169 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
20170 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
20171 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
20172 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
20173 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
20174 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
20175 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
20176 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
20177 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
20178 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
20179 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
20180 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
20181 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
20182 case ISD::SHL_PARTS:
20183 case ISD::SRA_PARTS:
20184 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
20185 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
20186 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
20187 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
20188 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
20189 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
20190 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
20191 case ISD::SIGN_EXTEND_VECTOR_INREG:
20192 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
20193 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
20194 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
20195 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
20196 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
20198 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
20199 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
20200 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
20201 case ISD::SETCC: return LowerSETCC(Op, DAG);
20202 case ISD::SETCCE: return LowerSETCCE(Op, DAG);
20203 case ISD::SELECT: return LowerSELECT(Op, DAG);
20204 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
20205 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
20206 case ISD::VASTART: return LowerVASTART(Op, DAG);
20207 case ISD::VAARG: return LowerVAARG(Op, DAG);
20208 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
20209 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
20210 case ISD::INTRINSIC_VOID:
20211 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
20212 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
20213 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
20214 case ISD::FRAME_TO_ARGS_OFFSET:
20215 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
20216 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
20217 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
20218 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
20219 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
20220 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
20221 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
20222 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
20223 case ISD::CTLZ: return LowerCTLZ(Op, Subtarget, DAG);
20224 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
20226 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op, DAG);
20227 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
20228 case ISD::UMUL_LOHI:
20229 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
20230 case ISD::ROTL: return LowerRotate(Op, Subtarget, DAG);
20233 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
20239 case ISD::UMULO: return LowerXALUO(Op, DAG);
20240 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
20241 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
20245 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
20246 case ISD::ADD: return LowerADD(Op, DAG);
20247 case ISD::SUB: return LowerSUB(Op, DAG);
20251 case ISD::UMIN: return LowerMINMAX(Op, DAG);
20252 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
20253 case ISD::MLOAD: return LowerMLOAD(Op, Subtarget, DAG);
20254 case ISD::MSTORE: return LowerMSTORE(Op, Subtarget, DAG);
20255 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
20256 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
20257 case ISD::GC_TRANSITION_START:
20258 return LowerGC_TRANSITION_START(Op, DAG);
20259 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
20263 /// ReplaceNodeResults - Replace a node with an illegal result type
20264 /// with a new node built out of custom code.
20265 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
20266 SmallVectorImpl<SDValue>&Results,
20267 SelectionDAG &DAG) const {
20269 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20270 switch (N->getOpcode()) {
20272 llvm_unreachable("Do not know how to custom type legalize this operation!");
20273 case X86ISD::AVG: {
20274 // Legalize types for X86ISD::AVG by expanding vectors.
20275 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20277 auto InVT = N->getValueType(0);
20278 auto InVTSize = InVT.getSizeInBits();
20279 const unsigned RegSize =
20280 (InVTSize > 128) ? ((InVTSize > 256) ? 512 : 256) : 128;
20281 assert((!Subtarget->hasAVX512() || RegSize < 512) &&
20282 "512-bit vector requires AVX512");
20283 assert((!Subtarget->hasAVX2() || RegSize < 256) &&
20284 "256-bit vector requires AVX2");
20286 auto ElemVT = InVT.getVectorElementType();
20287 auto RegVT = EVT::getVectorVT(*DAG.getContext(), ElemVT,
20288 RegSize / ElemVT.getSizeInBits());
20289 assert(RegSize % InVT.getSizeInBits() == 0);
20290 unsigned NumConcat = RegSize / InVT.getSizeInBits();
20292 SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
20293 Ops[0] = N->getOperand(0);
20294 SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20295 Ops[0] = N->getOperand(1);
20296 SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20298 SDValue Res = DAG.getNode(X86ISD::AVG, dl, RegVT, InVec0, InVec1);
20299 Results.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InVT, Res,
20300 DAG.getIntPtrConstant(0, dl)));
20303 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
20304 case X86ISD::FMINC:
20306 case X86ISD::FMAXC:
20307 case X86ISD::FMAX: {
20308 EVT VT = N->getValueType(0);
20309 assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
20310 SDValue UNDEF = DAG.getUNDEF(VT);
20311 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20312 N->getOperand(0), UNDEF);
20313 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20314 N->getOperand(1), UNDEF);
20315 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
20318 case ISD::SIGN_EXTEND_INREG:
20323 // We don't want to expand or promote these.
20330 case ISD::UDIVREM: {
20331 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
20332 Results.push_back(V);
20335 case ISD::FP_TO_SINT:
20336 case ISD::FP_TO_UINT: {
20337 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
20339 std::pair<SDValue,SDValue> Vals =
20340 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
20341 SDValue FIST = Vals.first, StackSlot = Vals.second;
20342 if (FIST.getNode()) {
20343 EVT VT = N->getValueType(0);
20344 // Return a load from the stack slot.
20345 if (StackSlot.getNode())
20346 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
20347 MachinePointerInfo(),
20348 false, false, false, 0));
20350 Results.push_back(FIST);
20354 case ISD::UINT_TO_FP: {
20355 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20356 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
20357 N->getValueType(0) != MVT::v2f32)
20359 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
20361 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
20363 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
20364 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
20365 DAG.getBitcast(MVT::v2i64, VBias));
20366 Or = DAG.getBitcast(MVT::v2f64, Or);
20367 // TODO: Are there any fast-math-flags to propagate here?
20368 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
20369 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
20372 case ISD::FP_ROUND: {
20373 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
20375 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
20376 Results.push_back(V);
20379 case ISD::FP_EXTEND: {
20380 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
20381 // No other ValueType for FP_EXTEND should reach this point.
20382 assert(N->getValueType(0) == MVT::v2f32 &&
20383 "Do not know how to legalize this Node");
20386 case ISD::INTRINSIC_W_CHAIN: {
20387 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20389 default : llvm_unreachable("Do not know how to custom type "
20390 "legalize this intrinsic operation!");
20391 case Intrinsic::x86_rdtsc:
20392 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20394 case Intrinsic::x86_rdtscp:
20395 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
20397 case Intrinsic::x86_rdpmc:
20398 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
20401 case ISD::INTRINSIC_WO_CHAIN: {
20402 if (SDValue V = LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), Subtarget, DAG))
20403 Results.push_back(V);
20406 case ISD::READCYCLECOUNTER: {
20407 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20410 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
20411 EVT T = N->getValueType(0);
20412 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
20413 bool Regs64bit = T == MVT::i128;
20414 MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
20415 SDValue cpInL, cpInH;
20416 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20417 DAG.getConstant(0, dl, HalfT));
20418 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20419 DAG.getConstant(1, dl, HalfT));
20420 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
20421 Regs64bit ? X86::RAX : X86::EAX,
20423 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
20424 Regs64bit ? X86::RDX : X86::EDX,
20425 cpInH, cpInL.getValue(1));
20426 SDValue swapInL, swapInH;
20427 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20428 DAG.getConstant(0, dl, HalfT));
20429 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20430 DAG.getConstant(1, dl, HalfT));
20431 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
20432 Regs64bit ? X86::RBX : X86::EBX,
20433 swapInL, cpInH.getValue(1));
20434 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
20435 Regs64bit ? X86::RCX : X86::ECX,
20436 swapInH, swapInL.getValue(1));
20437 SDValue Ops[] = { swapInH.getValue(0),
20439 swapInH.getValue(1) };
20440 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
20441 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
20442 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
20443 X86ISD::LCMPXCHG8_DAG;
20444 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
20445 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
20446 Regs64bit ? X86::RAX : X86::EAX,
20447 HalfT, Result.getValue(1));
20448 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
20449 Regs64bit ? X86::RDX : X86::EDX,
20450 HalfT, cpOutL.getValue(2));
20451 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
20453 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
20454 MVT::i32, cpOutH.getValue(2));
20456 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
20457 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
20458 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
20460 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
20461 Results.push_back(Success);
20462 Results.push_back(EFLAGS.getValue(1));
20465 case ISD::ATOMIC_SWAP:
20466 case ISD::ATOMIC_LOAD_ADD:
20467 case ISD::ATOMIC_LOAD_SUB:
20468 case ISD::ATOMIC_LOAD_AND:
20469 case ISD::ATOMIC_LOAD_OR:
20470 case ISD::ATOMIC_LOAD_XOR:
20471 case ISD::ATOMIC_LOAD_NAND:
20472 case ISD::ATOMIC_LOAD_MIN:
20473 case ISD::ATOMIC_LOAD_MAX:
20474 case ISD::ATOMIC_LOAD_UMIN:
20475 case ISD::ATOMIC_LOAD_UMAX:
20476 case ISD::ATOMIC_LOAD: {
20477 // Delegate to generic TypeLegalization. Situations we can really handle
20478 // should have already been dealt with by AtomicExpandPass.cpp.
20481 case ISD::BITCAST: {
20482 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20483 EVT DstVT = N->getValueType(0);
20484 EVT SrcVT = N->getOperand(0)->getValueType(0);
20486 if (SrcVT != MVT::f64 ||
20487 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
20490 unsigned NumElts = DstVT.getVectorNumElements();
20491 EVT SVT = DstVT.getVectorElementType();
20492 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
20493 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
20494 MVT::v2f64, N->getOperand(0));
20495 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
20497 if (ExperimentalVectorWideningLegalization) {
20498 // If we are legalizing vectors by widening, we already have the desired
20499 // legal vector type, just return it.
20500 Results.push_back(ToVecInt);
20504 SmallVector<SDValue, 8> Elts;
20505 for (unsigned i = 0, e = NumElts; i != e; ++i)
20506 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
20507 ToVecInt, DAG.getIntPtrConstant(i, dl)));
20509 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
20514 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
20515 switch ((X86ISD::NodeType)Opcode) {
20516 case X86ISD::FIRST_NUMBER: break;
20517 case X86ISD::BSF: return "X86ISD::BSF";
20518 case X86ISD::BSR: return "X86ISD::BSR";
20519 case X86ISD::SHLD: return "X86ISD::SHLD";
20520 case X86ISD::SHRD: return "X86ISD::SHRD";
20521 case X86ISD::FAND: return "X86ISD::FAND";
20522 case X86ISD::FANDN: return "X86ISD::FANDN";
20523 case X86ISD::FOR: return "X86ISD::FOR";
20524 case X86ISD::FXOR: return "X86ISD::FXOR";
20525 case X86ISD::FILD: return "X86ISD::FILD";
20526 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
20527 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
20528 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
20529 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
20530 case X86ISD::FLD: return "X86ISD::FLD";
20531 case X86ISD::FST: return "X86ISD::FST";
20532 case X86ISD::CALL: return "X86ISD::CALL";
20533 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
20534 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
20535 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
20536 case X86ISD::BT: return "X86ISD::BT";
20537 case X86ISD::CMP: return "X86ISD::CMP";
20538 case X86ISD::COMI: return "X86ISD::COMI";
20539 case X86ISD::UCOMI: return "X86ISD::UCOMI";
20540 case X86ISD::CMPM: return "X86ISD::CMPM";
20541 case X86ISD::CMPMU: return "X86ISD::CMPMU";
20542 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
20543 case X86ISD::SETCC: return "X86ISD::SETCC";
20544 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
20545 case X86ISD::FSETCC: return "X86ISD::FSETCC";
20546 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
20547 case X86ISD::CMOV: return "X86ISD::CMOV";
20548 case X86ISD::BRCOND: return "X86ISD::BRCOND";
20549 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
20550 case X86ISD::IRET: return "X86ISD::IRET";
20551 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
20552 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
20553 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
20554 case X86ISD::Wrapper: return "X86ISD::Wrapper";
20555 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
20556 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
20557 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
20558 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
20559 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
20560 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
20561 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
20562 case X86ISD::PINSRB: return "X86ISD::PINSRB";
20563 case X86ISD::PINSRW: return "X86ISD::PINSRW";
20564 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
20565 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
20566 case X86ISD::ANDNP: return "X86ISD::ANDNP";
20567 case X86ISD::PSIGN: return "X86ISD::PSIGN";
20568 case X86ISD::BLENDI: return "X86ISD::BLENDI";
20569 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
20570 case X86ISD::ADDUS: return "X86ISD::ADDUS";
20571 case X86ISD::SUBUS: return "X86ISD::SUBUS";
20572 case X86ISD::HADD: return "X86ISD::HADD";
20573 case X86ISD::HSUB: return "X86ISD::HSUB";
20574 case X86ISD::FHADD: return "X86ISD::FHADD";
20575 case X86ISD::FHSUB: return "X86ISD::FHSUB";
20576 case X86ISD::ABS: return "X86ISD::ABS";
20577 case X86ISD::CONFLICT: return "X86ISD::CONFLICT";
20578 case X86ISD::FMAX: return "X86ISD::FMAX";
20579 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
20580 case X86ISD::FMIN: return "X86ISD::FMIN";
20581 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
20582 case X86ISD::FMAXC: return "X86ISD::FMAXC";
20583 case X86ISD::FMINC: return "X86ISD::FMINC";
20584 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
20585 case X86ISD::FRCP: return "X86ISD::FRCP";
20586 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
20587 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
20588 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
20589 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
20590 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
20591 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
20592 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
20593 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
20594 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
20595 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
20596 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
20597 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
20598 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
20599 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
20600 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
20601 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
20602 case X86ISD::VZEXT: return "X86ISD::VZEXT";
20603 case X86ISD::VSEXT: return "X86ISD::VSEXT";
20604 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
20605 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
20606 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
20607 case X86ISD::VINSERT: return "X86ISD::VINSERT";
20608 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
20609 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
20610 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
20611 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
20612 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
20613 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
20614 case X86ISD::VSHL: return "X86ISD::VSHL";
20615 case X86ISD::VSRL: return "X86ISD::VSRL";
20616 case X86ISD::VSRA: return "X86ISD::VSRA";
20617 case X86ISD::VSHLI: return "X86ISD::VSHLI";
20618 case X86ISD::VSRLI: return "X86ISD::VSRLI";
20619 case X86ISD::VSRAI: return "X86ISD::VSRAI";
20620 case X86ISD::CMPP: return "X86ISD::CMPP";
20621 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
20622 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
20623 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
20624 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
20625 case X86ISD::ADD: return "X86ISD::ADD";
20626 case X86ISD::SUB: return "X86ISD::SUB";
20627 case X86ISD::ADC: return "X86ISD::ADC";
20628 case X86ISD::SBB: return "X86ISD::SBB";
20629 case X86ISD::SMUL: return "X86ISD::SMUL";
20630 case X86ISD::UMUL: return "X86ISD::UMUL";
20631 case X86ISD::SMUL8: return "X86ISD::SMUL8";
20632 case X86ISD::UMUL8: return "X86ISD::UMUL8";
20633 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20634 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20635 case X86ISD::INC: return "X86ISD::INC";
20636 case X86ISD::DEC: return "X86ISD::DEC";
20637 case X86ISD::OR: return "X86ISD::OR";
20638 case X86ISD::XOR: return "X86ISD::XOR";
20639 case X86ISD::AND: return "X86ISD::AND";
20640 case X86ISD::BEXTR: return "X86ISD::BEXTR";
20641 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
20642 case X86ISD::PTEST: return "X86ISD::PTEST";
20643 case X86ISD::TESTP: return "X86ISD::TESTP";
20644 case X86ISD::TESTM: return "X86ISD::TESTM";
20645 case X86ISD::TESTNM: return "X86ISD::TESTNM";
20646 case X86ISD::KORTEST: return "X86ISD::KORTEST";
20647 case X86ISD::KTEST: return "X86ISD::KTEST";
20648 case X86ISD::PACKSS: return "X86ISD::PACKSS";
20649 case X86ISD::PACKUS: return "X86ISD::PACKUS";
20650 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
20651 case X86ISD::VALIGN: return "X86ISD::VALIGN";
20652 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
20653 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
20654 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
20655 case X86ISD::SHUFP: return "X86ISD::SHUFP";
20656 case X86ISD::SHUF128: return "X86ISD::SHUF128";
20657 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
20658 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
20659 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
20660 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
20661 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
20662 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
20663 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
20664 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
20665 case X86ISD::MOVSD: return "X86ISD::MOVSD";
20666 case X86ISD::MOVSS: return "X86ISD::MOVSS";
20667 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
20668 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
20669 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
20670 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
20671 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
20672 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
20673 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
20674 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
20675 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
20676 case X86ISD::VPERMV: return "X86ISD::VPERMV";
20677 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
20678 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
20679 case X86ISD::VPERMI: return "X86ISD::VPERMI";
20680 case X86ISD::VPTERNLOG: return "X86ISD::VPTERNLOG";
20681 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
20682 case X86ISD::VRANGE: return "X86ISD::VRANGE";
20683 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
20684 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
20685 case X86ISD::PSADBW: return "X86ISD::PSADBW";
20686 case X86ISD::DBPSADBW: return "X86ISD::DBPSADBW";
20687 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20688 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
20689 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
20690 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
20691 case X86ISD::MFENCE: return "X86ISD::MFENCE";
20692 case X86ISD::SFENCE: return "X86ISD::SFENCE";
20693 case X86ISD::LFENCE: return "X86ISD::LFENCE";
20694 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
20695 case X86ISD::SAHF: return "X86ISD::SAHF";
20696 case X86ISD::RDRAND: return "X86ISD::RDRAND";
20697 case X86ISD::RDSEED: return "X86ISD::RDSEED";
20698 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
20699 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
20700 case X86ISD::VPROT: return "X86ISD::VPROT";
20701 case X86ISD::VPROTI: return "X86ISD::VPROTI";
20702 case X86ISD::VPSHA: return "X86ISD::VPSHA";
20703 case X86ISD::VPSHL: return "X86ISD::VPSHL";
20704 case X86ISD::VPCOM: return "X86ISD::VPCOM";
20705 case X86ISD::VPCOMU: return "X86ISD::VPCOMU";
20706 case X86ISD::FMADD: return "X86ISD::FMADD";
20707 case X86ISD::FMSUB: return "X86ISD::FMSUB";
20708 case X86ISD::FNMADD: return "X86ISD::FNMADD";
20709 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
20710 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
20711 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
20712 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
20713 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
20714 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
20715 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
20716 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
20717 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
20718 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
20719 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
20720 case X86ISD::VGETMANT: return "X86ISD::VGETMANT";
20721 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
20722 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
20723 case X86ISD::XTEST: return "X86ISD::XTEST";
20724 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
20725 case X86ISD::EXPAND: return "X86ISD::EXPAND";
20726 case X86ISD::SELECT: return "X86ISD::SELECT";
20727 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
20728 case X86ISD::RCP28: return "X86ISD::RCP28";
20729 case X86ISD::EXP2: return "X86ISD::EXP2";
20730 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
20731 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
20732 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
20733 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
20734 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
20735 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
20736 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
20737 case X86ISD::SCALEF: return "X86ISD::SCALEF";
20738 case X86ISD::ADDS: return "X86ISD::ADDS";
20739 case X86ISD::SUBS: return "X86ISD::SUBS";
20740 case X86ISD::AVG: return "X86ISD::AVG";
20741 case X86ISD::MULHRS: return "X86ISD::MULHRS";
20742 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
20743 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
20744 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
20745 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
20746 case X86ISD::VFPCLASS: return "X86ISD::VFPCLASS";
20747 case X86ISD::VFPCLASSS: return "X86ISD::VFPCLASSS";
20752 // isLegalAddressingMode - Return true if the addressing mode represented
20753 // by AM is legal for this target, for a load/store of the specified type.
20754 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20755 const AddrMode &AM, Type *Ty,
20756 unsigned AS) const {
20757 // X86 supports extremely general addressing modes.
20758 CodeModel::Model M = getTargetMachine().getCodeModel();
20759 Reloc::Model R = getTargetMachine().getRelocationModel();
20761 // X86 allows a sign-extended 32-bit immediate field as a displacement.
20762 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20767 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20769 // If a reference to this global requires an extra load, we can't fold it.
20770 if (isGlobalStubReference(GVFlags))
20773 // If BaseGV requires a register for the PIC base, we cannot also have a
20774 // BaseReg specified.
20775 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20778 // If lower 4G is not available, then we must use rip-relative addressing.
20779 if ((M != CodeModel::Small || R != Reloc::Static) &&
20780 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20784 switch (AM.Scale) {
20790 // These scales always work.
20795 // These scales are formed with basereg+scalereg. Only accept if there is
20800 default: // Other stuff never works.
20807 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20808 unsigned Bits = Ty->getScalarSizeInBits();
20810 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20811 // particularly cheaper than those without.
20815 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20816 // variable shifts just as cheap as scalar ones.
20817 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20820 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20821 // fully general vector.
20825 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20826 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20828 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20829 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20830 return NumBits1 > NumBits2;
20833 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20834 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20837 if (!isTypeLegal(EVT::getEVT(Ty1)))
20840 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20842 // Assuming the caller doesn't have a zeroext or signext return parameter,
20843 // truncation all the way down to i1 is valid.
20847 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20848 return isInt<32>(Imm);
20851 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20852 // Can also use sub to handle negated immediates.
20853 return isInt<32>(Imm);
20856 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20857 if (!VT1.isInteger() || !VT2.isInteger())
20859 unsigned NumBits1 = VT1.getSizeInBits();
20860 unsigned NumBits2 = VT2.getSizeInBits();
20861 return NumBits1 > NumBits2;
20864 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20865 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20866 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20869 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20870 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20871 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20874 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20875 EVT VT1 = Val.getValueType();
20876 if (isZExtFree(VT1, VT2))
20879 if (Val.getOpcode() != ISD::LOAD)
20882 if (!VT1.isSimple() || !VT1.isInteger() ||
20883 !VT2.isSimple() || !VT2.isInteger())
20886 switch (VT1.getSimpleVT().SimpleTy) {
20891 // X86 has 8, 16, and 32-bit zero-extending loads.
20898 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20901 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20902 if (!Subtarget->hasAnyFMA())
20905 VT = VT.getScalarType();
20907 if (!VT.isSimple())
20910 switch (VT.getSimpleVT().SimpleTy) {
20921 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20922 // i16 instructions are longer (0x66 prefix) and potentially slower.
20923 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20926 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20927 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20928 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20929 /// are assumed to be legal.
20931 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20933 if (!VT.isSimple())
20936 // Not for i1 vectors
20937 if (VT.getSimpleVT().getScalarType() == MVT::i1)
20940 // Very little shuffling can be done for 64-bit vectors right now.
20941 if (VT.getSimpleVT().getSizeInBits() == 64)
20944 // We only care that the types being shuffled are legal. The lowering can
20945 // handle any possible shuffle mask that results.
20946 return isTypeLegal(VT.getSimpleVT());
20950 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20952 // Just delegate to the generic legality, clear masks aren't special.
20953 return isShuffleMaskLegal(Mask, VT);
20956 //===----------------------------------------------------------------------===//
20957 // X86 Scheduler Hooks
20958 //===----------------------------------------------------------------------===//
20960 /// Utility function to emit xbegin specifying the start of an RTM region.
20961 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20962 const TargetInstrInfo *TII) {
20963 DebugLoc DL = MI->getDebugLoc();
20965 const BasicBlock *BB = MBB->getBasicBlock();
20966 MachineFunction::iterator I = ++MBB->getIterator();
20968 // For the v = xbegin(), we generate
20979 MachineBasicBlock *thisMBB = MBB;
20980 MachineFunction *MF = MBB->getParent();
20981 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20982 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20983 MF->insert(I, mainMBB);
20984 MF->insert(I, sinkMBB);
20986 // Transfer the remainder of BB and its successor edges to sinkMBB.
20987 sinkMBB->splice(sinkMBB->begin(), MBB,
20988 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20989 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20993 // # fallthrough to mainMBB
20994 // # abortion to sinkMBB
20995 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20996 thisMBB->addSuccessor(mainMBB);
20997 thisMBB->addSuccessor(sinkMBB);
21001 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
21002 mainMBB->addSuccessor(sinkMBB);
21005 // EAX is live into the sinkMBB
21006 sinkMBB->addLiveIn(X86::EAX);
21007 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21008 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21011 MI->eraseFromParent();
21015 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
21016 // or XMM0_V32I8 in AVX all of this code can be replaced with that
21017 // in the .td file.
21018 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
21019 const TargetInstrInfo *TII) {
21021 switch (MI->getOpcode()) {
21022 default: llvm_unreachable("illegal opcode!");
21023 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
21024 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
21025 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
21026 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
21027 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
21028 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
21029 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
21030 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
21033 DebugLoc dl = MI->getDebugLoc();
21034 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21036 unsigned NumArgs = MI->getNumOperands();
21037 for (unsigned i = 1; i < NumArgs; ++i) {
21038 MachineOperand &Op = MI->getOperand(i);
21039 if (!(Op.isReg() && Op.isImplicit()))
21040 MIB.addOperand(Op);
21042 if (MI->hasOneMemOperand())
21043 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21045 BuildMI(*BB, MI, dl,
21046 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21047 .addReg(X86::XMM0);
21049 MI->eraseFromParent();
21053 // FIXME: Custom handling because TableGen doesn't support multiple implicit
21054 // defs in an instruction pattern
21055 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
21056 const TargetInstrInfo *TII) {
21058 switch (MI->getOpcode()) {
21059 default: llvm_unreachable("illegal opcode!");
21060 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
21061 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
21062 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
21063 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
21064 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
21065 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
21066 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
21067 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
21070 DebugLoc dl = MI->getDebugLoc();
21071 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21073 unsigned NumArgs = MI->getNumOperands(); // remove the results
21074 for (unsigned i = 1; i < NumArgs; ++i) {
21075 MachineOperand &Op = MI->getOperand(i);
21076 if (!(Op.isReg() && Op.isImplicit()))
21077 MIB.addOperand(Op);
21079 if (MI->hasOneMemOperand())
21080 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21082 BuildMI(*BB, MI, dl,
21083 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21086 MI->eraseFromParent();
21090 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
21091 const X86Subtarget *Subtarget) {
21092 DebugLoc dl = MI->getDebugLoc();
21093 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21094 // Address into RAX/EAX, other two args into ECX, EDX.
21095 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
21096 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
21097 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
21098 for (int i = 0; i < X86::AddrNumOperands; ++i)
21099 MIB.addOperand(MI->getOperand(i));
21101 unsigned ValOps = X86::AddrNumOperands;
21102 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
21103 .addReg(MI->getOperand(ValOps).getReg());
21104 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
21105 .addReg(MI->getOperand(ValOps+1).getReg());
21107 // The instruction doesn't actually take any operands though.
21108 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
21110 MI->eraseFromParent(); // The pseudo is gone now.
21114 MachineBasicBlock *
21115 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
21116 MachineBasicBlock *MBB) const {
21117 // Emit va_arg instruction on X86-64.
21119 // Operands to this pseudo-instruction:
21120 // 0 ) Output : destination address (reg)
21121 // 1-5) Input : va_list address (addr, i64mem)
21122 // 6 ) ArgSize : Size (in bytes) of vararg type
21123 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
21124 // 8 ) Align : Alignment of type
21125 // 9 ) EFLAGS (implicit-def)
21127 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
21128 static_assert(X86::AddrNumOperands == 5,
21129 "VAARG_64 assumes 5 address operands");
21131 unsigned DestReg = MI->getOperand(0).getReg();
21132 MachineOperand &Base = MI->getOperand(1);
21133 MachineOperand &Scale = MI->getOperand(2);
21134 MachineOperand &Index = MI->getOperand(3);
21135 MachineOperand &Disp = MI->getOperand(4);
21136 MachineOperand &Segment = MI->getOperand(5);
21137 unsigned ArgSize = MI->getOperand(6).getImm();
21138 unsigned ArgMode = MI->getOperand(7).getImm();
21139 unsigned Align = MI->getOperand(8).getImm();
21141 // Memory Reference
21142 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
21143 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21144 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21146 // Machine Information
21147 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21148 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
21149 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
21150 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
21151 DebugLoc DL = MI->getDebugLoc();
21153 // struct va_list {
21156 // i64 overflow_area (address)
21157 // i64 reg_save_area (address)
21159 // sizeof(va_list) = 24
21160 // alignment(va_list) = 8
21162 unsigned TotalNumIntRegs = 6;
21163 unsigned TotalNumXMMRegs = 8;
21164 bool UseGPOffset = (ArgMode == 1);
21165 bool UseFPOffset = (ArgMode == 2);
21166 unsigned MaxOffset = TotalNumIntRegs * 8 +
21167 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
21169 /* Align ArgSize to a multiple of 8 */
21170 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
21171 bool NeedsAlign = (Align > 8);
21173 MachineBasicBlock *thisMBB = MBB;
21174 MachineBasicBlock *overflowMBB;
21175 MachineBasicBlock *offsetMBB;
21176 MachineBasicBlock *endMBB;
21178 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
21179 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
21180 unsigned OffsetReg = 0;
21182 if (!UseGPOffset && !UseFPOffset) {
21183 // If we only pull from the overflow region, we don't create a branch.
21184 // We don't need to alter control flow.
21185 OffsetDestReg = 0; // unused
21186 OverflowDestReg = DestReg;
21188 offsetMBB = nullptr;
21189 overflowMBB = thisMBB;
21192 // First emit code to check if gp_offset (or fp_offset) is below the bound.
21193 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
21194 // If not, pull from overflow_area. (branch to overflowMBB)
21199 // offsetMBB overflowMBB
21204 // Registers for the PHI in endMBB
21205 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
21206 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
21208 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21209 MachineFunction *MF = MBB->getParent();
21210 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21211 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21212 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21214 MachineFunction::iterator MBBIter = ++MBB->getIterator();
21216 // Insert the new basic blocks
21217 MF->insert(MBBIter, offsetMBB);
21218 MF->insert(MBBIter, overflowMBB);
21219 MF->insert(MBBIter, endMBB);
21221 // Transfer the remainder of MBB and its successor edges to endMBB.
21222 endMBB->splice(endMBB->begin(), thisMBB,
21223 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
21224 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
21226 // Make offsetMBB and overflowMBB successors of thisMBB
21227 thisMBB->addSuccessor(offsetMBB);
21228 thisMBB->addSuccessor(overflowMBB);
21230 // endMBB is a successor of both offsetMBB and overflowMBB
21231 offsetMBB->addSuccessor(endMBB);
21232 overflowMBB->addSuccessor(endMBB);
21234 // Load the offset value into a register
21235 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21236 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
21240 .addDisp(Disp, UseFPOffset ? 4 : 0)
21241 .addOperand(Segment)
21242 .setMemRefs(MMOBegin, MMOEnd);
21244 // Check if there is enough room left to pull this argument.
21245 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
21247 .addImm(MaxOffset + 8 - ArgSizeA8);
21249 // Branch to "overflowMBB" if offset >= max
21250 // Fall through to "offsetMBB" otherwise
21251 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
21252 .addMBB(overflowMBB);
21255 // In offsetMBB, emit code to use the reg_save_area.
21257 assert(OffsetReg != 0);
21259 // Read the reg_save_area address.
21260 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
21261 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
21266 .addOperand(Segment)
21267 .setMemRefs(MMOBegin, MMOEnd);
21269 // Zero-extend the offset
21270 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
21271 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
21274 .addImm(X86::sub_32bit);
21276 // Add the offset to the reg_save_area to get the final address.
21277 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
21278 .addReg(OffsetReg64)
21279 .addReg(RegSaveReg);
21281 // Compute the offset for the next argument
21282 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21283 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
21285 .addImm(UseFPOffset ? 16 : 8);
21287 // Store it back into the va_list.
21288 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
21292 .addDisp(Disp, UseFPOffset ? 4 : 0)
21293 .addOperand(Segment)
21294 .addReg(NextOffsetReg)
21295 .setMemRefs(MMOBegin, MMOEnd);
21298 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
21303 // Emit code to use overflow area
21306 // Load the overflow_area address into a register.
21307 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
21308 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
21313 .addOperand(Segment)
21314 .setMemRefs(MMOBegin, MMOEnd);
21316 // If we need to align it, do so. Otherwise, just copy the address
21317 // to OverflowDestReg.
21319 // Align the overflow address
21320 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
21321 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
21323 // aligned_addr = (addr + (align-1)) & ~(align-1)
21324 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
21325 .addReg(OverflowAddrReg)
21328 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
21330 .addImm(~(uint64_t)(Align-1));
21332 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
21333 .addReg(OverflowAddrReg);
21336 // Compute the next overflow address after this argument.
21337 // (the overflow address should be kept 8-byte aligned)
21338 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
21339 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
21340 .addReg(OverflowDestReg)
21341 .addImm(ArgSizeA8);
21343 // Store the new overflow address.
21344 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
21349 .addOperand(Segment)
21350 .addReg(NextAddrReg)
21351 .setMemRefs(MMOBegin, MMOEnd);
21353 // If we branched, emit the PHI to the front of endMBB.
21355 BuildMI(*endMBB, endMBB->begin(), DL,
21356 TII->get(X86::PHI), DestReg)
21357 .addReg(OffsetDestReg).addMBB(offsetMBB)
21358 .addReg(OverflowDestReg).addMBB(overflowMBB);
21361 // Erase the pseudo instruction
21362 MI->eraseFromParent();
21367 MachineBasicBlock *
21368 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
21370 MachineBasicBlock *MBB) const {
21371 // Emit code to save XMM registers to the stack. The ABI says that the
21372 // number of registers to save is given in %al, so it's theoretically
21373 // possible to do an indirect jump trick to avoid saving all of them,
21374 // however this code takes a simpler approach and just executes all
21375 // of the stores if %al is non-zero. It's less code, and it's probably
21376 // easier on the hardware branch predictor, and stores aren't all that
21377 // expensive anyway.
21379 // Create the new basic blocks. One block contains all the XMM stores,
21380 // and one block is the final destination regardless of whether any
21381 // stores were performed.
21382 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21383 MachineFunction *F = MBB->getParent();
21384 MachineFunction::iterator MBBIter = ++MBB->getIterator();
21385 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
21386 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
21387 F->insert(MBBIter, XMMSaveMBB);
21388 F->insert(MBBIter, EndMBB);
21390 // Transfer the remainder of MBB and its successor edges to EndMBB.
21391 EndMBB->splice(EndMBB->begin(), MBB,
21392 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21393 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
21395 // The original block will now fall through to the XMM save block.
21396 MBB->addSuccessor(XMMSaveMBB);
21397 // The XMMSaveMBB will fall through to the end block.
21398 XMMSaveMBB->addSuccessor(EndMBB);
21400 // Now add the instructions.
21401 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21402 DebugLoc DL = MI->getDebugLoc();
21404 unsigned CountReg = MI->getOperand(0).getReg();
21405 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
21406 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
21408 if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
21409 // If %al is 0, branch around the XMM save block.
21410 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
21411 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
21412 MBB->addSuccessor(EndMBB);
21415 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
21416 // that was just emitted, but clearly shouldn't be "saved".
21417 assert((MI->getNumOperands() <= 3 ||
21418 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
21419 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
21420 && "Expected last argument to be EFLAGS");
21421 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
21422 // In the XMM save block, save all the XMM argument registers.
21423 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
21424 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
21425 MachineMemOperand *MMO = F->getMachineMemOperand(
21426 MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
21427 MachineMemOperand::MOStore,
21428 /*Size=*/16, /*Align=*/16);
21429 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
21430 .addFrameIndex(RegSaveFrameIndex)
21431 .addImm(/*Scale=*/1)
21432 .addReg(/*IndexReg=*/0)
21433 .addImm(/*Disp=*/Offset)
21434 .addReg(/*Segment=*/0)
21435 .addReg(MI->getOperand(i).getReg())
21436 .addMemOperand(MMO);
21439 MI->eraseFromParent(); // The pseudo instruction is gone now.
21444 // The EFLAGS operand of SelectItr might be missing a kill marker
21445 // because there were multiple uses of EFLAGS, and ISel didn't know
21446 // which to mark. Figure out whether SelectItr should have had a
21447 // kill marker, and set it if it should. Returns the correct kill
21449 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
21450 MachineBasicBlock* BB,
21451 const TargetRegisterInfo* TRI) {
21452 // Scan forward through BB for a use/def of EFLAGS.
21453 MachineBasicBlock::iterator miI(std::next(SelectItr));
21454 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
21455 const MachineInstr& mi = *miI;
21456 if (mi.readsRegister(X86::EFLAGS))
21458 if (mi.definesRegister(X86::EFLAGS))
21459 break; // Should have kill-flag - update below.
21462 // If we hit the end of the block, check whether EFLAGS is live into a
21464 if (miI == BB->end()) {
21465 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
21466 sEnd = BB->succ_end();
21467 sItr != sEnd; ++sItr) {
21468 MachineBasicBlock* succ = *sItr;
21469 if (succ->isLiveIn(X86::EFLAGS))
21474 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
21475 // out. SelectMI should have a kill flag on EFLAGS.
21476 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
21480 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
21481 // together with other CMOV pseudo-opcodes into a single basic-block with
21482 // conditional jump around it.
21483 static bool isCMOVPseudo(MachineInstr *MI) {
21484 switch (MI->getOpcode()) {
21485 case X86::CMOV_FR32:
21486 case X86::CMOV_FR64:
21487 case X86::CMOV_GR8:
21488 case X86::CMOV_GR16:
21489 case X86::CMOV_GR32:
21490 case X86::CMOV_RFP32:
21491 case X86::CMOV_RFP64:
21492 case X86::CMOV_RFP80:
21493 case X86::CMOV_V2F64:
21494 case X86::CMOV_V2I64:
21495 case X86::CMOV_V4F32:
21496 case X86::CMOV_V4F64:
21497 case X86::CMOV_V4I64:
21498 case X86::CMOV_V16F32:
21499 case X86::CMOV_V8F32:
21500 case X86::CMOV_V8F64:
21501 case X86::CMOV_V8I64:
21502 case X86::CMOV_V8I1:
21503 case X86::CMOV_V16I1:
21504 case X86::CMOV_V32I1:
21505 case X86::CMOV_V64I1:
21513 MachineBasicBlock *
21514 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
21515 MachineBasicBlock *BB) const {
21516 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21517 DebugLoc DL = MI->getDebugLoc();
21519 // To "insert" a SELECT_CC instruction, we actually have to insert the
21520 // diamond control-flow pattern. The incoming instruction knows the
21521 // destination vreg to set, the condition code register to branch on, the
21522 // true/false values to select between, and a branch opcode to use.
21523 const BasicBlock *LLVM_BB = BB->getBasicBlock();
21524 MachineFunction::iterator It = ++BB->getIterator();
21529 // cmpTY ccX, r1, r2
21531 // fallthrough --> copy0MBB
21532 MachineBasicBlock *thisMBB = BB;
21533 MachineFunction *F = BB->getParent();
21535 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
21536 // as described above, by inserting a BB, and then making a PHI at the join
21537 // point to select the true and false operands of the CMOV in the PHI.
21539 // The code also handles two different cases of multiple CMOV opcodes
21543 // In this case, there are multiple CMOVs in a row, all which are based on
21544 // the same condition setting (or the exact opposite condition setting).
21545 // In this case we can lower all the CMOVs using a single inserted BB, and
21546 // then make a number of PHIs at the join point to model the CMOVs. The only
21547 // trickiness here, is that in a case like:
21549 // t2 = CMOV cond1 t1, f1
21550 // t3 = CMOV cond1 t2, f2
21552 // when rewriting this into PHIs, we have to perform some renaming on the
21553 // temps since you cannot have a PHI operand refer to a PHI result earlier
21554 // in the same block. The "simple" but wrong lowering would be:
21556 // t2 = PHI t1(BB1), f1(BB2)
21557 // t3 = PHI t2(BB1), f2(BB2)
21559 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
21560 // renaming is to note that on the path through BB1, t2 is really just a
21561 // copy of t1, and do that renaming, properly generating:
21563 // t2 = PHI t1(BB1), f1(BB2)
21564 // t3 = PHI t1(BB1), f2(BB2)
21566 // Case 2, we lower cascaded CMOVs such as
21568 // (CMOV (CMOV F, T, cc1), T, cc2)
21570 // to two successives branches. For that, we look for another CMOV as the
21571 // following instruction.
21573 // Without this, we would add a PHI between the two jumps, which ends up
21574 // creating a few copies all around. For instance, for
21576 // (sitofp (zext (fcmp une)))
21578 // we would generate:
21580 // ucomiss %xmm1, %xmm0
21581 // movss <1.0f>, %xmm0
21582 // movaps %xmm0, %xmm1
21584 // xorps %xmm1, %xmm1
21587 // movaps %xmm1, %xmm0
21591 // because this custom-inserter would have generated:
21603 // A: X = ...; Y = ...
21605 // C: Z = PHI [X, A], [Y, B]
21607 // E: PHI [X, C], [Z, D]
21609 // If we lower both CMOVs in a single step, we can instead generate:
21621 // A: X = ...; Y = ...
21623 // E: PHI [X, A], [X, C], [Y, D]
21625 // Which, in our sitofp/fcmp example, gives us something like:
21627 // ucomiss %xmm1, %xmm0
21628 // movss <1.0f>, %xmm0
21631 // xorps %xmm0, %xmm0
21635 MachineInstr *CascadedCMOV = nullptr;
21636 MachineInstr *LastCMOV = MI;
21637 X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21638 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21639 MachineBasicBlock::iterator NextMIIt =
21640 std::next(MachineBasicBlock::iterator(MI));
21642 // Check for case 1, where there are multiple CMOVs with the same condition
21643 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
21644 // number of jumps the most.
21646 if (isCMOVPseudo(MI)) {
21647 // See if we have a string of CMOVS with the same condition.
21648 while (NextMIIt != BB->end() &&
21649 isCMOVPseudo(NextMIIt) &&
21650 (NextMIIt->getOperand(3).getImm() == CC ||
21651 NextMIIt->getOperand(3).getImm() == OppCC)) {
21652 LastCMOV = &*NextMIIt;
21657 // This checks for case 2, but only do this if we didn't already find
21658 // case 1, as indicated by LastCMOV == MI.
21659 if (LastCMOV == MI &&
21660 NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21661 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21662 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21663 CascadedCMOV = &*NextMIIt;
21666 MachineBasicBlock *jcc1MBB = nullptr;
21668 // If we have a cascaded CMOV, we lower it to two successive branches to
21669 // the same block. EFLAGS is used by both, so mark it as live in the second.
21670 if (CascadedCMOV) {
21671 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21672 F->insert(It, jcc1MBB);
21673 jcc1MBB->addLiveIn(X86::EFLAGS);
21676 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21677 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21678 F->insert(It, copy0MBB);
21679 F->insert(It, sinkMBB);
21681 // If the EFLAGS register isn't dead in the terminator, then claim that it's
21682 // live into the sink and copy blocks.
21683 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21685 MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21686 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21687 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21688 copy0MBB->addLiveIn(X86::EFLAGS);
21689 sinkMBB->addLiveIn(X86::EFLAGS);
21692 // Transfer the remainder of BB and its successor edges to sinkMBB.
21693 sinkMBB->splice(sinkMBB->begin(), BB,
21694 std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21695 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21697 // Add the true and fallthrough blocks as its successors.
21698 if (CascadedCMOV) {
21699 // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21700 BB->addSuccessor(jcc1MBB);
21702 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21703 // jump to the sinkMBB.
21704 jcc1MBB->addSuccessor(copy0MBB);
21705 jcc1MBB->addSuccessor(sinkMBB);
21707 BB->addSuccessor(copy0MBB);
21710 // The true block target of the first (or only) branch is always sinkMBB.
21711 BB->addSuccessor(sinkMBB);
21713 // Create the conditional branch instruction.
21714 unsigned Opc = X86::GetCondBranchFromCond(CC);
21715 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21717 if (CascadedCMOV) {
21718 unsigned Opc2 = X86::GetCondBranchFromCond(
21719 (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21720 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21724 // %FalseValue = ...
21725 // # fallthrough to sinkMBB
21726 copy0MBB->addSuccessor(sinkMBB);
21729 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21731 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21732 MachineBasicBlock::iterator MIItEnd =
21733 std::next(MachineBasicBlock::iterator(LastCMOV));
21734 MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21735 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21736 MachineInstrBuilder MIB;
21738 // As we are creating the PHIs, we have to be careful if there is more than
21739 // one. Later CMOVs may reference the results of earlier CMOVs, but later
21740 // PHIs have to reference the individual true/false inputs from earlier PHIs.
21741 // That also means that PHI construction must work forward from earlier to
21742 // later, and that the code must maintain a mapping from earlier PHI's
21743 // destination registers, and the registers that went into the PHI.
21745 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21746 unsigned DestReg = MIIt->getOperand(0).getReg();
21747 unsigned Op1Reg = MIIt->getOperand(1).getReg();
21748 unsigned Op2Reg = MIIt->getOperand(2).getReg();
21750 // If this CMOV we are generating is the opposite condition from
21751 // the jump we generated, then we have to swap the operands for the
21752 // PHI that is going to be generated.
21753 if (MIIt->getOperand(3).getImm() == OppCC)
21754 std::swap(Op1Reg, Op2Reg);
21756 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21757 Op1Reg = RegRewriteTable[Op1Reg].first;
21759 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21760 Op2Reg = RegRewriteTable[Op2Reg].second;
21762 MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21763 TII->get(X86::PHI), DestReg)
21764 .addReg(Op1Reg).addMBB(copy0MBB)
21765 .addReg(Op2Reg).addMBB(thisMBB);
21767 // Add this PHI to the rewrite table.
21768 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21771 // If we have a cascaded CMOV, the second Jcc provides the same incoming
21772 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21773 if (CascadedCMOV) {
21774 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21775 // Copy the PHI result to the register defined by the second CMOV.
21776 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21777 DL, TII->get(TargetOpcode::COPY),
21778 CascadedCMOV->getOperand(0).getReg())
21779 .addReg(MI->getOperand(0).getReg());
21780 CascadedCMOV->eraseFromParent();
21783 // Now remove the CMOV(s).
21784 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21785 (MIIt++)->eraseFromParent();
21790 MachineBasicBlock *
21791 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21792 MachineBasicBlock *BB) const {
21793 // Combine the following atomic floating-point modification pattern:
21794 // a.store(reg OP a.load(acquire), release)
21795 // Transform them into:
21796 // OPss (%gpr), %xmm
21797 // movss %xmm, (%gpr)
21798 // Or sd equivalent for 64-bit operations.
21800 switch (MI->getOpcode()) {
21801 default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21802 case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21803 case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21805 const X86InstrInfo *TII = Subtarget->getInstrInfo();
21806 DebugLoc DL = MI->getDebugLoc();
21807 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21808 MachineOperand MSrc = MI->getOperand(0);
21809 unsigned VSrc = MI->getOperand(5).getReg();
21810 const MachineOperand &Disp = MI->getOperand(3);
21811 MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21812 bool hasDisp = Disp.isGlobal() || Disp.isImm();
21813 if (hasDisp && MSrc.isReg())
21814 MSrc.setIsKill(false);
21815 MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21816 .addOperand(/*Base=*/MSrc)
21817 .addImm(/*Scale=*/1)
21818 .addReg(/*Index=*/0)
21819 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21821 MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21822 MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21824 .addOperand(/*Base=*/MSrc)
21825 .addImm(/*Scale=*/1)
21826 .addReg(/*Index=*/0)
21827 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21828 .addReg(/*Segment=*/0);
21829 MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
21830 MI->eraseFromParent(); // The pseudo instruction is gone now.
21834 MachineBasicBlock *
21835 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21836 MachineBasicBlock *BB) const {
21837 MachineFunction *MF = BB->getParent();
21838 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21839 DebugLoc DL = MI->getDebugLoc();
21840 const BasicBlock *LLVM_BB = BB->getBasicBlock();
21842 assert(MF->shouldSplitStack());
21844 const bool Is64Bit = Subtarget->is64Bit();
21845 const bool IsLP64 = Subtarget->isTarget64BitLP64();
21847 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21848 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21851 // ... [Till the alloca]
21852 // If stacklet is not large enough, jump to mallocMBB
21855 // Allocate by subtracting from RSP
21856 // Jump to continueMBB
21859 // Allocate by call to runtime
21863 // [rest of original BB]
21866 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21867 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21868 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21870 MachineRegisterInfo &MRI = MF->getRegInfo();
21871 const TargetRegisterClass *AddrRegClass =
21872 getRegClassFor(getPointerTy(MF->getDataLayout()));
21874 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21875 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21876 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
21877 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
21878 sizeVReg = MI->getOperand(1).getReg(),
21879 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
21881 MachineFunction::iterator MBBIter = ++BB->getIterator();
21883 MF->insert(MBBIter, bumpMBB);
21884 MF->insert(MBBIter, mallocMBB);
21885 MF->insert(MBBIter, continueMBB);
21887 continueMBB->splice(continueMBB->begin(), BB,
21888 std::next(MachineBasicBlock::iterator(MI)), BB->end());
21889 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
21891 // Add code to the main basic block to check if the stack limit has been hit,
21892 // and if so, jump to mallocMBB otherwise to bumpMBB.
21893 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
21894 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
21895 .addReg(tmpSPVReg).addReg(sizeVReg);
21896 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
21897 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
21898 .addReg(SPLimitVReg);
21899 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
21901 // bumpMBB simply decreases the stack pointer, since we know the current
21902 // stacklet has enough space.
21903 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
21904 .addReg(SPLimitVReg);
21905 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
21906 .addReg(SPLimitVReg);
21907 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21909 // Calls into a routine in libgcc to allocate more space from the heap.
21910 const uint32_t *RegMask =
21911 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
21913 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21915 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21916 .addExternalSymbol("__morestack_allocate_stack_space")
21917 .addRegMask(RegMask)
21918 .addReg(X86::RDI, RegState::Implicit)
21919 .addReg(X86::RAX, RegState::ImplicitDefine);
21920 } else if (Is64Bit) {
21921 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21923 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21924 .addExternalSymbol("__morestack_allocate_stack_space")
21925 .addRegMask(RegMask)
21926 .addReg(X86::EDI, RegState::Implicit)
21927 .addReg(X86::EAX, RegState::ImplicitDefine);
21929 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21931 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21932 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21933 .addExternalSymbol("__morestack_allocate_stack_space")
21934 .addRegMask(RegMask)
21935 .addReg(X86::EAX, RegState::ImplicitDefine);
21939 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21942 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21943 .addReg(IsLP64 ? X86::RAX : X86::EAX);
21944 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21946 // Set up the CFG correctly.
21947 BB->addSuccessor(bumpMBB);
21948 BB->addSuccessor(mallocMBB);
21949 mallocMBB->addSuccessor(continueMBB);
21950 bumpMBB->addSuccessor(continueMBB);
21952 // Take care of the PHI nodes.
21953 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21954 MI->getOperand(0).getReg())
21955 .addReg(mallocPtrVReg).addMBB(mallocMBB)
21956 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21958 // Delete the original pseudo instruction.
21959 MI->eraseFromParent();
21962 return continueMBB;
21965 MachineBasicBlock *
21966 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21967 MachineBasicBlock *BB) const {
21968 assert(!Subtarget->isTargetMachO());
21969 DebugLoc DL = MI->getDebugLoc();
21970 MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
21971 *BB->getParent(), *BB, MI, DL, false);
21972 MachineBasicBlock *ResumeBB = ResumeMI->getParent();
21973 MI->eraseFromParent(); // The pseudo instruction is gone now.
21977 MachineBasicBlock *
21978 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
21979 MachineBasicBlock *BB) const {
21980 MachineFunction *MF = BB->getParent();
21981 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21982 MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
21983 DebugLoc DL = MI->getDebugLoc();
21985 assert(!isAsynchronousEHPersonality(
21986 classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
21987 "SEH does not use catchret!");
21989 // Only 32-bit EH needs to worry about manually restoring stack pointers.
21990 if (!Subtarget->is32Bit())
21993 // C++ EH creates a new target block to hold the restore code, and wires up
21994 // the new block to the return destination with a normal JMP_4.
21995 MachineBasicBlock *RestoreMBB =
21996 MF->CreateMachineBasicBlock(BB->getBasicBlock());
21997 assert(BB->succ_size() == 1);
21998 MF->insert(std::next(BB->getIterator()), RestoreMBB);
21999 RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
22000 BB->addSuccessor(RestoreMBB);
22001 MI->getOperand(0).setMBB(RestoreMBB);
22003 auto RestoreMBBI = RestoreMBB->begin();
22004 BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
22005 BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
22009 MachineBasicBlock *
22010 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
22011 MachineBasicBlock *BB) const {
22012 MachineFunction *MF = BB->getParent();
22013 const Constant *PerFn = MF->getFunction()->getPersonalityFn();
22014 bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
22015 // Only 32-bit SEH requires special handling for catchpad.
22016 if (IsSEH && Subtarget->is32Bit()) {
22017 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22018 DebugLoc DL = MI->getDebugLoc();
22019 BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
22021 MI->eraseFromParent();
22025 MachineBasicBlock *
22026 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
22027 MachineBasicBlock *BB) const {
22028 // This is pretty easy. We're taking the value that we received from
22029 // our load from the relocation, sticking it in either RDI (x86-64)
22030 // or EAX and doing an indirect call. The return value will then
22031 // be in the normal return register.
22032 MachineFunction *F = BB->getParent();
22033 const X86InstrInfo *TII = Subtarget->getInstrInfo();
22034 DebugLoc DL = MI->getDebugLoc();
22036 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
22037 assert(MI->getOperand(3).isGlobal() && "This should be a global");
22039 // Get a register mask for the lowered call.
22040 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
22041 // proper register mask.
22042 const uint32_t *RegMask =
22043 Subtarget->is64Bit() ?
22044 Subtarget->getRegisterInfo()->getDarwinTLSCallPreservedMask() :
22045 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
22046 if (Subtarget->is64Bit()) {
22047 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22048 TII->get(X86::MOV64rm), X86::RDI)
22050 .addImm(0).addReg(0)
22051 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22052 MI->getOperand(3).getTargetFlags())
22054 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
22055 addDirectMem(MIB, X86::RDI);
22056 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
22057 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
22058 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22059 TII->get(X86::MOV32rm), X86::EAX)
22061 .addImm(0).addReg(0)
22062 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22063 MI->getOperand(3).getTargetFlags())
22065 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22066 addDirectMem(MIB, X86::EAX);
22067 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22069 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22070 TII->get(X86::MOV32rm), X86::EAX)
22071 .addReg(TII->getGlobalBaseReg(F))
22072 .addImm(0).addReg(0)
22073 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22074 MI->getOperand(3).getTargetFlags())
22076 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22077 addDirectMem(MIB, X86::EAX);
22078 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22081 MI->eraseFromParent(); // The pseudo instruction is gone now.
22085 MachineBasicBlock *
22086 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
22087 MachineBasicBlock *MBB) const {
22088 DebugLoc DL = MI->getDebugLoc();
22089 MachineFunction *MF = MBB->getParent();
22090 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22091 MachineRegisterInfo &MRI = MF->getRegInfo();
22093 const BasicBlock *BB = MBB->getBasicBlock();
22094 MachineFunction::iterator I = ++MBB->getIterator();
22096 // Memory Reference
22097 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22098 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22101 unsigned MemOpndSlot = 0;
22103 unsigned CurOp = 0;
22105 DstReg = MI->getOperand(CurOp++).getReg();
22106 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
22107 assert(RC->hasType(MVT::i32) && "Invalid destination!");
22108 unsigned mainDstReg = MRI.createVirtualRegister(RC);
22109 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
22111 MemOpndSlot = CurOp;
22113 MVT PVT = getPointerTy(MF->getDataLayout());
22114 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22115 "Invalid Pointer Size!");
22117 // For v = setjmp(buf), we generate
22120 // buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
22121 // SjLjSetup restoreMBB
22127 // v = phi(main, restore)
22130 // if base pointer being used, load it from frame
22133 MachineBasicBlock *thisMBB = MBB;
22134 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
22135 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
22136 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
22137 MF->insert(I, mainMBB);
22138 MF->insert(I, sinkMBB);
22139 MF->push_back(restoreMBB);
22140 restoreMBB->setHasAddressTaken();
22142 MachineInstrBuilder MIB;
22144 // Transfer the remainder of BB and its successor edges to sinkMBB.
22145 sinkMBB->splice(sinkMBB->begin(), MBB,
22146 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
22147 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
22150 unsigned PtrStoreOpc = 0;
22151 unsigned LabelReg = 0;
22152 const int64_t LabelOffset = 1 * PVT.getStoreSize();
22153 Reloc::Model RM = MF->getTarget().getRelocationModel();
22154 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
22155 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
22157 // Prepare IP either in reg or imm.
22158 if (!UseImmLabel) {
22159 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
22160 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
22161 LabelReg = MRI.createVirtualRegister(PtrRC);
22162 if (Subtarget->is64Bit()) {
22163 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
22167 .addMBB(restoreMBB)
22170 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
22171 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
22172 .addReg(XII->getGlobalBaseReg(MF))
22175 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
22179 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
22181 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
22182 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22183 if (i == X86::AddrDisp)
22184 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
22186 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
22189 MIB.addReg(LabelReg);
22191 MIB.addMBB(restoreMBB);
22192 MIB.setMemRefs(MMOBegin, MMOEnd);
22194 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
22195 .addMBB(restoreMBB);
22197 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22198 MIB.addRegMask(RegInfo->getNoPreservedMask());
22199 thisMBB->addSuccessor(mainMBB);
22200 thisMBB->addSuccessor(restoreMBB);
22204 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
22205 mainMBB->addSuccessor(sinkMBB);
22208 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
22209 TII->get(X86::PHI), DstReg)
22210 .addReg(mainDstReg).addMBB(mainMBB)
22211 .addReg(restoreDstReg).addMBB(restoreMBB);
22214 if (RegInfo->hasBasePointer(*MF)) {
22215 const bool Uses64BitFramePtr =
22216 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
22217 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
22218 X86FI->setRestoreBasePointer(MF);
22219 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
22220 unsigned BasePtr = RegInfo->getBaseRegister();
22221 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
22222 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
22223 FramePtr, true, X86FI->getRestoreBasePointerOffset())
22224 .setMIFlag(MachineInstr::FrameSetup);
22226 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
22227 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
22228 restoreMBB->addSuccessor(sinkMBB);
22230 MI->eraseFromParent();
22234 MachineBasicBlock *
22235 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
22236 MachineBasicBlock *MBB) const {
22237 DebugLoc DL = MI->getDebugLoc();
22238 MachineFunction *MF = MBB->getParent();
22239 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22240 MachineRegisterInfo &MRI = MF->getRegInfo();
22242 // Memory Reference
22243 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22244 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22246 MVT PVT = getPointerTy(MF->getDataLayout());
22247 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22248 "Invalid Pointer Size!");
22250 const TargetRegisterClass *RC =
22251 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
22252 unsigned Tmp = MRI.createVirtualRegister(RC);
22253 // Since FP is only updated here but NOT referenced, it's treated as GPR.
22254 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22255 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
22256 unsigned SP = RegInfo->getStackRegister();
22258 MachineInstrBuilder MIB;
22260 const int64_t LabelOffset = 1 * PVT.getStoreSize();
22261 const int64_t SPOffset = 2 * PVT.getStoreSize();
22263 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
22264 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
22267 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
22268 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
22269 MIB.addOperand(MI->getOperand(i));
22270 MIB.setMemRefs(MMOBegin, MMOEnd);
22272 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
22273 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22274 if (i == X86::AddrDisp)
22275 MIB.addDisp(MI->getOperand(i), LabelOffset);
22277 MIB.addOperand(MI->getOperand(i));
22279 MIB.setMemRefs(MMOBegin, MMOEnd);
22281 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
22282 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22283 if (i == X86::AddrDisp)
22284 MIB.addDisp(MI->getOperand(i), SPOffset);
22286 MIB.addOperand(MI->getOperand(i));
22288 MIB.setMemRefs(MMOBegin, MMOEnd);
22290 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
22292 MI->eraseFromParent();
22296 // Replace 213-type (isel default) FMA3 instructions with 231-type for
22297 // accumulator loops. Writing back to the accumulator allows the coalescer
22298 // to remove extra copies in the loop.
22299 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
22300 MachineBasicBlock *
22301 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
22302 MachineBasicBlock *MBB) const {
22303 MachineOperand &AddendOp = MI->getOperand(3);
22305 // Bail out early if the addend isn't a register - we can't switch these.
22306 if (!AddendOp.isReg())
22309 MachineFunction &MF = *MBB->getParent();
22310 MachineRegisterInfo &MRI = MF.getRegInfo();
22312 // Check whether the addend is defined by a PHI:
22313 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
22314 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
22315 if (!AddendDef.isPHI())
22318 // Look for the following pattern:
22320 // %addend = phi [%entry, 0], [%loop, %result]
22322 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
22326 // %addend = phi [%entry, 0], [%loop, %result]
22328 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
22330 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
22331 assert(AddendDef.getOperand(i).isReg());
22332 MachineOperand PHISrcOp = AddendDef.getOperand(i);
22333 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
22334 if (&PHISrcInst == MI) {
22335 // Found a matching instruction.
22336 unsigned NewFMAOpc = 0;
22337 switch (MI->getOpcode()) {
22338 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
22339 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
22340 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
22341 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
22342 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
22343 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
22344 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
22345 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
22346 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
22347 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
22348 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
22349 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
22350 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
22351 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
22352 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
22353 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
22354 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
22355 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
22356 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
22357 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
22359 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
22360 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
22361 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
22362 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
22363 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
22364 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
22365 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
22366 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
22367 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
22368 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
22369 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
22370 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
22371 default: llvm_unreachable("Unrecognized FMA variant.");
22374 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22375 MachineInstrBuilder MIB =
22376 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
22377 .addOperand(MI->getOperand(0))
22378 .addOperand(MI->getOperand(3))
22379 .addOperand(MI->getOperand(2))
22380 .addOperand(MI->getOperand(1));
22381 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
22382 MI->eraseFromParent();
22389 MachineBasicBlock *
22390 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
22391 MachineBasicBlock *BB) const {
22392 switch (MI->getOpcode()) {
22393 default: llvm_unreachable("Unexpected instr type to insert");
22394 case X86::TAILJMPd64:
22395 case X86::TAILJMPr64:
22396 case X86::TAILJMPm64:
22397 case X86::TAILJMPd64_REX:
22398 case X86::TAILJMPr64_REX:
22399 case X86::TAILJMPm64_REX:
22400 llvm_unreachable("TAILJMP64 would not be touched here.");
22401 case X86::TCRETURNdi64:
22402 case X86::TCRETURNri64:
22403 case X86::TCRETURNmi64:
22405 case X86::WIN_ALLOCA:
22406 return EmitLoweredWinAlloca(MI, BB);
22407 case X86::CATCHRET:
22408 return EmitLoweredCatchRet(MI, BB);
22409 case X86::CATCHPAD:
22410 return EmitLoweredCatchPad(MI, BB);
22411 case X86::SEG_ALLOCA_32:
22412 case X86::SEG_ALLOCA_64:
22413 return EmitLoweredSegAlloca(MI, BB);
22414 case X86::TLSCall_32:
22415 case X86::TLSCall_64:
22416 return EmitLoweredTLSCall(MI, BB);
22417 case X86::CMOV_FR32:
22418 case X86::CMOV_FR64:
22419 case X86::CMOV_FR128:
22420 case X86::CMOV_GR8:
22421 case X86::CMOV_GR16:
22422 case X86::CMOV_GR32:
22423 case X86::CMOV_RFP32:
22424 case X86::CMOV_RFP64:
22425 case X86::CMOV_RFP80:
22426 case X86::CMOV_V2F64:
22427 case X86::CMOV_V2I64:
22428 case X86::CMOV_V4F32:
22429 case X86::CMOV_V4F64:
22430 case X86::CMOV_V4I64:
22431 case X86::CMOV_V16F32:
22432 case X86::CMOV_V8F32:
22433 case X86::CMOV_V8F64:
22434 case X86::CMOV_V8I64:
22435 case X86::CMOV_V8I1:
22436 case X86::CMOV_V16I1:
22437 case X86::CMOV_V32I1:
22438 case X86::CMOV_V64I1:
22439 return EmitLoweredSelect(MI, BB);
22441 case X86::RELEASE_FADD32mr:
22442 case X86::RELEASE_FADD64mr:
22443 return EmitLoweredAtomicFP(MI, BB);
22445 case X86::FP32_TO_INT16_IN_MEM:
22446 case X86::FP32_TO_INT32_IN_MEM:
22447 case X86::FP32_TO_INT64_IN_MEM:
22448 case X86::FP64_TO_INT16_IN_MEM:
22449 case X86::FP64_TO_INT32_IN_MEM:
22450 case X86::FP64_TO_INT64_IN_MEM:
22451 case X86::FP80_TO_INT16_IN_MEM:
22452 case X86::FP80_TO_INT32_IN_MEM:
22453 case X86::FP80_TO_INT64_IN_MEM: {
22454 MachineFunction *F = BB->getParent();
22455 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22456 DebugLoc DL = MI->getDebugLoc();
22458 // Change the floating point control register to use "round towards zero"
22459 // mode when truncating to an integer value.
22460 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
22461 addFrameReference(BuildMI(*BB, MI, DL,
22462 TII->get(X86::FNSTCW16m)), CWFrameIdx);
22464 // Load the old value of the high byte of the control word...
22466 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
22467 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
22470 // Set the high part to be round to zero...
22471 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
22474 // Reload the modified control word now...
22475 addFrameReference(BuildMI(*BB, MI, DL,
22476 TII->get(X86::FLDCW16m)), CWFrameIdx);
22478 // Restore the memory image of control word to original value
22479 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
22482 // Get the X86 opcode to use.
22484 switch (MI->getOpcode()) {
22485 default: llvm_unreachable("illegal opcode!");
22486 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
22487 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
22488 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
22489 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
22490 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
22491 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
22492 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
22493 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
22494 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
22498 MachineOperand &Op = MI->getOperand(0);
22500 AM.BaseType = X86AddressMode::RegBase;
22501 AM.Base.Reg = Op.getReg();
22503 AM.BaseType = X86AddressMode::FrameIndexBase;
22504 AM.Base.FrameIndex = Op.getIndex();
22506 Op = MI->getOperand(1);
22508 AM.Scale = Op.getImm();
22509 Op = MI->getOperand(2);
22511 AM.IndexReg = Op.getImm();
22512 Op = MI->getOperand(3);
22513 if (Op.isGlobal()) {
22514 AM.GV = Op.getGlobal();
22516 AM.Disp = Op.getImm();
22518 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
22519 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
22521 // Reload the original control word now.
22522 addFrameReference(BuildMI(*BB, MI, DL,
22523 TII->get(X86::FLDCW16m)), CWFrameIdx);
22525 MI->eraseFromParent(); // The pseudo instruction is gone now.
22528 // String/text processing lowering.
22529 case X86::PCMPISTRM128REG:
22530 case X86::VPCMPISTRM128REG:
22531 case X86::PCMPISTRM128MEM:
22532 case X86::VPCMPISTRM128MEM:
22533 case X86::PCMPESTRM128REG:
22534 case X86::VPCMPESTRM128REG:
22535 case X86::PCMPESTRM128MEM:
22536 case X86::VPCMPESTRM128MEM:
22537 assert(Subtarget->hasSSE42() &&
22538 "Target must have SSE4.2 or AVX features enabled");
22539 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
22541 // String/text processing lowering.
22542 case X86::PCMPISTRIREG:
22543 case X86::VPCMPISTRIREG:
22544 case X86::PCMPISTRIMEM:
22545 case X86::VPCMPISTRIMEM:
22546 case X86::PCMPESTRIREG:
22547 case X86::VPCMPESTRIREG:
22548 case X86::PCMPESTRIMEM:
22549 case X86::VPCMPESTRIMEM:
22550 assert(Subtarget->hasSSE42() &&
22551 "Target must have SSE4.2 or AVX features enabled");
22552 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
22554 // Thread synchronization.
22556 return EmitMonitor(MI, BB, Subtarget);
22560 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
22562 case X86::VASTART_SAVE_XMM_REGS:
22563 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
22565 case X86::VAARG_64:
22566 return EmitVAARG64WithCustomInserter(MI, BB);
22568 case X86::EH_SjLj_SetJmp32:
22569 case X86::EH_SjLj_SetJmp64:
22570 return emitEHSjLjSetJmp(MI, BB);
22572 case X86::EH_SjLj_LongJmp32:
22573 case X86::EH_SjLj_LongJmp64:
22574 return emitEHSjLjLongJmp(MI, BB);
22576 case TargetOpcode::STATEPOINT:
22577 // As an implementation detail, STATEPOINT shares the STACKMAP format at
22578 // this point in the process. We diverge later.
22579 return emitPatchPoint(MI, BB);
22581 case TargetOpcode::STACKMAP:
22582 case TargetOpcode::PATCHPOINT:
22583 return emitPatchPoint(MI, BB);
22585 case X86::VFMADDPDr213r:
22586 case X86::VFMADDPSr213r:
22587 case X86::VFMADDSDr213r:
22588 case X86::VFMADDSSr213r:
22589 case X86::VFMSUBPDr213r:
22590 case X86::VFMSUBPSr213r:
22591 case X86::VFMSUBSDr213r:
22592 case X86::VFMSUBSSr213r:
22593 case X86::VFNMADDPDr213r:
22594 case X86::VFNMADDPSr213r:
22595 case X86::VFNMADDSDr213r:
22596 case X86::VFNMADDSSr213r:
22597 case X86::VFNMSUBPDr213r:
22598 case X86::VFNMSUBPSr213r:
22599 case X86::VFNMSUBSDr213r:
22600 case X86::VFNMSUBSSr213r:
22601 case X86::VFMADDSUBPDr213r:
22602 case X86::VFMADDSUBPSr213r:
22603 case X86::VFMSUBADDPDr213r:
22604 case X86::VFMSUBADDPSr213r:
22605 case X86::VFMADDPDr213rY:
22606 case X86::VFMADDPSr213rY:
22607 case X86::VFMSUBPDr213rY:
22608 case X86::VFMSUBPSr213rY:
22609 case X86::VFNMADDPDr213rY:
22610 case X86::VFNMADDPSr213rY:
22611 case X86::VFNMSUBPDr213rY:
22612 case X86::VFNMSUBPSr213rY:
22613 case X86::VFMADDSUBPDr213rY:
22614 case X86::VFMADDSUBPSr213rY:
22615 case X86::VFMSUBADDPDr213rY:
22616 case X86::VFMSUBADDPSr213rY:
22617 return emitFMA3Instr(MI, BB);
22621 //===----------------------------------------------------------------------===//
22622 // X86 Optimization Hooks
22623 //===----------------------------------------------------------------------===//
22625 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22628 const SelectionDAG &DAG,
22629 unsigned Depth) const {
22630 unsigned BitWidth = KnownZero.getBitWidth();
22631 unsigned Opc = Op.getOpcode();
22632 assert((Opc >= ISD::BUILTIN_OP_END ||
22633 Opc == ISD::INTRINSIC_WO_CHAIN ||
22634 Opc == ISD::INTRINSIC_W_CHAIN ||
22635 Opc == ISD::INTRINSIC_VOID) &&
22636 "Should use MaskedValueIsZero if you don't know whether Op"
22637 " is a target node!");
22639 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
22653 // These nodes' second result is a boolean.
22654 if (Op.getResNo() == 0)
22657 case X86ISD::SETCC:
22658 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22660 case ISD::INTRINSIC_WO_CHAIN: {
22661 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22662 unsigned NumLoBits = 0;
22665 case Intrinsic::x86_sse_movmsk_ps:
22666 case Intrinsic::x86_avx_movmsk_ps_256:
22667 case Intrinsic::x86_sse2_movmsk_pd:
22668 case Intrinsic::x86_avx_movmsk_pd_256:
22669 case Intrinsic::x86_mmx_pmovmskb:
22670 case Intrinsic::x86_sse2_pmovmskb_128:
22671 case Intrinsic::x86_avx2_pmovmskb: {
22672 // High bits of movmskp{s|d}, pmovmskb are known zero.
22674 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
22675 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
22676 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
22677 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
22678 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
22679 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
22680 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
22681 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
22683 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22692 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22694 const SelectionDAG &,
22695 unsigned Depth) const {
22696 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22697 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22698 return Op.getValueType().getScalarSizeInBits();
22704 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22705 /// node is a GlobalAddress + offset.
22706 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22707 const GlobalValue* &GA,
22708 int64_t &Offset) const {
22709 if (N->getOpcode() == X86ISD::Wrapper) {
22710 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22711 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22712 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22716 return TargetLowering::isGAPlusOffset(N, GA, Offset);
22719 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22720 /// FIXME: This could be expanded to support 512 bit vectors as well.
22721 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22722 TargetLowering::DAGCombinerInfo &DCI,
22723 const X86Subtarget* Subtarget) {
22725 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22726 SDValue V1 = SVOp->getOperand(0);
22727 SDValue V2 = SVOp->getOperand(1);
22728 MVT VT = SVOp->getSimpleValueType(0);
22729 unsigned NumElems = VT.getVectorNumElements();
22731 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22732 V2.getOpcode() == ISD::CONCAT_VECTORS) {
22736 // V UNDEF BUILD_VECTOR UNDEF
22738 // CONCAT_VECTOR CONCAT_VECTOR
22741 // RESULT: V + zero extended
22743 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22744 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22745 V1.getOperand(1).getOpcode() != ISD::UNDEF)
22748 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22751 // To match the shuffle mask, the first half of the mask should
22752 // be exactly the first vector, and all the rest a splat with the
22753 // first element of the second one.
22754 for (unsigned i = 0; i != NumElems/2; ++i)
22755 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22756 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22759 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22760 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22761 if (Ld->hasNUsesOfValue(1, 0)) {
22762 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22763 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22765 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22767 Ld->getPointerInfo(),
22768 Ld->getAlignment(),
22769 false/*isVolatile*/, true/*ReadMem*/,
22770 false/*WriteMem*/);
22772 // Make sure the newly-created LOAD is in the same position as Ld in
22773 // terms of dependency. We create a TokenFactor for Ld and ResNode,
22774 // and update uses of Ld's output chain to use the TokenFactor.
22775 if (Ld->hasAnyUseOfValue(1)) {
22776 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22777 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22778 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22779 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22780 SDValue(ResNode.getNode(), 1));
22783 return DAG.getBitcast(VT, ResNode);
22787 // Emit a zeroed vector and insert the desired subvector on its
22789 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22790 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22791 return DCI.CombineTo(N, InsV);
22797 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22800 /// This is the leaf of the recursive combinine below. When we have found some
22801 /// chain of single-use x86 shuffle instructions and accumulated the combined
22802 /// shuffle mask represented by them, this will try to pattern match that mask
22803 /// into either a single instruction if there is a special purpose instruction
22804 /// for this operation, or into a PSHUFB instruction which is a fully general
22805 /// instruction but should only be used to replace chains over a certain depth.
22806 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
22807 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
22808 TargetLowering::DAGCombinerInfo &DCI,
22809 const X86Subtarget *Subtarget) {
22810 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
22812 // Find the operand that enters the chain. Note that multiple uses are OK
22813 // here, we're not going to remove the operand we find.
22814 SDValue Input = Op.getOperand(0);
22815 while (Input.getOpcode() == ISD::BITCAST)
22816 Input = Input.getOperand(0);
22818 MVT VT = Input.getSimpleValueType();
22819 MVT RootVT = Root.getSimpleValueType();
22822 if (Mask.size() == 1) {
22823 int Index = Mask[0];
22824 assert((Index >= 0 || Index == SM_SentinelUndef ||
22825 Index == SM_SentinelZero) &&
22826 "Invalid shuffle index found!");
22828 // We may end up with an accumulated mask of size 1 as a result of
22829 // widening of shuffle operands (see function canWidenShuffleElements).
22830 // If the only shuffle index is equal to SM_SentinelZero then propagate
22831 // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
22832 // mask, and therefore the entire chain of shuffles can be folded away.
22833 if (Index == SM_SentinelZero)
22834 DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
22836 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
22841 // Use the float domain if the operand type is a floating point type.
22842 bool FloatDomain = VT.isFloatingPoint();
22844 // For floating point shuffles, we don't have free copies in the shuffle
22845 // instructions or the ability to load as part of the instruction, so
22846 // canonicalize their shuffles to UNPCK or MOV variants.
22848 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
22849 // vectors because it can have a load folded into it that UNPCK cannot. This
22850 // doesn't preclude something switching to the shorter encoding post-RA.
22852 // FIXME: Should teach these routines about AVX vector widths.
22853 if (FloatDomain && VT.is128BitVector()) {
22854 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
22855 bool Lo = Mask.equals({0, 0});
22858 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
22859 // is no slower than UNPCKLPD but has the option to fold the input operand
22860 // into even an unaligned memory load.
22861 if (Lo && Subtarget->hasSSE3()) {
22862 Shuffle = X86ISD::MOVDDUP;
22863 ShuffleVT = MVT::v2f64;
22865 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
22866 // than the UNPCK variants.
22867 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
22868 ShuffleVT = MVT::v4f32;
22870 if (Depth == 1 && Root->getOpcode() == Shuffle)
22871 return false; // Nothing to do!
22872 Op = DAG.getBitcast(ShuffleVT, Input);
22873 DCI.AddToWorklist(Op.getNode());
22874 if (Shuffle == X86ISD::MOVDDUP)
22875 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22877 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22878 DCI.AddToWorklist(Op.getNode());
22879 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22883 if (Subtarget->hasSSE3() &&
22884 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
22885 bool Lo = Mask.equals({0, 0, 2, 2});
22886 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
22887 MVT ShuffleVT = MVT::v4f32;
22888 if (Depth == 1 && Root->getOpcode() == Shuffle)
22889 return false; // Nothing to do!
22890 Op = DAG.getBitcast(ShuffleVT, Input);
22891 DCI.AddToWorklist(Op.getNode());
22892 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22893 DCI.AddToWorklist(Op.getNode());
22894 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22898 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
22899 bool Lo = Mask.equals({0, 0, 1, 1});
22900 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22901 MVT ShuffleVT = MVT::v4f32;
22902 if (Depth == 1 && Root->getOpcode() == Shuffle)
22903 return false; // Nothing to do!
22904 Op = DAG.getBitcast(ShuffleVT, Input);
22905 DCI.AddToWorklist(Op.getNode());
22906 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22907 DCI.AddToWorklist(Op.getNode());
22908 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22914 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
22915 // variants as none of these have single-instruction variants that are
22916 // superior to the UNPCK formulation.
22917 if (!FloatDomain && VT.is128BitVector() &&
22918 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22919 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
22920 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
22922 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
22923 bool Lo = Mask[0] == 0;
22924 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22925 if (Depth == 1 && Root->getOpcode() == Shuffle)
22926 return false; // Nothing to do!
22928 switch (Mask.size()) {
22930 ShuffleVT = MVT::v8i16;
22933 ShuffleVT = MVT::v16i8;
22936 llvm_unreachable("Impossible mask size!");
22938 Op = DAG.getBitcast(ShuffleVT, Input);
22939 DCI.AddToWorklist(Op.getNode());
22940 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22941 DCI.AddToWorklist(Op.getNode());
22942 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22947 // Don't try to re-form single instruction chains under any circumstances now
22948 // that we've done encoding canonicalization for them.
22952 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22953 // can replace them with a single PSHUFB instruction profitably. Intel's
22954 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22955 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22956 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22957 SmallVector<SDValue, 16> PSHUFBMask;
22958 int NumBytes = VT.getSizeInBits() / 8;
22959 int Ratio = NumBytes / Mask.size();
22960 for (int i = 0; i < NumBytes; ++i) {
22961 if (Mask[i / Ratio] == SM_SentinelUndef) {
22962 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22965 int M = Mask[i / Ratio] != SM_SentinelZero
22966 ? Ratio * Mask[i / Ratio] + i % Ratio
22968 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
22970 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
22971 Op = DAG.getBitcast(ByteVT, Input);
22972 DCI.AddToWorklist(Op.getNode());
22973 SDValue PSHUFBMaskOp =
22974 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
22975 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22976 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
22977 DCI.AddToWorklist(Op.getNode());
22978 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22983 // Failed to find any combines.
22987 /// \brief Fully generic combining of x86 shuffle instructions.
22989 /// This should be the last combine run over the x86 shuffle instructions. Once
22990 /// they have been fully optimized, this will recursively consider all chains
22991 /// of single-use shuffle instructions, build a generic model of the cumulative
22992 /// shuffle operation, and check for simpler instructions which implement this
22993 /// operation. We use this primarily for two purposes:
22995 /// 1) Collapse generic shuffles to specialized single instructions when
22996 /// equivalent. In most cases, this is just an encoding size win, but
22997 /// sometimes we will collapse multiple generic shuffles into a single
22998 /// special-purpose shuffle.
22999 /// 2) Look for sequences of shuffle instructions with 3 or more total
23000 /// instructions, and replace them with the slightly more expensive SSSE3
23001 /// PSHUFB instruction if available. We do this as the last combining step
23002 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
23003 /// a suitable short sequence of other instructions. The PHUFB will either
23004 /// use a register or have to read from memory and so is slightly (but only
23005 /// slightly) more expensive than the other shuffle instructions.
23007 /// Because this is inherently a quadratic operation (for each shuffle in
23008 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
23009 /// This should never be an issue in practice as the shuffle lowering doesn't
23010 /// produce sequences of more than 8 instructions.
23012 /// FIXME: We will currently miss some cases where the redundant shuffling
23013 /// would simplify under the threshold for PSHUFB formation because of
23014 /// combine-ordering. To fix this, we should do the redundant instruction
23015 /// combining in this recursive walk.
23016 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
23017 ArrayRef<int> RootMask,
23018 int Depth, bool HasPSHUFB,
23020 TargetLowering::DAGCombinerInfo &DCI,
23021 const X86Subtarget *Subtarget) {
23022 // Bound the depth of our recursive combine because this is ultimately
23023 // quadratic in nature.
23027 // Directly rip through bitcasts to find the underlying operand.
23028 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
23029 Op = Op.getOperand(0);
23031 MVT VT = Op.getSimpleValueType();
23032 if (!VT.isVector())
23033 return false; // Bail if we hit a non-vector.
23035 assert(Root.getSimpleValueType().isVector() &&
23036 "Shuffles operate on vector types!");
23037 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
23038 "Can only combine shuffles of the same vector register size.");
23040 if (!isTargetShuffle(Op.getOpcode()))
23042 SmallVector<int, 16> OpMask;
23044 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
23045 // We only can combine unary shuffles which we can decode the mask for.
23046 if (!HaveMask || !IsUnary)
23049 assert(VT.getVectorNumElements() == OpMask.size() &&
23050 "Different mask size from vector size!");
23051 assert(((RootMask.size() > OpMask.size() &&
23052 RootMask.size() % OpMask.size() == 0) ||
23053 (OpMask.size() > RootMask.size() &&
23054 OpMask.size() % RootMask.size() == 0) ||
23055 OpMask.size() == RootMask.size()) &&
23056 "The smaller number of elements must divide the larger.");
23057 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
23058 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
23059 assert(((RootRatio == 1 && OpRatio == 1) ||
23060 (RootRatio == 1) != (OpRatio == 1)) &&
23061 "Must not have a ratio for both incoming and op masks!");
23063 SmallVector<int, 16> Mask;
23064 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
23066 // Merge this shuffle operation's mask into our accumulated mask. Note that
23067 // this shuffle's mask will be the first applied to the input, followed by the
23068 // root mask to get us all the way to the root value arrangement. The reason
23069 // for this order is that we are recursing up the operation chain.
23070 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
23071 int RootIdx = i / RootRatio;
23072 if (RootMask[RootIdx] < 0) {
23073 // This is a zero or undef lane, we're done.
23074 Mask.push_back(RootMask[RootIdx]);
23078 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
23079 int OpIdx = RootMaskedIdx / OpRatio;
23080 if (OpMask[OpIdx] < 0) {
23081 // The incoming lanes are zero or undef, it doesn't matter which ones we
23083 Mask.push_back(OpMask[OpIdx]);
23087 // Ok, we have non-zero lanes, map them through.
23088 Mask.push_back(OpMask[OpIdx] * OpRatio +
23089 RootMaskedIdx % OpRatio);
23092 // See if we can recurse into the operand to combine more things.
23093 switch (Op.getOpcode()) {
23094 case X86ISD::PSHUFB:
23096 case X86ISD::PSHUFD:
23097 case X86ISD::PSHUFHW:
23098 case X86ISD::PSHUFLW:
23099 if (Op.getOperand(0).hasOneUse() &&
23100 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23101 HasPSHUFB, DAG, DCI, Subtarget))
23105 case X86ISD::UNPCKL:
23106 case X86ISD::UNPCKH:
23107 assert(Op.getOperand(0) == Op.getOperand(1) &&
23108 "We only combine unary shuffles!");
23109 // We can't check for single use, we have to check that this shuffle is the
23111 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
23112 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23113 HasPSHUFB, DAG, DCI, Subtarget))
23118 // Minor canonicalization of the accumulated shuffle mask to make it easier
23119 // to match below. All this does is detect masks with squential pairs of
23120 // elements, and shrink them to the half-width mask. It does this in a loop
23121 // so it will reduce the size of the mask to the minimal width mask which
23122 // performs an equivalent shuffle.
23123 SmallVector<int, 16> WidenedMask;
23124 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
23125 Mask = std::move(WidenedMask);
23126 WidenedMask.clear();
23129 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
23133 /// \brief Get the PSHUF-style mask from PSHUF node.
23135 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
23136 /// PSHUF-style masks that can be reused with such instructions.
23137 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
23138 MVT VT = N.getSimpleValueType();
23139 SmallVector<int, 4> Mask;
23141 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
23145 // If we have more than 128-bits, only the low 128-bits of shuffle mask
23146 // matter. Check that the upper masks are repeats and remove them.
23147 if (VT.getSizeInBits() > 128) {
23148 int LaneElts = 128 / VT.getScalarSizeInBits();
23150 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
23151 for (int j = 0; j < LaneElts; ++j)
23152 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
23153 "Mask doesn't repeat in high 128-bit lanes!");
23155 Mask.resize(LaneElts);
23158 switch (N.getOpcode()) {
23159 case X86ISD::PSHUFD:
23161 case X86ISD::PSHUFLW:
23164 case X86ISD::PSHUFHW:
23165 Mask.erase(Mask.begin(), Mask.begin() + 4);
23166 for (int &M : Mask)
23170 llvm_unreachable("No valid shuffle instruction found!");
23174 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
23176 /// We walk up the chain and look for a combinable shuffle, skipping over
23177 /// shuffles that we could hoist this shuffle's transformation past without
23178 /// altering anything.
23180 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
23182 TargetLowering::DAGCombinerInfo &DCI) {
23183 assert(N.getOpcode() == X86ISD::PSHUFD &&
23184 "Called with something other than an x86 128-bit half shuffle!");
23187 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
23188 // of the shuffles in the chain so that we can form a fresh chain to replace
23190 SmallVector<SDValue, 8> Chain;
23191 SDValue V = N.getOperand(0);
23192 for (; V.hasOneUse(); V = V.getOperand(0)) {
23193 switch (V.getOpcode()) {
23195 return SDValue(); // Nothing combined!
23198 // Skip bitcasts as we always know the type for the target specific
23202 case X86ISD::PSHUFD:
23203 // Found another dword shuffle.
23206 case X86ISD::PSHUFLW:
23207 // Check that the low words (being shuffled) are the identity in the
23208 // dword shuffle, and the high words are self-contained.
23209 if (Mask[0] != 0 || Mask[1] != 1 ||
23210 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
23213 Chain.push_back(V);
23216 case X86ISD::PSHUFHW:
23217 // Check that the high words (being shuffled) are the identity in the
23218 // dword shuffle, and the low words are self-contained.
23219 if (Mask[2] != 2 || Mask[3] != 3 ||
23220 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
23223 Chain.push_back(V);
23226 case X86ISD::UNPCKL:
23227 case X86ISD::UNPCKH:
23228 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
23229 // shuffle into a preceding word shuffle.
23230 if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
23231 V.getSimpleValueType().getVectorElementType() != MVT::i16)
23234 // Search for a half-shuffle which we can combine with.
23235 unsigned CombineOp =
23236 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
23237 if (V.getOperand(0) != V.getOperand(1) ||
23238 !V->isOnlyUserOf(V.getOperand(0).getNode()))
23240 Chain.push_back(V);
23241 V = V.getOperand(0);
23243 switch (V.getOpcode()) {
23245 return SDValue(); // Nothing to combine.
23247 case X86ISD::PSHUFLW:
23248 case X86ISD::PSHUFHW:
23249 if (V.getOpcode() == CombineOp)
23252 Chain.push_back(V);
23256 V = V.getOperand(0);
23260 } while (V.hasOneUse());
23263 // Break out of the loop if we break out of the switch.
23267 if (!V.hasOneUse())
23268 // We fell out of the loop without finding a viable combining instruction.
23271 // Merge this node's mask and our incoming mask.
23272 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23273 for (int &M : Mask)
23275 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
23276 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23278 // Rebuild the chain around this new shuffle.
23279 while (!Chain.empty()) {
23280 SDValue W = Chain.pop_back_val();
23282 if (V.getValueType() != W.getOperand(0).getValueType())
23283 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
23285 switch (W.getOpcode()) {
23287 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
23289 case X86ISD::UNPCKL:
23290 case X86ISD::UNPCKH:
23291 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
23294 case X86ISD::PSHUFD:
23295 case X86ISD::PSHUFLW:
23296 case X86ISD::PSHUFHW:
23297 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
23301 if (V.getValueType() != N.getValueType())
23302 V = DAG.getBitcast(N.getValueType(), V);
23304 // Return the new chain to replace N.
23308 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
23311 /// We walk up the chain, skipping shuffles of the other half and looking
23312 /// through shuffles which switch halves trying to find a shuffle of the same
23313 /// pair of dwords.
23314 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
23316 TargetLowering::DAGCombinerInfo &DCI) {
23318 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
23319 "Called with something other than an x86 128-bit half shuffle!");
23321 unsigned CombineOpcode = N.getOpcode();
23323 // Walk up a single-use chain looking for a combinable shuffle.
23324 SDValue V = N.getOperand(0);
23325 for (; V.hasOneUse(); V = V.getOperand(0)) {
23326 switch (V.getOpcode()) {
23328 return false; // Nothing combined!
23331 // Skip bitcasts as we always know the type for the target specific
23335 case X86ISD::PSHUFLW:
23336 case X86ISD::PSHUFHW:
23337 if (V.getOpcode() == CombineOpcode)
23340 // Other-half shuffles are no-ops.
23343 // Break out of the loop if we break out of the switch.
23347 if (!V.hasOneUse())
23348 // We fell out of the loop without finding a viable combining instruction.
23351 // Combine away the bottom node as its shuffle will be accumulated into
23352 // a preceding shuffle.
23353 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23355 // Record the old value.
23358 // Merge this node's mask and our incoming mask (adjusted to account for all
23359 // the pshufd instructions encountered).
23360 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23361 for (int &M : Mask)
23363 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
23364 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23366 // Check that the shuffles didn't cancel each other out. If not, we need to
23367 // combine to the new one.
23369 // Replace the combinable shuffle with the combined one, updating all users
23370 // so that we re-evaluate the chain here.
23371 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
23376 /// \brief Try to combine x86 target specific shuffles.
23377 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
23378 TargetLowering::DAGCombinerInfo &DCI,
23379 const X86Subtarget *Subtarget) {
23381 MVT VT = N.getSimpleValueType();
23382 SmallVector<int, 4> Mask;
23384 switch (N.getOpcode()) {
23385 case X86ISD::PSHUFD:
23386 case X86ISD::PSHUFLW:
23387 case X86ISD::PSHUFHW:
23388 Mask = getPSHUFShuffleMask(N);
23389 assert(Mask.size() == 4);
23391 case X86ISD::UNPCKL: {
23392 // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
23393 // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
23394 // moves upper half elements into the lower half part. For example:
23396 // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
23398 // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
23400 // will be combined to:
23402 // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
23404 // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
23405 // happen due to advanced instructions.
23406 if (!VT.is128BitVector())
23409 auto Op0 = N.getOperand(0);
23410 auto Op1 = N.getOperand(1);
23411 if (Op0.getOpcode() == ISD::UNDEF &&
23412 Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
23413 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
23415 unsigned NumElts = VT.getVectorNumElements();
23416 SmallVector<int, 8> ExpectedMask(NumElts, -1);
23417 std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
23420 auto ShufOp = Op1.getOperand(0);
23421 if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
23422 return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
23430 // Nuke no-op shuffles that show up after combining.
23431 if (isNoopShuffleMask(Mask))
23432 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23434 // Look for simplifications involving one or two shuffle instructions.
23435 SDValue V = N.getOperand(0);
23436 switch (N.getOpcode()) {
23439 case X86ISD::PSHUFLW:
23440 case X86ISD::PSHUFHW:
23441 assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
23443 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
23444 return SDValue(); // We combined away this shuffle, so we're done.
23446 // See if this reduces to a PSHUFD which is no more expensive and can
23447 // combine with more operations. Note that it has to at least flip the
23448 // dwords as otherwise it would have been removed as a no-op.
23449 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
23450 int DMask[] = {0, 1, 2, 3};
23451 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
23452 DMask[DOffset + 0] = DOffset + 1;
23453 DMask[DOffset + 1] = DOffset + 0;
23454 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
23455 V = DAG.getBitcast(DVT, V);
23456 DCI.AddToWorklist(V.getNode());
23457 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
23458 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
23459 DCI.AddToWorklist(V.getNode());
23460 return DAG.getBitcast(VT, V);
23463 // Look for shuffle patterns which can be implemented as a single unpack.
23464 // FIXME: This doesn't handle the location of the PSHUFD generically, and
23465 // only works when we have a PSHUFD followed by two half-shuffles.
23466 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
23467 (V.getOpcode() == X86ISD::PSHUFLW ||
23468 V.getOpcode() == X86ISD::PSHUFHW) &&
23469 V.getOpcode() != N.getOpcode() &&
23471 SDValue D = V.getOperand(0);
23472 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
23473 D = D.getOperand(0);
23474 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
23475 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23476 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
23477 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23478 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23480 for (int i = 0; i < 4; ++i) {
23481 WordMask[i + NOffset] = Mask[i] + NOffset;
23482 WordMask[i + VOffset] = VMask[i] + VOffset;
23484 // Map the word mask through the DWord mask.
23486 for (int i = 0; i < 8; ++i)
23487 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
23488 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23489 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
23490 // We can replace all three shuffles with an unpack.
23491 V = DAG.getBitcast(VT, D.getOperand(0));
23492 DCI.AddToWorklist(V.getNode());
23493 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
23502 case X86ISD::PSHUFD:
23503 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
23512 /// \brief Try to combine a shuffle into a target-specific add-sub node.
23514 /// We combine this directly on the abstract vector shuffle nodes so it is
23515 /// easier to generically match. We also insert dummy vector shuffle nodes for
23516 /// the operands which explicitly discard the lanes which are unused by this
23517 /// operation to try to flow through the rest of the combiner the fact that
23518 /// they're unused.
23519 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
23521 EVT VT = N->getValueType(0);
23523 // We only handle target-independent shuffles.
23524 // FIXME: It would be easy and harmless to use the target shuffle mask
23525 // extraction tool to support more.
23526 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
23529 auto *SVN = cast<ShuffleVectorSDNode>(N);
23530 SmallVector<int, 8> Mask;
23531 for (int M : SVN->getMask())
23534 SDValue V1 = N->getOperand(0);
23535 SDValue V2 = N->getOperand(1);
23537 // We require the first shuffle operand to be the FSUB node, and the second to
23538 // be the FADD node.
23539 if (V1.getOpcode() == ISD::FADD && V2.getOpcode() == ISD::FSUB) {
23540 ShuffleVectorSDNode::commuteMask(Mask);
23542 } else if (V1.getOpcode() != ISD::FSUB || V2.getOpcode() != ISD::FADD)
23545 // If there are other uses of these operations we can't fold them.
23546 if (!V1->hasOneUse() || !V2->hasOneUse())
23549 // Ensure that both operations have the same operands. Note that we can
23550 // commute the FADD operands.
23551 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
23552 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
23553 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
23556 // We're looking for blends between FADD and FSUB nodes. We insist on these
23557 // nodes being lined up in a specific expected pattern.
23558 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
23559 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
23560 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
23563 // Only specific types are legal at this point, assert so we notice if and
23564 // when these change.
23565 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
23566 VT == MVT::v4f64) &&
23567 "Unknown vector type encountered!");
23569 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
23572 /// PerformShuffleCombine - Performs several different shuffle combines.
23573 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
23574 TargetLowering::DAGCombinerInfo &DCI,
23575 const X86Subtarget *Subtarget) {
23577 SDValue N0 = N->getOperand(0);
23578 SDValue N1 = N->getOperand(1);
23579 EVT VT = N->getValueType(0);
23581 // Don't create instructions with illegal types after legalize types has run.
23582 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23583 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23586 // If we have legalized the vector types, look for blends of FADD and FSUB
23587 // nodes that we can fuse into an ADDSUB node.
23588 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
23589 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
23592 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23593 if (TLI.isTypeLegal(VT) && Subtarget->hasFp256() && VT.is256BitVector() &&
23594 N->getOpcode() == ISD::VECTOR_SHUFFLE)
23595 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23597 // During Type Legalization, when promoting illegal vector types,
23598 // the backend might introduce new shuffle dag nodes and bitcasts.
23600 // This code performs the following transformation:
23601 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23602 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23604 // We do this only if both the bitcast and the BINOP dag nodes have
23605 // one use. Also, perform this transformation only if the new binary
23606 // operation is legal. This is to avoid introducing dag nodes that
23607 // potentially need to be further expanded (or custom lowered) into a
23608 // less optimal sequence of dag nodes.
23609 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23610 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23611 N0.getOpcode() == ISD::BITCAST) {
23612 SDValue BC0 = N0.getOperand(0);
23613 EVT SVT = BC0.getValueType();
23614 unsigned Opcode = BC0.getOpcode();
23615 unsigned NumElts = VT.getVectorNumElements();
23617 if (BC0.hasOneUse() && SVT.isVector() &&
23618 SVT.getVectorNumElements() * 2 == NumElts &&
23619 TLI.isOperationLegal(Opcode, VT)) {
23620 bool CanFold = false;
23632 unsigned SVTNumElts = SVT.getVectorNumElements();
23633 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23634 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23635 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23636 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23637 CanFold = SVOp->getMaskElt(i) < 0;
23640 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23641 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23642 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23643 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23648 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23649 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23650 // consecutive, non-overlapping, and in the right order.
23651 SmallVector<SDValue, 16> Elts;
23652 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23653 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23655 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23658 if (isTargetShuffle(N->getOpcode())) {
23660 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23661 if (Shuffle.getNode())
23664 // Try recursively combining arbitrary sequences of x86 shuffle
23665 // instructions into higher-order shuffles. We do this after combining
23666 // specific PSHUF instruction sequences into their minimal form so that we
23667 // can evaluate how many specialized shuffle instructions are involved in
23668 // a particular chain.
23669 SmallVector<int, 1> NonceMask; // Just a placeholder.
23670 NonceMask.push_back(0);
23671 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23672 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23674 return SDValue(); // This routine will use CombineTo to replace N.
23680 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23681 /// specific shuffle of a load can be folded into a single element load.
23682 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23683 /// shuffles have been custom lowered so we need to handle those here.
23684 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23685 TargetLowering::DAGCombinerInfo &DCI) {
23686 if (DCI.isBeforeLegalizeOps())
23689 SDValue InVec = N->getOperand(0);
23690 SDValue EltNo = N->getOperand(1);
23692 if (!isa<ConstantSDNode>(EltNo))
23695 EVT OriginalVT = InVec.getValueType();
23697 if (InVec.getOpcode() == ISD::BITCAST) {
23698 // Don't duplicate a load with other uses.
23699 if (!InVec.hasOneUse())
23701 EVT BCVT = InVec.getOperand(0).getValueType();
23702 if (!BCVT.isVector() ||
23703 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23705 InVec = InVec.getOperand(0);
23708 EVT CurrentVT = InVec.getValueType();
23710 if (!isTargetShuffle(InVec.getOpcode()))
23713 // Don't duplicate a load with other uses.
23714 if (!InVec.hasOneUse())
23717 SmallVector<int, 16> ShuffleMask;
23719 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
23720 ShuffleMask, UnaryShuffle))
23723 // Select the input vector, guarding against out of range extract vector.
23724 unsigned NumElems = CurrentVT.getVectorNumElements();
23725 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23726 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
23727 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23728 : InVec.getOperand(1);
23730 // If inputs to shuffle are the same for both ops, then allow 2 uses
23731 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
23732 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
23734 if (LdNode.getOpcode() == ISD::BITCAST) {
23735 // Don't duplicate a load with other uses.
23736 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
23739 AllowedUses = 1; // only allow 1 load use if we have a bitcast
23740 LdNode = LdNode.getOperand(0);
23743 if (!ISD::isNormalLoad(LdNode.getNode()))
23746 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23748 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23751 EVT EltVT = N->getValueType(0);
23752 // If there's a bitcast before the shuffle, check if the load type and
23753 // alignment is valid.
23754 unsigned Align = LN0->getAlignment();
23755 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23756 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23757 EltVT.getTypeForEVT(*DAG.getContext()));
23759 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23762 // All checks match so transform back to vector_shuffle so that DAG combiner
23763 // can finish the job
23766 // Create shuffle node taking into account the case that its a unary shuffle
23767 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23768 : InVec.getOperand(1);
23769 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23770 InVec.getOperand(0), Shuffle,
23772 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
23773 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
23777 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
23778 const X86Subtarget *Subtarget) {
23779 SDValue N0 = N->getOperand(0);
23780 EVT VT = N->getValueType(0);
23782 // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
23783 // special and don't usually play with other vector types, it's better to
23784 // handle them early to be sure we emit efficient code by avoiding
23785 // store-load conversions.
23786 if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
23787 N0.getValueType() == MVT::v2i32 &&
23788 isNullConstant(N0.getOperand(1))) {
23789 SDValue N00 = N0->getOperand(0);
23790 if (N00.getValueType() == MVT::i32)
23791 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
23794 // Convert a bitcasted integer logic operation that has one bitcasted
23795 // floating-point operand and one constant operand into a floating-point
23796 // logic operation. This may create a load of the constant, but that is
23797 // cheaper than materializing the constant in an integer register and
23798 // transferring it to an SSE register or transferring the SSE operand to
23799 // integer register and back.
23801 switch (N0.getOpcode()) {
23802 case ISD::AND: FPOpcode = X86ISD::FAND; break;
23803 case ISD::OR: FPOpcode = X86ISD::FOR; break;
23804 case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
23805 default: return SDValue();
23807 if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
23808 (Subtarget->hasSSE2() && VT == MVT::f64)) &&
23809 isa<ConstantSDNode>(N0.getOperand(1)) &&
23810 N0.getOperand(0).getOpcode() == ISD::BITCAST &&
23811 N0.getOperand(0).getOperand(0).getValueType() == VT) {
23812 SDValue N000 = N0.getOperand(0).getOperand(0);
23813 SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
23814 return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
23820 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
23821 /// generation and convert it from being a bunch of shuffles and extracts
23822 /// into a somewhat faster sequence. For i686, the best sequence is apparently
23823 /// storing the value and loading scalars back, while for x64 we should
23824 /// use 64-bit extracts and shifts.
23825 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
23826 TargetLowering::DAGCombinerInfo &DCI) {
23827 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
23830 SDValue InputVector = N->getOperand(0);
23831 SDLoc dl(InputVector);
23832 // Detect mmx to i32 conversion through a v2i32 elt extract.
23833 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
23834 N->getValueType(0) == MVT::i32 &&
23835 InputVector.getValueType() == MVT::v2i32) {
23837 // The bitcast source is a direct mmx result.
23838 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
23839 if (MMXSrc.getValueType() == MVT::x86mmx)
23840 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23841 N->getValueType(0),
23842 InputVector.getNode()->getOperand(0));
23844 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
23845 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
23846 MMXSrc.getValueType() == MVT::i64) {
23847 SDValue MMXSrcOp = MMXSrc.getOperand(0);
23848 if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
23849 MMXSrcOp.getValueType() == MVT::v1i64 &&
23850 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
23851 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23852 N->getValueType(0), MMXSrcOp.getOperand(0));
23856 EVT VT = N->getValueType(0);
23858 if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
23859 InputVector.getOpcode() == ISD::BITCAST &&
23860 isa<ConstantSDNode>(InputVector.getOperand(0))) {
23861 uint64_t ExtractedElt =
23862 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
23863 uint64_t InputValue =
23864 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
23865 uint64_t Res = (InputValue >> ExtractedElt) & 1;
23866 return DAG.getConstant(Res, dl, MVT::i1);
23868 // Only operate on vectors of 4 elements, where the alternative shuffling
23869 // gets to be more expensive.
23870 if (InputVector.getValueType() != MVT::v4i32)
23873 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
23874 // single use which is a sign-extend or zero-extend, and all elements are
23876 SmallVector<SDNode *, 4> Uses;
23877 unsigned ExtractedElements = 0;
23878 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
23879 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
23880 if (UI.getUse().getResNo() != InputVector.getResNo())
23883 SDNode *Extract = *UI;
23884 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
23887 if (Extract->getValueType(0) != MVT::i32)
23889 if (!Extract->hasOneUse())
23891 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
23892 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
23894 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
23897 // Record which element was extracted.
23898 ExtractedElements |=
23899 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
23901 Uses.push_back(Extract);
23904 // If not all the elements were used, this may not be worthwhile.
23905 if (ExtractedElements != 15)
23908 // Ok, we've now decided to do the transformation.
23909 // If 64-bit shifts are legal, use the extract-shift sequence,
23910 // otherwise bounce the vector off the cache.
23911 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23914 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
23915 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
23916 auto &DL = DAG.getDataLayout();
23917 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
23918 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23919 DAG.getConstant(0, dl, VecIdxTy));
23920 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23921 DAG.getConstant(1, dl, VecIdxTy));
23923 SDValue ShAmt = DAG.getConstant(
23924 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
23925 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
23926 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23927 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
23928 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
23929 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23930 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
23932 // Store the value to a temporary stack slot.
23933 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
23934 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
23935 MachinePointerInfo(), false, false, 0);
23937 EVT ElementType = InputVector.getValueType().getVectorElementType();
23938 unsigned EltSize = ElementType.getSizeInBits() / 8;
23940 // Replace each use (extract) with a load of the appropriate element.
23941 for (unsigned i = 0; i < 4; ++i) {
23942 uint64_t Offset = EltSize * i;
23943 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
23944 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
23946 SDValue ScalarAddr =
23947 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
23949 // Load the scalar.
23950 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
23951 ScalarAddr, MachinePointerInfo(),
23952 false, false, false, 0);
23957 // Replace the extracts
23958 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
23959 UE = Uses.end(); UI != UE; ++UI) {
23960 SDNode *Extract = *UI;
23962 SDValue Idx = Extract->getOperand(1);
23963 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
23964 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
23967 // The replacement was made in place; don't return anything.
23972 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
23973 const X86Subtarget *Subtarget) {
23975 SDValue Cond = N->getOperand(0);
23976 SDValue LHS = N->getOperand(1);
23977 SDValue RHS = N->getOperand(2);
23979 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
23980 SDValue CondSrc = Cond->getOperand(0);
23981 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
23982 Cond = CondSrc->getOperand(0);
23985 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
23988 // A vselect where all conditions and data are constants can be optimized into
23989 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23990 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23991 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23994 unsigned MaskValue = 0;
23995 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23998 MVT VT = N->getSimpleValueType(0);
23999 unsigned NumElems = VT.getVectorNumElements();
24000 SmallVector<int, 8> ShuffleMask(NumElems, -1);
24001 for (unsigned i = 0; i < NumElems; ++i) {
24002 // Be sure we emit undef where we can.
24003 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
24004 ShuffleMask[i] = -1;
24006 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
24009 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24010 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
24012 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
24015 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
24017 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
24018 TargetLowering::DAGCombinerInfo &DCI,
24019 const X86Subtarget *Subtarget) {
24021 SDValue Cond = N->getOperand(0);
24022 // Get the LHS/RHS of the select.
24023 SDValue LHS = N->getOperand(1);
24024 SDValue RHS = N->getOperand(2);
24025 EVT VT = LHS.getValueType();
24026 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24028 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
24029 // instructions match the semantics of the common C idiom x<y?x:y but not
24030 // x<=y?x:y, because of how they handle negative zero (which can be
24031 // ignored in unsafe-math mode).
24032 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
24033 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
24034 VT != MVT::f80 && VT != MVT::f128 &&
24035 (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
24036 (Subtarget->hasSSE2() ||
24037 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
24038 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24040 unsigned Opcode = 0;
24041 // Check for x CC y ? x : y.
24042 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24043 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24047 // Converting this to a min would handle NaNs incorrectly, and swapping
24048 // the operands would cause it to handle comparisons between positive
24049 // and negative zero incorrectly.
24050 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24051 if (!DAG.getTarget().Options.UnsafeFPMath &&
24052 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24054 std::swap(LHS, RHS);
24056 Opcode = X86ISD::FMIN;
24059 // Converting this to a min would handle comparisons between positive
24060 // and negative zero incorrectly.
24061 if (!DAG.getTarget().Options.UnsafeFPMath &&
24062 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24064 Opcode = X86ISD::FMIN;
24067 // Converting this to a min would handle both negative zeros and NaNs
24068 // incorrectly, but we can swap the operands to fix both.
24069 std::swap(LHS, RHS);
24073 Opcode = X86ISD::FMIN;
24077 // Converting this to a max would handle comparisons between positive
24078 // and negative zero incorrectly.
24079 if (!DAG.getTarget().Options.UnsafeFPMath &&
24080 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24082 Opcode = X86ISD::FMAX;
24085 // Converting this to a max would handle NaNs incorrectly, and swapping
24086 // the operands would cause it to handle comparisons between positive
24087 // and negative zero incorrectly.
24088 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24089 if (!DAG.getTarget().Options.UnsafeFPMath &&
24090 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24092 std::swap(LHS, RHS);
24094 Opcode = X86ISD::FMAX;
24097 // Converting this to a max would handle both negative zeros and NaNs
24098 // incorrectly, but we can swap the operands to fix both.
24099 std::swap(LHS, RHS);
24103 Opcode = X86ISD::FMAX;
24106 // Check for x CC y ? y : x -- a min/max with reversed arms.
24107 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
24108 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
24112 // Converting this to a min would handle comparisons between positive
24113 // and negative zero incorrectly, and swapping the operands would
24114 // cause it to handle NaNs incorrectly.
24115 if (!DAG.getTarget().Options.UnsafeFPMath &&
24116 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
24117 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24119 std::swap(LHS, RHS);
24121 Opcode = X86ISD::FMIN;
24124 // Converting this to a min would handle NaNs incorrectly.
24125 if (!DAG.getTarget().Options.UnsafeFPMath &&
24126 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
24128 Opcode = X86ISD::FMIN;
24131 // Converting this to a min would handle both negative zeros and NaNs
24132 // incorrectly, but we can swap the operands to fix both.
24133 std::swap(LHS, RHS);
24137 Opcode = X86ISD::FMIN;
24141 // Converting this to a max would handle NaNs incorrectly.
24142 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24144 Opcode = X86ISD::FMAX;
24147 // Converting this to a max would handle comparisons between positive
24148 // and negative zero incorrectly, and swapping the operands would
24149 // cause it to handle NaNs incorrectly.
24150 if (!DAG.getTarget().Options.UnsafeFPMath &&
24151 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
24152 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24154 std::swap(LHS, RHS);
24156 Opcode = X86ISD::FMAX;
24159 // Converting this to a max would handle both negative zeros and NaNs
24160 // incorrectly, but we can swap the operands to fix both.
24161 std::swap(LHS, RHS);
24165 Opcode = X86ISD::FMAX;
24171 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
24174 EVT CondVT = Cond.getValueType();
24175 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
24176 CondVT.getVectorElementType() == MVT::i1) {
24177 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
24178 // lowering on KNL. In this case we convert it to
24179 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
24180 // The same situation for all 128 and 256-bit vectors of i8 and i16.
24181 // Since SKX these selects have a proper lowering.
24182 EVT OpVT = LHS.getValueType();
24183 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
24184 (OpVT.getVectorElementType() == MVT::i8 ||
24185 OpVT.getVectorElementType() == MVT::i16) &&
24186 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
24187 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
24188 DCI.AddToWorklist(Cond.getNode());
24189 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
24192 // If this is a select between two integer constants, try to do some
24194 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
24195 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
24196 // Don't do this for crazy integer types.
24197 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
24198 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
24199 // so that TrueC (the true value) is larger than FalseC.
24200 bool NeedsCondInvert = false;
24202 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
24203 // Efficiently invertible.
24204 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
24205 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
24206 isa<ConstantSDNode>(Cond.getOperand(1))))) {
24207 NeedsCondInvert = true;
24208 std::swap(TrueC, FalseC);
24211 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
24212 if (FalseC->getAPIntValue() == 0 &&
24213 TrueC->getAPIntValue().isPowerOf2()) {
24214 if (NeedsCondInvert) // Invert the condition if needed.
24215 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24216 DAG.getConstant(1, DL, Cond.getValueType()));
24218 // Zero extend the condition if needed.
24219 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
24221 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24222 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
24223 DAG.getConstant(ShAmt, DL, MVT::i8));
24226 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
24227 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24228 if (NeedsCondInvert) // Invert the condition if needed.
24229 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24230 DAG.getConstant(1, DL, Cond.getValueType()));
24232 // Zero extend the condition if needed.
24233 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24234 FalseC->getValueType(0), Cond);
24235 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24236 SDValue(FalseC, 0));
24239 // Optimize cases that will turn into an LEA instruction. This requires
24240 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24241 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24242 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24243 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24245 bool isFastMultiplier = false;
24247 switch ((unsigned char)Diff) {
24249 case 1: // result = add base, cond
24250 case 2: // result = lea base( , cond*2)
24251 case 3: // result = lea base(cond, cond*2)
24252 case 4: // result = lea base( , cond*4)
24253 case 5: // result = lea base(cond, cond*4)
24254 case 8: // result = lea base( , cond*8)
24255 case 9: // result = lea base(cond, cond*8)
24256 isFastMultiplier = true;
24261 if (isFastMultiplier) {
24262 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24263 if (NeedsCondInvert) // Invert the condition if needed.
24264 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24265 DAG.getConstant(1, DL, Cond.getValueType()));
24267 // Zero extend the condition if needed.
24268 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24270 // Scale the condition by the difference.
24272 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24273 DAG.getConstant(Diff, DL,
24274 Cond.getValueType()));
24276 // Add the base if non-zero.
24277 if (FalseC->getAPIntValue() != 0)
24278 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24279 SDValue(FalseC, 0));
24286 // Canonicalize max and min:
24287 // (x > y) ? x : y -> (x >= y) ? x : y
24288 // (x < y) ? x : y -> (x <= y) ? x : y
24289 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
24290 // the need for an extra compare
24291 // against zero. e.g.
24292 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
24294 // testl %edi, %edi
24296 // cmovgl %edi, %eax
24300 // cmovsl %eax, %edi
24301 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
24302 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24303 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24304 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24309 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
24310 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
24311 Cond.getOperand(0), Cond.getOperand(1), NewCC);
24312 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
24317 // Early exit check
24318 if (!TLI.isTypeLegal(VT))
24321 // Match VSELECTs into subs with unsigned saturation.
24322 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
24323 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
24324 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
24325 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
24326 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24328 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
24329 // left side invert the predicate to simplify logic below.
24331 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
24333 CC = ISD::getSetCCInverse(CC, true);
24334 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
24338 if (Other.getNode() && Other->getNumOperands() == 2 &&
24339 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
24340 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
24341 SDValue CondRHS = Cond->getOperand(1);
24343 // Look for a general sub with unsigned saturation first.
24344 // x >= y ? x-y : 0 --> subus x, y
24345 // x > y ? x-y : 0 --> subus x, y
24346 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
24347 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
24348 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
24350 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
24351 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
24352 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
24353 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
24354 // If the RHS is a constant we have to reverse the const
24355 // canonicalization.
24356 // x > C-1 ? x+-C : 0 --> subus x, C
24357 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
24358 CondRHSConst->getAPIntValue() ==
24359 (-OpRHSConst->getAPIntValue() - 1))
24360 return DAG.getNode(
24361 X86ISD::SUBUS, DL, VT, OpLHS,
24362 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
24364 // Another special case: If C was a sign bit, the sub has been
24365 // canonicalized into a xor.
24366 // FIXME: Would it be better to use computeKnownBits to determine
24367 // whether it's safe to decanonicalize the xor?
24368 // x s< 0 ? x^C : 0 --> subus x, C
24369 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
24370 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
24371 OpRHSConst->getAPIntValue().isSignBit())
24372 // Note that we have to rebuild the RHS constant here to ensure we
24373 // don't rely on particular values of undef lanes.
24374 return DAG.getNode(
24375 X86ISD::SUBUS, DL, VT, OpLHS,
24376 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
24381 // Simplify vector selection if condition value type matches vselect
24383 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
24384 assert(Cond.getValueType().isVector() &&
24385 "vector select expects a vector selector!");
24387 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
24388 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
24390 // Try invert the condition if true value is not all 1s and false value
24392 if (!TValIsAllOnes && !FValIsAllZeros &&
24393 // Check if the selector will be produced by CMPP*/PCMP*
24394 Cond.getOpcode() == ISD::SETCC &&
24395 // Check if SETCC has already been promoted
24396 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
24398 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
24399 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
24401 if (TValIsAllZeros || FValIsAllOnes) {
24402 SDValue CC = Cond.getOperand(2);
24403 ISD::CondCode NewCC =
24404 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
24405 Cond.getOperand(0).getValueType().isInteger());
24406 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
24407 std::swap(LHS, RHS);
24408 TValIsAllOnes = FValIsAllOnes;
24409 FValIsAllZeros = TValIsAllZeros;
24413 if (TValIsAllOnes || FValIsAllZeros) {
24416 if (TValIsAllOnes && FValIsAllZeros)
24418 else if (TValIsAllOnes)
24420 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
24421 else if (FValIsAllZeros)
24422 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
24423 DAG.getBitcast(CondVT, LHS));
24425 return DAG.getBitcast(VT, Ret);
24429 // We should generate an X86ISD::BLENDI from a vselect if its argument
24430 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
24431 // constants. This specific pattern gets generated when we split a
24432 // selector for a 512 bit vector in a machine without AVX512 (but with
24433 // 256-bit vectors), during legalization:
24435 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
24437 // Iff we find this pattern and the build_vectors are built from
24438 // constants, we translate the vselect into a shuffle_vector that we
24439 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
24440 if ((N->getOpcode() == ISD::VSELECT ||
24441 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
24442 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
24443 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
24444 if (Shuffle.getNode())
24448 // If this is a *dynamic* select (non-constant condition) and we can match
24449 // this node with one of the variable blend instructions, restructure the
24450 // condition so that the blends can use the high bit of each element and use
24451 // SimplifyDemandedBits to simplify the condition operand.
24452 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
24453 !DCI.isBeforeLegalize() &&
24454 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
24455 unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
24457 // Don't optimize vector selects that map to mask-registers.
24461 // We can only handle the cases where VSELECT is directly legal on the
24462 // subtarget. We custom lower VSELECT nodes with constant conditions and
24463 // this makes it hard to see whether a dynamic VSELECT will correctly
24464 // lower, so we both check the operation's status and explicitly handle the
24465 // cases where a *dynamic* blend will fail even though a constant-condition
24466 // blend could be custom lowered.
24467 // FIXME: We should find a better way to handle this class of problems.
24468 // Potentially, we should combine constant-condition vselect nodes
24469 // pre-legalization into shuffles and not mark as many types as custom
24471 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
24473 // FIXME: We don't support i16-element blends currently. We could and
24474 // should support them by making *all* the bits in the condition be set
24475 // rather than just the high bit and using an i8-element blend.
24476 if (VT.getVectorElementType() == MVT::i16)
24478 // Dynamic blending was only available from SSE4.1 onward.
24479 if (VT.is128BitVector() && !Subtarget->hasSSE41())
24481 // Byte blends are only available in AVX2
24482 if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
24485 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
24486 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
24488 APInt KnownZero, KnownOne;
24489 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
24490 DCI.isBeforeLegalizeOps());
24491 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
24492 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
24494 // If we changed the computation somewhere in the DAG, this change
24495 // will affect all users of Cond.
24496 // Make sure it is fine and update all the nodes so that we do not
24497 // use the generic VSELECT anymore. Otherwise, we may perform
24498 // wrong optimizations as we messed up with the actual expectation
24499 // for the vector boolean values.
24500 if (Cond != TLO.Old) {
24501 // Check all uses of that condition operand to check whether it will be
24502 // consumed by non-BLEND instructions, which may depend on all bits are
24504 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24506 if (I->getOpcode() != ISD::VSELECT)
24507 // TODO: Add other opcodes eventually lowered into BLEND.
24510 // Update all the users of the condition, before committing the change,
24511 // so that the VSELECT optimizations that expect the correct vector
24512 // boolean value will not be triggered.
24513 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24515 DAG.ReplaceAllUsesOfValueWith(
24517 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
24518 Cond, I->getOperand(1), I->getOperand(2)));
24519 DCI.CommitTargetLoweringOpt(TLO);
24522 // At this point, only Cond is changed. Change the condition
24523 // just for N to keep the opportunity to optimize all other
24524 // users their own way.
24525 DAG.ReplaceAllUsesOfValueWith(
24527 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
24528 TLO.New, N->getOperand(1), N->getOperand(2)));
24536 // Check whether a boolean test is testing a boolean value generated by
24537 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
24540 // Simplify the following patterns:
24541 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
24542 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
24543 // to (Op EFLAGS Cond)
24545 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
24546 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
24547 // to (Op EFLAGS !Cond)
24549 // where Op could be BRCOND or CMOV.
24551 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
24552 // Quit if not CMP and SUB with its value result used.
24553 if (Cmp.getOpcode() != X86ISD::CMP &&
24554 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
24557 // Quit if not used as a boolean value.
24558 if (CC != X86::COND_E && CC != X86::COND_NE)
24561 // Check CMP operands. One of them should be 0 or 1 and the other should be
24562 // an SetCC or extended from it.
24563 SDValue Op1 = Cmp.getOperand(0);
24564 SDValue Op2 = Cmp.getOperand(1);
24567 const ConstantSDNode* C = nullptr;
24568 bool needOppositeCond = (CC == X86::COND_E);
24569 bool checkAgainstTrue = false; // Is it a comparison against 1?
24571 if ((C = dyn_cast<ConstantSDNode>(Op1)))
24573 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
24575 else // Quit if all operands are not constants.
24578 if (C->getZExtValue() == 1) {
24579 needOppositeCond = !needOppositeCond;
24580 checkAgainstTrue = true;
24581 } else if (C->getZExtValue() != 0)
24582 // Quit if the constant is neither 0 or 1.
24585 bool truncatedToBoolWithAnd = false;
24586 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24587 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24588 SetCC.getOpcode() == ISD::TRUNCATE ||
24589 SetCC.getOpcode() == ISD::AND) {
24590 if (SetCC.getOpcode() == ISD::AND) {
24592 if (isOneConstant(SetCC.getOperand(0)))
24594 if (isOneConstant(SetCC.getOperand(1)))
24598 SetCC = SetCC.getOperand(OpIdx);
24599 truncatedToBoolWithAnd = true;
24601 SetCC = SetCC.getOperand(0);
24604 switch (SetCC.getOpcode()) {
24605 case X86ISD::SETCC_CARRY:
24606 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24607 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24608 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24609 // truncated to i1 using 'and'.
24610 if (checkAgainstTrue && !truncatedToBoolWithAnd)
24612 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24613 "Invalid use of SETCC_CARRY!");
24615 case X86ISD::SETCC:
24616 // Set the condition code or opposite one if necessary.
24617 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24618 if (needOppositeCond)
24619 CC = X86::GetOppositeBranchCondition(CC);
24620 return SetCC.getOperand(1);
24621 case X86ISD::CMOV: {
24622 // Check whether false/true value has canonical one, i.e. 0 or 1.
24623 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24624 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24625 // Quit if true value is not a constant.
24628 // Quit if false value is not a constant.
24630 SDValue Op = SetCC.getOperand(0);
24631 // Skip 'zext' or 'trunc' node.
24632 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24633 Op.getOpcode() == ISD::TRUNCATE)
24634 Op = Op.getOperand(0);
24635 // A special case for rdrand/rdseed, where 0 is set if false cond is
24637 if ((Op.getOpcode() != X86ISD::RDRAND &&
24638 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24641 // Quit if false value is not the constant 0 or 1.
24642 bool FValIsFalse = true;
24643 if (FVal && FVal->getZExtValue() != 0) {
24644 if (FVal->getZExtValue() != 1)
24646 // If FVal is 1, opposite cond is needed.
24647 needOppositeCond = !needOppositeCond;
24648 FValIsFalse = false;
24650 // Quit if TVal is not the constant opposite of FVal.
24651 if (FValIsFalse && TVal->getZExtValue() != 1)
24653 if (!FValIsFalse && TVal->getZExtValue() != 0)
24655 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24656 if (needOppositeCond)
24657 CC = X86::GetOppositeBranchCondition(CC);
24658 return SetCC.getOperand(3);
24665 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24667 /// (X86or (X86setcc) (X86setcc))
24668 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
24669 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24670 X86::CondCode &CC1, SDValue &Flags,
24672 if (Cond->getOpcode() == X86ISD::CMP) {
24673 if (!isNullConstant(Cond->getOperand(1)))
24676 Cond = Cond->getOperand(0);
24681 SDValue SetCC0, SetCC1;
24682 switch (Cond->getOpcode()) {
24683 default: return false;
24690 SetCC0 = Cond->getOperand(0);
24691 SetCC1 = Cond->getOperand(1);
24695 // Make sure we have SETCC nodes, using the same flags value.
24696 if (SetCC0.getOpcode() != X86ISD::SETCC ||
24697 SetCC1.getOpcode() != X86ISD::SETCC ||
24698 SetCC0->getOperand(1) != SetCC1->getOperand(1))
24701 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24702 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24703 Flags = SetCC0->getOperand(1);
24707 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24708 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24709 TargetLowering::DAGCombinerInfo &DCI,
24710 const X86Subtarget *Subtarget) {
24713 // If the flag operand isn't dead, don't touch this CMOV.
24714 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24717 SDValue FalseOp = N->getOperand(0);
24718 SDValue TrueOp = N->getOperand(1);
24719 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24720 SDValue Cond = N->getOperand(3);
24722 if (CC == X86::COND_E || CC == X86::COND_NE) {
24723 switch (Cond.getOpcode()) {
24727 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24728 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24729 return (CC == X86::COND_E) ? FalseOp : TrueOp;
24735 Flags = checkBoolTestSetCCCombine(Cond, CC);
24736 if (Flags.getNode() &&
24737 // Extra check as FCMOV only supports a subset of X86 cond.
24738 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
24739 SDValue Ops[] = { FalseOp, TrueOp,
24740 DAG.getConstant(CC, DL, MVT::i8), Flags };
24741 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24744 // If this is a select between two integer constants, try to do some
24745 // optimizations. Note that the operands are ordered the opposite of SELECT
24747 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
24748 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
24749 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
24750 // larger than FalseC (the false value).
24751 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
24752 CC = X86::GetOppositeBranchCondition(CC);
24753 std::swap(TrueC, FalseC);
24754 std::swap(TrueOp, FalseOp);
24757 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
24758 // This is efficient for any integer data type (including i8/i16) and
24760 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24761 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24762 DAG.getConstant(CC, DL, MVT::i8), Cond);
24764 // Zero extend the condition if needed.
24765 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24767 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24768 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24769 DAG.getConstant(ShAmt, DL, MVT::i8));
24770 if (N->getNumValues() == 2) // Dead flag value?
24771 return DCI.CombineTo(N, Cond, SDValue());
24775 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
24776 // for any integer data type, including i8/i16.
24777 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24778 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24779 DAG.getConstant(CC, DL, MVT::i8), Cond);
24781 // Zero extend the condition if needed.
24782 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24783 FalseC->getValueType(0), Cond);
24784 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24785 SDValue(FalseC, 0));
24787 if (N->getNumValues() == 2) // Dead flag value?
24788 return DCI.CombineTo(N, Cond, SDValue());
24792 // Optimize cases that will turn into an LEA instruction. This requires
24793 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24794 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24795 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24796 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24798 bool isFastMultiplier = false;
24800 switch ((unsigned char)Diff) {
24802 case 1: // result = add base, cond
24803 case 2: // result = lea base( , cond*2)
24804 case 3: // result = lea base(cond, cond*2)
24805 case 4: // result = lea base( , cond*4)
24806 case 5: // result = lea base(cond, cond*4)
24807 case 8: // result = lea base( , cond*8)
24808 case 9: // result = lea base(cond, cond*8)
24809 isFastMultiplier = true;
24814 if (isFastMultiplier) {
24815 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24816 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24817 DAG.getConstant(CC, DL, MVT::i8), Cond);
24818 // Zero extend the condition if needed.
24819 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24821 // Scale the condition by the difference.
24823 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24824 DAG.getConstant(Diff, DL, Cond.getValueType()));
24826 // Add the base if non-zero.
24827 if (FalseC->getAPIntValue() != 0)
24828 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24829 SDValue(FalseC, 0));
24830 if (N->getNumValues() == 2) // Dead flag value?
24831 return DCI.CombineTo(N, Cond, SDValue());
24838 // Handle these cases:
24839 // (select (x != c), e, c) -> select (x != c), e, x),
24840 // (select (x == c), c, e) -> select (x == c), x, e)
24841 // where the c is an integer constant, and the "select" is the combination
24842 // of CMOV and CMP.
24844 // The rationale for this change is that the conditional-move from a constant
24845 // needs two instructions, however, conditional-move from a register needs
24846 // only one instruction.
24848 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
24849 // some instruction-combining opportunities. This opt needs to be
24850 // postponed as late as possible.
24852 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
24853 // the DCI.xxxx conditions are provided to postpone the optimization as
24854 // late as possible.
24856 ConstantSDNode *CmpAgainst = nullptr;
24857 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
24858 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
24859 !isa<ConstantSDNode>(Cond.getOperand(0))) {
24861 if (CC == X86::COND_NE &&
24862 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
24863 CC = X86::GetOppositeBranchCondition(CC);
24864 std::swap(TrueOp, FalseOp);
24867 if (CC == X86::COND_E &&
24868 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
24869 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
24870 DAG.getConstant(CC, DL, MVT::i8), Cond };
24871 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
24876 // Fold and/or of setcc's to double CMOV:
24877 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
24878 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
24880 // This combine lets us generate:
24881 // cmovcc1 (jcc1 if we don't have CMOV)
24887 // cmovne (jne if we don't have CMOV)
24888 // When we can't use the CMOV instruction, it might increase branch
24890 // When we can use CMOV, or when there is no mispredict, this improves
24891 // throughput and reduces register pressure.
24893 if (CC == X86::COND_NE) {
24895 X86::CondCode CC0, CC1;
24897 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
24899 std::swap(FalseOp, TrueOp);
24900 CC0 = X86::GetOppositeBranchCondition(CC0);
24901 CC1 = X86::GetOppositeBranchCondition(CC1);
24904 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
24906 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
24907 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
24908 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24909 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
24917 /// PerformMulCombine - Optimize a single multiply with constant into two
24918 /// in order to implement it with two cheaper instructions, e.g.
24919 /// LEA + SHL, LEA + LEA.
24920 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
24921 TargetLowering::DAGCombinerInfo &DCI) {
24922 // An imul is usually smaller than the alternative sequence.
24923 if (DAG.getMachineFunction().getFunction()->optForMinSize())
24926 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
24929 EVT VT = N->getValueType(0);
24930 if (VT != MVT::i64 && VT != MVT::i32)
24933 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
24936 uint64_t MulAmt = C->getZExtValue();
24937 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
24940 uint64_t MulAmt1 = 0;
24941 uint64_t MulAmt2 = 0;
24942 if ((MulAmt % 9) == 0) {
24944 MulAmt2 = MulAmt / 9;
24945 } else if ((MulAmt % 5) == 0) {
24947 MulAmt2 = MulAmt / 5;
24948 } else if ((MulAmt % 3) == 0) {
24950 MulAmt2 = MulAmt / 3;
24956 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
24958 if (isPowerOf2_64(MulAmt2) &&
24959 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
24960 // If second multiplifer is pow2, issue it first. We want the multiply by
24961 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
24963 std::swap(MulAmt1, MulAmt2);
24965 if (isPowerOf2_64(MulAmt1))
24966 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
24967 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
24969 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
24970 DAG.getConstant(MulAmt1, DL, VT));
24972 if (isPowerOf2_64(MulAmt2))
24973 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
24974 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
24976 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
24977 DAG.getConstant(MulAmt2, DL, VT));
24981 assert(MulAmt != 0 && MulAmt != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX)
24982 && "Both cases that could cause potential overflows should have "
24983 "already been handled.");
24984 if (isPowerOf2_64(MulAmt - 1))
24985 // (mul x, 2^N + 1) => (add (shl x, N), x)
24986 NewMul = DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
24987 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
24988 DAG.getConstant(Log2_64(MulAmt - 1), DL,
24991 else if (isPowerOf2_64(MulAmt + 1))
24992 // (mul x, 2^N - 1) => (sub (shl x, N), x)
24993 NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getNode(ISD::SHL, DL, VT,
24995 DAG.getConstant(Log2_64(MulAmt + 1),
24996 DL, MVT::i8)), N->getOperand(0));
25000 // Do not add new nodes to DAG combiner worklist.
25001 DCI.CombineTo(N, NewMul, false);
25006 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
25007 SDValue N0 = N->getOperand(0);
25008 SDValue N1 = N->getOperand(1);
25009 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
25010 EVT VT = N0.getValueType();
25012 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
25013 // since the result of setcc_c is all zero's or all ones.
25014 if (VT.isInteger() && !VT.isVector() &&
25015 N1C && N0.getOpcode() == ISD::AND &&
25016 N0.getOperand(1).getOpcode() == ISD::Constant) {
25017 SDValue N00 = N0.getOperand(0);
25018 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
25019 APInt ShAmt = N1C->getAPIntValue();
25020 Mask = Mask.shl(ShAmt);
25021 bool MaskOK = false;
25022 // We can handle cases concerning bit-widening nodes containing setcc_c if
25023 // we carefully interrogate the mask to make sure we are semantics
25025 // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
25026 // of the underlying setcc_c operation if the setcc_c was zero extended.
25027 // Consider the following example:
25028 // zext(setcc_c) -> i32 0x0000FFFF
25029 // c1 -> i32 0x0000FFFF
25030 // c2 -> i32 0x00000001
25031 // (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
25032 // (and setcc_c, (c1 << c2)) -> i32 0x0000FFFE
25033 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25035 } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
25036 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25038 } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
25039 N00.getOpcode() == ISD::ANY_EXTEND) &&
25040 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25041 MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
25043 if (MaskOK && Mask != 0) {
25045 return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
25049 // Hardware support for vector shifts is sparse which makes us scalarize the
25050 // vector operations in many cases. Also, on sandybridge ADD is faster than
25052 // (shl V, 1) -> add V,V
25053 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
25054 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
25055 assert(N0.getValueType().isVector() && "Invalid vector shift type");
25056 // We shift all of the values by one. In many cases we do not have
25057 // hardware support for this operation. This is better expressed as an ADD
25059 if (N1SplatC->getAPIntValue() == 1)
25060 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
25066 static SDValue PerformSRACombine(SDNode *N, SelectionDAG &DAG) {
25067 SDValue N0 = N->getOperand(0);
25068 SDValue N1 = N->getOperand(1);
25069 EVT VT = N0.getValueType();
25070 unsigned Size = VT.getSizeInBits();
25072 // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
25073 // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
25074 // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
25075 // depending on sign of (SarConst - [56,48,32,24,16])
25077 // sexts in X86 are MOVs. The MOVs have the same code size
25078 // as above SHIFTs (only SHIFT on 1 has lower code size).
25079 // However the MOVs have 2 advantages to a SHIFT:
25080 // 1. MOVs can write to a register that differs from source
25081 // 2. MOVs accept memory operands
25083 if (!VT.isInteger() || VT.isVector() || N1.getOpcode() != ISD::Constant ||
25084 N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
25085 N0.getOperand(1).getOpcode() != ISD::Constant)
25088 SDValue N00 = N0.getOperand(0);
25089 SDValue N01 = N0.getOperand(1);
25090 APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
25091 APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
25092 EVT CVT = N1.getValueType();
25094 if (SarConst.isNegative())
25097 for (MVT SVT : MVT::integer_valuetypes()) {
25098 unsigned ShiftSize = SVT.getSizeInBits();
25099 // skipping types without corresponding sext/zext and
25100 // ShlConst that is not one of [56,48,32,24,16]
25101 if (ShiftSize < 8 || ShiftSize > 64 || ShlConst != Size - ShiftSize)
25105 DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
25106 SarConst = SarConst - (Size - ShiftSize);
25109 else if (SarConst.isNegative())
25110 return DAG.getNode(ISD::SHL, DL, VT, NN,
25111 DAG.getConstant(-SarConst, DL, CVT));
25113 return DAG.getNode(ISD::SRA, DL, VT, NN,
25114 DAG.getConstant(SarConst, DL, CVT));
25119 /// \brief Returns a vector of 0s if the node in input is a vector logical
25120 /// shift by a constant amount which is known to be bigger than or equal
25121 /// to the vector element size in bits.
25122 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
25123 const X86Subtarget *Subtarget) {
25124 EVT VT = N->getValueType(0);
25126 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
25127 (!Subtarget->hasInt256() ||
25128 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
25131 SDValue Amt = N->getOperand(1);
25133 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
25134 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
25135 APInt ShiftAmt = AmtSplat->getAPIntValue();
25136 unsigned MaxAmount =
25137 VT.getSimpleVT().getVectorElementType().getSizeInBits();
25139 // SSE2/AVX2 logical shifts always return a vector of 0s
25140 // if the shift amount is bigger than or equal to
25141 // the element size. The constant shift amount will be
25142 // encoded as a 8-bit immediate.
25143 if (ShiftAmt.trunc(8).uge(MaxAmount))
25144 return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, DL);
25150 /// PerformShiftCombine - Combine shifts.
25151 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
25152 TargetLowering::DAGCombinerInfo &DCI,
25153 const X86Subtarget *Subtarget) {
25154 if (N->getOpcode() == ISD::SHL)
25155 if (SDValue V = PerformSHLCombine(N, DAG))
25158 if (N->getOpcode() == ISD::SRA)
25159 if (SDValue V = PerformSRACombine(N, DAG))
25162 // Try to fold this logical shift into a zero vector.
25163 if (N->getOpcode() != ISD::SRA)
25164 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
25170 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
25171 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
25172 // and friends. Likewise for OR -> CMPNEQSS.
25173 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
25174 TargetLowering::DAGCombinerInfo &DCI,
25175 const X86Subtarget *Subtarget) {
25178 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
25179 // we're requiring SSE2 for both.
25180 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
25181 SDValue N0 = N->getOperand(0);
25182 SDValue N1 = N->getOperand(1);
25183 SDValue CMP0 = N0->getOperand(1);
25184 SDValue CMP1 = N1->getOperand(1);
25187 // The SETCCs should both refer to the same CMP.
25188 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
25191 SDValue CMP00 = CMP0->getOperand(0);
25192 SDValue CMP01 = CMP0->getOperand(1);
25193 EVT VT = CMP00.getValueType();
25195 if (VT == MVT::f32 || VT == MVT::f64) {
25196 bool ExpectingFlags = false;
25197 // Check for any users that want flags:
25198 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
25199 !ExpectingFlags && UI != UE; ++UI)
25200 switch (UI->getOpcode()) {
25205 ExpectingFlags = true;
25207 case ISD::CopyToReg:
25208 case ISD::SIGN_EXTEND:
25209 case ISD::ZERO_EXTEND:
25210 case ISD::ANY_EXTEND:
25214 if (!ExpectingFlags) {
25215 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
25216 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
25218 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
25219 X86::CondCode tmp = cc0;
25224 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
25225 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
25226 // FIXME: need symbolic constants for these magic numbers.
25227 // See X86ATTInstPrinter.cpp:printSSECC().
25228 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
25229 if (Subtarget->hasAVX512()) {
25230 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
25232 DAG.getConstant(x86cc, DL, MVT::i8));
25233 if (N->getValueType(0) != MVT::i1)
25234 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
25238 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
25239 CMP00.getValueType(), CMP00, CMP01,
25240 DAG.getConstant(x86cc, DL,
25243 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
25244 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
25246 if (is64BitFP && !Subtarget->is64Bit()) {
25247 // On a 32-bit target, we cannot bitcast the 64-bit float to a
25248 // 64-bit integer, since that's not a legal type. Since
25249 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
25250 // bits, but can do this little dance to extract the lowest 32 bits
25251 // and work with those going forward.
25252 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
25254 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
25255 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
25256 Vector32, DAG.getIntPtrConstant(0, DL));
25260 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
25261 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
25262 DAG.getConstant(1, DL, IntVT));
25263 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
25265 return OneBitOfTruth;
25273 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
25274 /// so it can be folded inside ANDNP.
25275 static bool CanFoldXORWithAllOnes(const SDNode *N) {
25276 EVT VT = N->getValueType(0);
25278 // Match direct AllOnes for 128 and 256-bit vectors
25279 if (ISD::isBuildVectorAllOnes(N))
25282 // Look through a bit convert.
25283 if (N->getOpcode() == ISD::BITCAST)
25284 N = N->getOperand(0).getNode();
25286 // Sometimes the operand may come from a insert_subvector building a 256-bit
25288 if (VT.is256BitVector() &&
25289 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
25290 SDValue V1 = N->getOperand(0);
25291 SDValue V2 = N->getOperand(1);
25293 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
25294 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
25295 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
25296 ISD::isBuildVectorAllOnes(V2.getNode()))
25303 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
25304 // register. In most cases we actually compare or select YMM-sized registers
25305 // and mixing the two types creates horrible code. This method optimizes
25306 // some of the transition sequences.
25307 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
25308 TargetLowering::DAGCombinerInfo &DCI,
25309 const X86Subtarget *Subtarget) {
25310 EVT VT = N->getValueType(0);
25311 if (!VT.is256BitVector())
25314 assert((N->getOpcode() == ISD::ANY_EXTEND ||
25315 N->getOpcode() == ISD::ZERO_EXTEND ||
25316 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
25318 SDValue Narrow = N->getOperand(0);
25319 EVT NarrowVT = Narrow->getValueType(0);
25320 if (!NarrowVT.is128BitVector())
25323 if (Narrow->getOpcode() != ISD::XOR &&
25324 Narrow->getOpcode() != ISD::AND &&
25325 Narrow->getOpcode() != ISD::OR)
25328 SDValue N0 = Narrow->getOperand(0);
25329 SDValue N1 = Narrow->getOperand(1);
25332 // The Left side has to be a trunc.
25333 if (N0.getOpcode() != ISD::TRUNCATE)
25336 // The type of the truncated inputs.
25337 EVT WideVT = N0->getOperand(0)->getValueType(0);
25341 // The right side has to be a 'trunc' or a constant vector.
25342 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
25343 ConstantSDNode *RHSConstSplat = nullptr;
25344 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
25345 RHSConstSplat = RHSBV->getConstantSplatNode();
25346 if (!RHSTrunc && !RHSConstSplat)
25349 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25351 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
25354 // Set N0 and N1 to hold the inputs to the new wide operation.
25355 N0 = N0->getOperand(0);
25356 if (RHSConstSplat) {
25357 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
25358 SDValue(RHSConstSplat, 0));
25359 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
25360 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
25361 } else if (RHSTrunc) {
25362 N1 = N1->getOperand(0);
25365 // Generate the wide operation.
25366 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
25367 unsigned Opcode = N->getOpcode();
25369 case ISD::ANY_EXTEND:
25371 case ISD::ZERO_EXTEND: {
25372 unsigned InBits = NarrowVT.getScalarSizeInBits();
25373 APInt Mask = APInt::getAllOnesValue(InBits);
25374 Mask = Mask.zext(VT.getScalarSizeInBits());
25375 return DAG.getNode(ISD::AND, DL, VT,
25376 Op, DAG.getConstant(Mask, DL, VT));
25378 case ISD::SIGN_EXTEND:
25379 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
25380 Op, DAG.getValueType(NarrowVT));
25382 llvm_unreachable("Unexpected opcode");
25386 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
25387 TargetLowering::DAGCombinerInfo &DCI,
25388 const X86Subtarget *Subtarget) {
25389 SDValue N0 = N->getOperand(0);
25390 SDValue N1 = N->getOperand(1);
25393 // A vector zext_in_reg may be represented as a shuffle,
25394 // feeding into a bitcast (this represents anyext) feeding into
25395 // an and with a mask.
25396 // We'd like to try to combine that into a shuffle with zero
25397 // plus a bitcast, removing the and.
25398 if (N0.getOpcode() != ISD::BITCAST ||
25399 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
25402 // The other side of the AND should be a splat of 2^C, where C
25403 // is the number of bits in the source type.
25404 if (N1.getOpcode() == ISD::BITCAST)
25405 N1 = N1.getOperand(0);
25406 if (N1.getOpcode() != ISD::BUILD_VECTOR)
25408 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
25410 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
25411 EVT SrcType = Shuffle->getValueType(0);
25413 // We expect a single-source shuffle
25414 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
25417 unsigned SrcSize = SrcType.getScalarSizeInBits();
25419 APInt SplatValue, SplatUndef;
25420 unsigned SplatBitSize;
25422 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
25423 SplatBitSize, HasAnyUndefs))
25426 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
25427 // Make sure the splat matches the mask we expect
25428 if (SplatBitSize > ResSize ||
25429 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
25432 // Make sure the input and output size make sense
25433 if (SrcSize >= ResSize || ResSize % SrcSize)
25436 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
25437 // The number of u's between each two values depends on the ratio between
25438 // the source and dest type.
25439 unsigned ZextRatio = ResSize / SrcSize;
25440 bool IsZext = true;
25441 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
25442 if (i % ZextRatio) {
25443 if (Shuffle->getMaskElt(i) > 0) {
25449 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
25450 // Expected element number
25460 // Ok, perform the transformation - replace the shuffle with
25461 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
25462 // (instead of undef) where the k elements come from the zero vector.
25463 SmallVector<int, 8> Mask;
25464 unsigned NumElems = SrcType.getVectorNumElements();
25465 for (unsigned i = 0; i < NumElems; ++i)
25467 Mask.push_back(NumElems);
25469 Mask.push_back(i / ZextRatio);
25471 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
25472 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
25473 return DAG.getBitcast(N0.getValueType(), NewShuffle);
25476 /// If both input operands of a logic op are being cast from floating point
25477 /// types, try to convert this into a floating point logic node to avoid
25478 /// unnecessary moves from SSE to integer registers.
25479 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
25480 const X86Subtarget *Subtarget) {
25481 unsigned FPOpcode = ISD::DELETED_NODE;
25482 if (N->getOpcode() == ISD::AND)
25483 FPOpcode = X86ISD::FAND;
25484 else if (N->getOpcode() == ISD::OR)
25485 FPOpcode = X86ISD::FOR;
25486 else if (N->getOpcode() == ISD::XOR)
25487 FPOpcode = X86ISD::FXOR;
25489 assert(FPOpcode != ISD::DELETED_NODE &&
25490 "Unexpected input node for FP logic conversion");
25492 EVT VT = N->getValueType(0);
25493 SDValue N0 = N->getOperand(0);
25494 SDValue N1 = N->getOperand(1);
25496 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
25497 ((Subtarget->hasSSE1() && VT == MVT::i32) ||
25498 (Subtarget->hasSSE2() && VT == MVT::i64))) {
25499 SDValue N00 = N0.getOperand(0);
25500 SDValue N10 = N1.getOperand(0);
25501 EVT N00Type = N00.getValueType();
25502 EVT N10Type = N10.getValueType();
25503 if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
25504 SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
25505 return DAG.getBitcast(VT, FPLogic);
25511 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
25512 TargetLowering::DAGCombinerInfo &DCI,
25513 const X86Subtarget *Subtarget) {
25514 if (DCI.isBeforeLegalizeOps())
25517 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
25520 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25523 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25526 EVT VT = N->getValueType(0);
25527 SDValue N0 = N->getOperand(0);
25528 SDValue N1 = N->getOperand(1);
25531 // Create BEXTR instructions
25532 // BEXTR is ((X >> imm) & (2**size-1))
25533 if (VT == MVT::i32 || VT == MVT::i64) {
25534 // Check for BEXTR.
25535 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
25536 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
25537 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
25538 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25539 if (MaskNode && ShiftNode) {
25540 uint64_t Mask = MaskNode->getZExtValue();
25541 uint64_t Shift = ShiftNode->getZExtValue();
25542 if (isMask_64(Mask)) {
25543 uint64_t MaskSize = countPopulation(Mask);
25544 if (Shift + MaskSize <= VT.getSizeInBits())
25545 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
25546 DAG.getConstant(Shift | (MaskSize << 8), DL,
25555 // Want to form ANDNP nodes:
25556 // 1) In the hopes of then easily combining them with OR and AND nodes
25557 // to form PBLEND/PSIGN.
25558 // 2) To match ANDN packed intrinsics
25559 if (VT != MVT::v2i64 && VT != MVT::v4i64)
25562 // Check LHS for vnot
25563 if (N0.getOpcode() == ISD::XOR &&
25564 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
25565 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
25566 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
25568 // Check RHS for vnot
25569 if (N1.getOpcode() == ISD::XOR &&
25570 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
25571 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
25572 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
25577 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
25578 TargetLowering::DAGCombinerInfo &DCI,
25579 const X86Subtarget *Subtarget) {
25580 if (DCI.isBeforeLegalizeOps())
25583 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25586 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25589 SDValue N0 = N->getOperand(0);
25590 SDValue N1 = N->getOperand(1);
25591 EVT VT = N->getValueType(0);
25593 // look for psign/blend
25594 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
25595 if (!Subtarget->hasSSSE3() ||
25596 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
25599 // Canonicalize pandn to RHS
25600 if (N0.getOpcode() == X86ISD::ANDNP)
25602 // or (and (m, y), (pandn m, x))
25603 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
25604 SDValue Mask = N1.getOperand(0);
25605 SDValue X = N1.getOperand(1);
25607 if (N0.getOperand(0) == Mask)
25608 Y = N0.getOperand(1);
25609 if (N0.getOperand(1) == Mask)
25610 Y = N0.getOperand(0);
25612 // Check to see if the mask appeared in both the AND and ANDNP and
25616 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
25617 // Look through mask bitcast.
25618 if (Mask.getOpcode() == ISD::BITCAST)
25619 Mask = Mask.getOperand(0);
25620 if (X.getOpcode() == ISD::BITCAST)
25621 X = X.getOperand(0);
25622 if (Y.getOpcode() == ISD::BITCAST)
25623 Y = Y.getOperand(0);
25625 EVT MaskVT = Mask.getValueType();
25627 // Validate that the Mask operand is a vector sra node.
25628 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
25629 // there is no psrai.b
25630 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
25631 unsigned SraAmt = ~0;
25632 if (Mask.getOpcode() == ISD::SRA) {
25633 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
25634 if (auto *AmtConst = AmtBV->getConstantSplatNode())
25635 SraAmt = AmtConst->getZExtValue();
25636 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
25637 SDValue SraC = Mask.getOperand(1);
25638 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
25640 if ((SraAmt + 1) != EltBits)
25645 // Now we know we at least have a plendvb with the mask val. See if
25646 // we can form a psignb/w/d.
25647 // psign = x.type == y.type == mask.type && y = sub(0, x);
25648 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
25649 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
25650 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
25651 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
25652 "Unsupported VT for PSIGN");
25653 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
25654 return DAG.getBitcast(VT, Mask);
25656 // PBLENDVB only available on SSE 4.1
25657 if (!Subtarget->hasSSE41())
25660 MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25662 X = DAG.getBitcast(BlendVT, X);
25663 Y = DAG.getBitcast(BlendVT, Y);
25664 Mask = DAG.getBitcast(BlendVT, Mask);
25665 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25666 return DAG.getBitcast(VT, Mask);
25670 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25673 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25674 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25676 // SHLD/SHRD instructions have lower register pressure, but on some
25677 // platforms they have higher latency than the equivalent
25678 // series of shifts/or that would otherwise be generated.
25679 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25680 // have higher latencies and we are not optimizing for size.
25681 if (!OptForSize && Subtarget->isSHLDSlow())
25684 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25686 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25688 if (!N0.hasOneUse() || !N1.hasOneUse())
25691 SDValue ShAmt0 = N0.getOperand(1);
25692 if (ShAmt0.getValueType() != MVT::i8)
25694 SDValue ShAmt1 = N1.getOperand(1);
25695 if (ShAmt1.getValueType() != MVT::i8)
25697 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
25698 ShAmt0 = ShAmt0.getOperand(0);
25699 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
25700 ShAmt1 = ShAmt1.getOperand(0);
25703 unsigned Opc = X86ISD::SHLD;
25704 SDValue Op0 = N0.getOperand(0);
25705 SDValue Op1 = N1.getOperand(0);
25706 if (ShAmt0.getOpcode() == ISD::SUB) {
25707 Opc = X86ISD::SHRD;
25708 std::swap(Op0, Op1);
25709 std::swap(ShAmt0, ShAmt1);
25712 unsigned Bits = VT.getSizeInBits();
25713 if (ShAmt1.getOpcode() == ISD::SUB) {
25714 SDValue Sum = ShAmt1.getOperand(0);
25715 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
25716 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
25717 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
25718 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
25719 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
25720 return DAG.getNode(Opc, DL, VT,
25722 DAG.getNode(ISD::TRUNCATE, DL,
25725 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
25726 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
25728 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
25729 return DAG.getNode(Opc, DL, VT,
25730 N0.getOperand(0), N1.getOperand(0),
25731 DAG.getNode(ISD::TRUNCATE, DL,
25738 // Generate NEG and CMOV for integer abs.
25739 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
25740 EVT VT = N->getValueType(0);
25742 // Since X86 does not have CMOV for 8-bit integer, we don't convert
25743 // 8-bit integer abs to NEG and CMOV.
25744 if (VT.isInteger() && VT.getSizeInBits() == 8)
25747 SDValue N0 = N->getOperand(0);
25748 SDValue N1 = N->getOperand(1);
25751 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
25752 // and change it to SUB and CMOV.
25753 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
25754 N0.getOpcode() == ISD::ADD &&
25755 N0.getOperand(1) == N1 &&
25756 N1.getOpcode() == ISD::SRA &&
25757 N1.getOperand(0) == N0.getOperand(0))
25758 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
25759 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
25760 // Generate SUB & CMOV.
25761 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
25762 DAG.getConstant(0, DL, VT), N0.getOperand(0));
25764 SDValue Ops[] = { N0.getOperand(0), Neg,
25765 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
25766 SDValue(Neg.getNode(), 1) };
25767 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
25772 // Try to turn tests against the signbit in the form of:
25773 // XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
25776 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
25777 // This is only worth doing if the output type is i8.
25778 if (N->getValueType(0) != MVT::i8)
25781 SDValue N0 = N->getOperand(0);
25782 SDValue N1 = N->getOperand(1);
25784 // We should be performing an xor against a truncated shift.
25785 if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
25788 // Make sure we are performing an xor against one.
25789 if (!isOneConstant(N1))
25792 // SetCC on x86 zero extends so only act on this if it's a logical shift.
25793 SDValue Shift = N0.getOperand(0);
25794 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
25797 // Make sure we are truncating from one of i16, i32 or i64.
25798 EVT ShiftTy = Shift.getValueType();
25799 if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
25802 // Make sure the shift amount extracts the sign bit.
25803 if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
25804 Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
25807 // Create a greater-than comparison against -1.
25808 // N.B. Using SETGE against 0 works but we want a canonical looking
25809 // comparison, using SETGT matches up with what TranslateX86CC.
25811 SDValue ShiftOp = Shift.getOperand(0);
25812 EVT ShiftOpTy = ShiftOp.getValueType();
25813 SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
25814 DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
25818 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
25819 TargetLowering::DAGCombinerInfo &DCI,
25820 const X86Subtarget *Subtarget) {
25821 if (DCI.isBeforeLegalizeOps())
25824 if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
25827 if (Subtarget->hasCMov())
25828 if (SDValue RV = performIntegerAbsCombine(N, DAG))
25831 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25837 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
25838 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
25839 /// X86ISD::AVG instruction.
25840 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
25841 const X86Subtarget *Subtarget, SDLoc DL) {
25842 if (!VT.isVector() || !VT.isSimple())
25844 EVT InVT = In.getValueType();
25845 unsigned NumElems = VT.getVectorNumElements();
25847 EVT ScalarVT = VT.getVectorElementType();
25848 if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
25849 isPowerOf2_32(NumElems)))
25852 // InScalarVT is the intermediate type in AVG pattern and it should be greater
25853 // than the original input type (i8/i16).
25854 EVT InScalarVT = InVT.getVectorElementType();
25855 if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
25858 if (Subtarget->hasAVX512()) {
25859 if (VT.getSizeInBits() > 512)
25861 } else if (Subtarget->hasAVX2()) {
25862 if (VT.getSizeInBits() > 256)
25865 if (VT.getSizeInBits() > 128)
25869 // Detect the following pattern:
25871 // %1 = zext <N x i8> %a to <N x i32>
25872 // %2 = zext <N x i8> %b to <N x i32>
25873 // %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
25874 // %4 = add nuw nsw <N x i32> %3, %2
25875 // %5 = lshr <N x i32> %N, <i32 1 x N>
25876 // %6 = trunc <N x i32> %5 to <N x i8>
25878 // In AVX512, the last instruction can also be a trunc store.
25880 if (In.getOpcode() != ISD::SRL)
25883 // A lambda checking the given SDValue is a constant vector and each element
25884 // is in the range [Min, Max].
25885 auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
25886 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
25887 if (!BV || !BV->isConstant())
25889 for (unsigned i = 0, e = V.getNumOperands(); i < e; i++) {
25890 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(i));
25893 uint64_t Val = C->getZExtValue();
25894 if (Val < Min || Val > Max)
25900 // Check if each element of the vector is left-shifted by one.
25901 auto LHS = In.getOperand(0);
25902 auto RHS = In.getOperand(1);
25903 if (!IsConstVectorInRange(RHS, 1, 1))
25905 if (LHS.getOpcode() != ISD::ADD)
25908 // Detect a pattern of a + b + 1 where the order doesn't matter.
25909 SDValue Operands[3];
25910 Operands[0] = LHS.getOperand(0);
25911 Operands[1] = LHS.getOperand(1);
25913 // Take care of the case when one of the operands is a constant vector whose
25914 // element is in the range [1, 256].
25915 if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
25916 Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
25917 Operands[0].getOperand(0).getValueType() == VT) {
25918 // The pattern is detected. Subtract one from the constant vector, then
25919 // demote it and emit X86ISD::AVG instruction.
25920 SDValue One = DAG.getConstant(1, DL, InScalarVT);
25921 SDValue Ones = DAG.getNode(ISD::BUILD_VECTOR, DL, InVT,
25922 SmallVector<SDValue, 8>(NumElems, One));
25923 Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], Ones);
25924 Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
25925 return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
25929 if (Operands[0].getOpcode() == ISD::ADD)
25930 std::swap(Operands[0], Operands[1]);
25931 else if (Operands[1].getOpcode() != ISD::ADD)
25933 Operands[2] = Operands[1].getOperand(0);
25934 Operands[1] = Operands[1].getOperand(1);
25936 // Now we have three operands of two additions. Check that one of them is a
25937 // constant vector with ones, and the other two are promoted from i8/i16.
25938 for (int i = 0; i < 3; ++i) {
25939 if (!IsConstVectorInRange(Operands[i], 1, 1))
25941 std::swap(Operands[i], Operands[2]);
25943 // Check if Operands[0] and Operands[1] are results of type promotion.
25944 for (int j = 0; j < 2; ++j)
25945 if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
25946 Operands[j].getOperand(0).getValueType() != VT)
25949 // The pattern is detected, emit X86ISD::AVG instruction.
25950 return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
25951 Operands[1].getOperand(0));
25957 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
25958 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
25959 TargetLowering::DAGCombinerInfo &DCI,
25960 const X86Subtarget *Subtarget) {
25961 LoadSDNode *Ld = cast<LoadSDNode>(N);
25962 EVT RegVT = Ld->getValueType(0);
25963 EVT MemVT = Ld->getMemoryVT();
25965 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25967 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
25968 // into two 16-byte operations.
25969 ISD::LoadExtType Ext = Ld->getExtensionType();
25971 unsigned AddressSpace = Ld->getAddressSpace();
25972 unsigned Alignment = Ld->getAlignment();
25973 if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
25974 Ext == ISD::NON_EXTLOAD &&
25975 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
25976 AddressSpace, Alignment, &Fast) && !Fast) {
25977 unsigned NumElems = RegVT.getVectorNumElements();
25981 SDValue Ptr = Ld->getBasePtr();
25982 SDValue Increment =
25983 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25985 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
25987 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25988 Ld->getPointerInfo(), Ld->isVolatile(),
25989 Ld->isNonTemporal(), Ld->isInvariant(),
25991 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25992 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25993 Ld->getPointerInfo(), Ld->isVolatile(),
25994 Ld->isNonTemporal(), Ld->isInvariant(),
25995 std::min(16U, Alignment));
25996 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
25998 Load2.getValue(1));
26000 SDValue NewVec = DAG.getUNDEF(RegVT);
26001 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
26002 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
26003 return DCI.CombineTo(N, NewVec, TF, true);
26009 /// PerformMLOADCombine - Resolve extending loads
26010 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
26011 TargetLowering::DAGCombinerInfo &DCI,
26012 const X86Subtarget *Subtarget) {
26013 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
26014 if (Mld->getExtensionType() != ISD::SEXTLOAD)
26017 EVT VT = Mld->getValueType(0);
26018 unsigned NumElems = VT.getVectorNumElements();
26019 EVT LdVT = Mld->getMemoryVT();
26022 assert(LdVT != VT && "Cannot extend to the same type");
26023 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
26024 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
26025 // From, To sizes and ElemCount must be pow of two
26026 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26027 "Unexpected size for extending masked load");
26029 unsigned SizeRatio = ToSz / FromSz;
26030 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
26032 // Create a type on which we perform the shuffle
26033 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26034 LdVT.getScalarType(), NumElems*SizeRatio);
26035 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26037 // Convert Src0 value
26038 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
26039 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
26040 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26041 for (unsigned i = 0; i != NumElems; ++i)
26042 ShuffleVec[i] = i * SizeRatio;
26044 // Can't shuffle using an illegal type.
26045 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26046 "WideVecVT should be legal");
26047 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
26048 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
26050 // Prepare the new mask
26052 SDValue Mask = Mld->getMask();
26053 if (Mask.getValueType() == VT) {
26054 // Mask and original value have the same type
26055 NewMask = DAG.getBitcast(WideVecVT, Mask);
26056 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26057 for (unsigned i = 0; i != NumElems; ++i)
26058 ShuffleVec[i] = i * SizeRatio;
26059 for (unsigned i = NumElems; i != NumElems * SizeRatio; ++i)
26060 ShuffleVec[i] = NumElems * SizeRatio;
26061 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26062 DAG.getConstant(0, dl, WideVecVT),
26066 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26067 unsigned WidenNumElts = NumElems*SizeRatio;
26068 unsigned MaskNumElts = VT.getVectorNumElements();
26069 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
26072 unsigned NumConcat = WidenNumElts / MaskNumElts;
26073 SmallVector<SDValue, 16> Ops(NumConcat);
26074 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26076 for (unsigned i = 1; i != NumConcat; ++i)
26079 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26082 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
26083 Mld->getBasePtr(), NewMask, WideSrc0,
26084 Mld->getMemoryVT(), Mld->getMemOperand(),
26086 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
26087 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
26089 /// PerformMSTORECombine - Resolve truncating stores
26090 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
26091 const X86Subtarget *Subtarget) {
26092 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
26093 if (!Mst->isTruncatingStore())
26096 EVT VT = Mst->getValue().getValueType();
26097 unsigned NumElems = VT.getVectorNumElements();
26098 EVT StVT = Mst->getMemoryVT();
26101 assert(StVT != VT && "Cannot truncate to the same type");
26102 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26103 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26105 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26107 // The truncating store is legal in some cases. For example
26108 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26109 // are designated for truncate store.
26110 // In this case we don't need any further transformations.
26111 if (TLI.isTruncStoreLegal(VT, StVT))
26114 // From, To sizes and ElemCount must be pow of two
26115 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26116 "Unexpected size for truncating masked store");
26117 // We are going to use the original vector elt for storing.
26118 // Accumulated smaller vector elements must be a multiple of the store size.
26119 assert (((NumElems * FromSz) % ToSz) == 0 &&
26120 "Unexpected ratio for truncating masked store");
26122 unsigned SizeRatio = FromSz / ToSz;
26123 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26125 // Create a type on which we perform the shuffle
26126 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26127 StVT.getScalarType(), NumElems*SizeRatio);
26129 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26131 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
26132 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26133 for (unsigned i = 0; i != NumElems; ++i)
26134 ShuffleVec[i] = i * SizeRatio;
26136 // Can't shuffle using an illegal type.
26137 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26138 "WideVecVT should be legal");
26140 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26141 DAG.getUNDEF(WideVecVT),
26145 SDValue Mask = Mst->getMask();
26146 if (Mask.getValueType() == VT) {
26147 // Mask and original value have the same type
26148 NewMask = DAG.getBitcast(WideVecVT, Mask);
26149 for (unsigned i = 0; i != NumElems; ++i)
26150 ShuffleVec[i] = i * SizeRatio;
26151 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
26152 ShuffleVec[i] = NumElems*SizeRatio;
26153 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26154 DAG.getConstant(0, dl, WideVecVT),
26158 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26159 unsigned WidenNumElts = NumElems*SizeRatio;
26160 unsigned MaskNumElts = VT.getVectorNumElements();
26161 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
26164 unsigned NumConcat = WidenNumElts / MaskNumElts;
26165 SmallVector<SDValue, 16> Ops(NumConcat);
26166 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26168 for (unsigned i = 1; i != NumConcat; ++i)
26171 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26174 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal,
26175 Mst->getBasePtr(), NewMask, StVT,
26176 Mst->getMemOperand(), false);
26178 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
26179 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
26180 const X86Subtarget *Subtarget) {
26181 StoreSDNode *St = cast<StoreSDNode>(N);
26182 EVT VT = St->getValue().getValueType();
26183 EVT StVT = St->getMemoryVT();
26185 SDValue StoredVal = St->getOperand(1);
26186 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26188 // If we are saving a concatenation of two XMM registers and 32-byte stores
26189 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
26191 unsigned AddressSpace = St->getAddressSpace();
26192 unsigned Alignment = St->getAlignment();
26193 if (VT.is256BitVector() && StVT == VT &&
26194 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
26195 AddressSpace, Alignment, &Fast) && !Fast) {
26196 unsigned NumElems = VT.getVectorNumElements();
26200 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
26201 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
26204 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26205 SDValue Ptr0 = St->getBasePtr();
26206 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
26208 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
26209 St->getPointerInfo(), St->isVolatile(),
26210 St->isNonTemporal(), Alignment);
26211 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
26212 St->getPointerInfo(), St->isVolatile(),
26213 St->isNonTemporal(),
26214 std::min(16U, Alignment));
26215 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
26218 // Optimize trunc store (of multiple scalars) to shuffle and store.
26219 // First, pack all of the elements in one place. Next, store to memory
26220 // in fewer chunks.
26221 if (St->isTruncatingStore() && VT.isVector()) {
26222 // Check if we can detect an AVG pattern from the truncation. If yes,
26223 // replace the trunc store by a normal store with the result of X86ISD::AVG
26226 detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG, Subtarget, dl);
26228 return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
26229 St->getPointerInfo(), St->isVolatile(),
26230 St->isNonTemporal(), St->getAlignment());
26232 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26233 unsigned NumElems = VT.getVectorNumElements();
26234 assert(StVT != VT && "Cannot truncate to the same type");
26235 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26236 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26238 // The truncating store is legal in some cases. For example
26239 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26240 // are designated for truncate store.
26241 // In this case we don't need any further transformations.
26242 if (TLI.isTruncStoreLegal(VT, StVT))
26245 // From, To sizes and ElemCount must be pow of two
26246 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
26247 // We are going to use the original vector elt for storing.
26248 // Accumulated smaller vector elements must be a multiple of the store size.
26249 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
26251 unsigned SizeRatio = FromSz / ToSz;
26253 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26255 // Create a type on which we perform the shuffle
26256 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26257 StVT.getScalarType(), NumElems*SizeRatio);
26259 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26261 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
26262 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
26263 for (unsigned i = 0; i != NumElems; ++i)
26264 ShuffleVec[i] = i * SizeRatio;
26266 // Can't shuffle using an illegal type.
26267 if (!TLI.isTypeLegal(WideVecVT))
26270 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26271 DAG.getUNDEF(WideVecVT),
26273 // At this point all of the data is stored at the bottom of the
26274 // register. We now need to save it to mem.
26276 // Find the largest store unit
26277 MVT StoreType = MVT::i8;
26278 for (MVT Tp : MVT::integer_valuetypes()) {
26279 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
26283 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
26284 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
26285 (64 <= NumElems * ToSz))
26286 StoreType = MVT::f64;
26288 // Bitcast the original vector into a vector of store-size units
26289 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
26290 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
26291 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
26292 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
26293 SmallVector<SDValue, 8> Chains;
26294 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
26295 TLI.getPointerTy(DAG.getDataLayout()));
26296 SDValue Ptr = St->getBasePtr();
26298 // Perform one or more big stores into memory.
26299 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
26300 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
26301 StoreType, ShuffWide,
26302 DAG.getIntPtrConstant(i, dl));
26303 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
26304 St->getPointerInfo(), St->isVolatile(),
26305 St->isNonTemporal(), St->getAlignment());
26306 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26307 Chains.push_back(Ch);
26310 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
26313 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
26314 // the FP state in cases where an emms may be missing.
26315 // A preferable solution to the general problem is to figure out the right
26316 // places to insert EMMS. This qualifies as a quick hack.
26318 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
26319 if (VT.getSizeInBits() != 64)
26322 const Function *F = DAG.getMachineFunction().getFunction();
26323 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
26325 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
26326 if ((VT.isVector() ||
26327 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
26328 isa<LoadSDNode>(St->getValue()) &&
26329 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
26330 St->getChain().hasOneUse() && !St->isVolatile()) {
26331 SDNode* LdVal = St->getValue().getNode();
26332 LoadSDNode *Ld = nullptr;
26333 int TokenFactorIndex = -1;
26334 SmallVector<SDValue, 8> Ops;
26335 SDNode* ChainVal = St->getChain().getNode();
26336 // Must be a store of a load. We currently handle two cases: the load
26337 // is a direct child, and it's under an intervening TokenFactor. It is
26338 // possible to dig deeper under nested TokenFactors.
26339 if (ChainVal == LdVal)
26340 Ld = cast<LoadSDNode>(St->getChain());
26341 else if (St->getValue().hasOneUse() &&
26342 ChainVal->getOpcode() == ISD::TokenFactor) {
26343 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
26344 if (ChainVal->getOperand(i).getNode() == LdVal) {
26345 TokenFactorIndex = i;
26346 Ld = cast<LoadSDNode>(St->getValue());
26348 Ops.push_back(ChainVal->getOperand(i));
26352 if (!Ld || !ISD::isNormalLoad(Ld))
26355 // If this is not the MMX case, i.e. we are just turning i64 load/store
26356 // into f64 load/store, avoid the transformation if there are multiple
26357 // uses of the loaded value.
26358 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
26363 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
26364 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
26366 if (Subtarget->is64Bit() || F64IsLegal) {
26367 MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
26368 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
26369 Ld->getPointerInfo(), Ld->isVolatile(),
26370 Ld->isNonTemporal(), Ld->isInvariant(),
26371 Ld->getAlignment());
26372 SDValue NewChain = NewLd.getValue(1);
26373 if (TokenFactorIndex != -1) {
26374 Ops.push_back(NewChain);
26375 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26377 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
26378 St->getPointerInfo(),
26379 St->isVolatile(), St->isNonTemporal(),
26380 St->getAlignment());
26383 // Otherwise, lower to two pairs of 32-bit loads / stores.
26384 SDValue LoAddr = Ld->getBasePtr();
26385 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
26386 DAG.getConstant(4, LdDL, MVT::i32));
26388 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
26389 Ld->getPointerInfo(),
26390 Ld->isVolatile(), Ld->isNonTemporal(),
26391 Ld->isInvariant(), Ld->getAlignment());
26392 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
26393 Ld->getPointerInfo().getWithOffset(4),
26394 Ld->isVolatile(), Ld->isNonTemporal(),
26396 MinAlign(Ld->getAlignment(), 4));
26398 SDValue NewChain = LoLd.getValue(1);
26399 if (TokenFactorIndex != -1) {
26400 Ops.push_back(LoLd);
26401 Ops.push_back(HiLd);
26402 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26405 LoAddr = St->getBasePtr();
26406 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
26407 DAG.getConstant(4, StDL, MVT::i32));
26409 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
26410 St->getPointerInfo(),
26411 St->isVolatile(), St->isNonTemporal(),
26412 St->getAlignment());
26413 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
26414 St->getPointerInfo().getWithOffset(4),
26416 St->isNonTemporal(),
26417 MinAlign(St->getAlignment(), 4));
26418 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
26421 // This is similar to the above case, but here we handle a scalar 64-bit
26422 // integer store that is extracted from a vector on a 32-bit target.
26423 // If we have SSE2, then we can treat it like a floating-point double
26424 // to get past legalization. The execution dependencies fixup pass will
26425 // choose the optimal machine instruction for the store if this really is
26426 // an integer or v2f32 rather than an f64.
26427 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
26428 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
26429 SDValue OldExtract = St->getOperand(1);
26430 SDValue ExtOp0 = OldExtract.getOperand(0);
26431 unsigned VecSize = ExtOp0.getValueSizeInBits();
26432 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
26433 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
26434 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
26435 BitCast, OldExtract.getOperand(1));
26436 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
26437 St->getPointerInfo(), St->isVolatile(),
26438 St->isNonTemporal(), St->getAlignment());
26444 /// Return 'true' if this vector operation is "horizontal"
26445 /// and return the operands for the horizontal operation in LHS and RHS. A
26446 /// horizontal operation performs the binary operation on successive elements
26447 /// of its first operand, then on successive elements of its second operand,
26448 /// returning the resulting values in a vector. For example, if
26449 /// A = < float a0, float a1, float a2, float a3 >
26451 /// B = < float b0, float b1, float b2, float b3 >
26452 /// then the result of doing a horizontal operation on A and B is
26453 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
26454 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
26455 /// A horizontal-op B, for some already available A and B, and if so then LHS is
26456 /// set to A, RHS to B, and the routine returns 'true'.
26457 /// Note that the binary operation should have the property that if one of the
26458 /// operands is UNDEF then the result is UNDEF.
26459 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
26460 // Look for the following pattern: if
26461 // A = < float a0, float a1, float a2, float a3 >
26462 // B = < float b0, float b1, float b2, float b3 >
26464 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
26465 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
26466 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
26467 // which is A horizontal-op B.
26469 // At least one of the operands should be a vector shuffle.
26470 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
26471 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
26474 MVT VT = LHS.getSimpleValueType();
26476 assert((VT.is128BitVector() || VT.is256BitVector()) &&
26477 "Unsupported vector type for horizontal add/sub");
26479 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
26480 // operate independently on 128-bit lanes.
26481 unsigned NumElts = VT.getVectorNumElements();
26482 unsigned NumLanes = VT.getSizeInBits()/128;
26483 unsigned NumLaneElts = NumElts / NumLanes;
26484 assert((NumLaneElts % 2 == 0) &&
26485 "Vector type should have an even number of elements in each lane");
26486 unsigned HalfLaneElts = NumLaneElts/2;
26488 // View LHS in the form
26489 // LHS = VECTOR_SHUFFLE A, B, LMask
26490 // If LHS is not a shuffle then pretend it is the shuffle
26491 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
26492 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
26495 SmallVector<int, 16> LMask(NumElts);
26496 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26497 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
26498 A = LHS.getOperand(0);
26499 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
26500 B = LHS.getOperand(1);
26501 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
26502 std::copy(Mask.begin(), Mask.end(), LMask.begin());
26504 if (LHS.getOpcode() != ISD::UNDEF)
26506 for (unsigned i = 0; i != NumElts; ++i)
26510 // Likewise, view RHS in the form
26511 // RHS = VECTOR_SHUFFLE C, D, RMask
26513 SmallVector<int, 16> RMask(NumElts);
26514 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26515 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
26516 C = RHS.getOperand(0);
26517 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
26518 D = RHS.getOperand(1);
26519 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
26520 std::copy(Mask.begin(), Mask.end(), RMask.begin());
26522 if (RHS.getOpcode() != ISD::UNDEF)
26524 for (unsigned i = 0; i != NumElts; ++i)
26528 // Check that the shuffles are both shuffling the same vectors.
26529 if (!(A == C && B == D) && !(A == D && B == C))
26532 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
26533 if (!A.getNode() && !B.getNode())
26536 // If A and B occur in reverse order in RHS, then "swap" them (which means
26537 // rewriting the mask).
26539 ShuffleVectorSDNode::commuteMask(RMask);
26541 // At this point LHS and RHS are equivalent to
26542 // LHS = VECTOR_SHUFFLE A, B, LMask
26543 // RHS = VECTOR_SHUFFLE A, B, RMask
26544 // Check that the masks correspond to performing a horizontal operation.
26545 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
26546 for (unsigned i = 0; i != NumLaneElts; ++i) {
26547 int LIdx = LMask[i+l], RIdx = RMask[i+l];
26549 // Ignore any UNDEF components.
26550 if (LIdx < 0 || RIdx < 0 ||
26551 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
26552 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
26555 // Check that successive elements are being operated on. If not, this is
26556 // not a horizontal operation.
26557 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
26558 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
26559 if (!(LIdx == Index && RIdx == Index + 1) &&
26560 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
26565 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
26566 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
26570 /// Do target-specific dag combines on floating point adds.
26571 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
26572 const X86Subtarget *Subtarget) {
26573 EVT VT = N->getValueType(0);
26574 SDValue LHS = N->getOperand(0);
26575 SDValue RHS = N->getOperand(1);
26577 // Try to synthesize horizontal adds from adds of shuffles.
26578 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26579 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26580 isHorizontalBinOp(LHS, RHS, true))
26581 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
26585 /// Do target-specific dag combines on floating point subs.
26586 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
26587 const X86Subtarget *Subtarget) {
26588 EVT VT = N->getValueType(0);
26589 SDValue LHS = N->getOperand(0);
26590 SDValue RHS = N->getOperand(1);
26592 // Try to synthesize horizontal subs from subs of shuffles.
26593 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26594 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26595 isHorizontalBinOp(LHS, RHS, false))
26596 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
26600 /// Truncate a group of v4i32 into v16i8/v8i16 using X86ISD::PACKUS.
26602 combineVectorTruncationWithPACKUS(SDNode *N, SelectionDAG &DAG,
26603 SmallVector<SDValue, 8> &Regs) {
26604 assert(Regs.size() > 0 && (Regs[0].getValueType() == MVT::v4i32 ||
26605 Regs[0].getValueType() == MVT::v2i64));
26606 EVT OutVT = N->getValueType(0);
26607 EVT OutSVT = OutVT.getVectorElementType();
26608 EVT InVT = Regs[0].getValueType();
26609 EVT InSVT = InVT.getVectorElementType();
26612 // First, use mask to unset all bits that won't appear in the result.
26613 assert((OutSVT == MVT::i8 || OutSVT == MVT::i16) &&
26614 "OutSVT can only be either i8 or i16.");
26616 DAG.getConstant(OutSVT == MVT::i8 ? 0xFF : 0xFFFF, DL, InSVT);
26617 SDValue MaskVec = DAG.getNode(
26618 ISD::BUILD_VECTOR, DL, InVT,
26619 SmallVector<SDValue, 8>(InVT.getVectorNumElements(), MaskVal));
26620 for (auto &Reg : Regs)
26621 Reg = DAG.getNode(ISD::AND, DL, InVT, MaskVec, Reg);
26623 MVT UnpackedVT, PackedVT;
26624 if (OutSVT == MVT::i8) {
26625 UnpackedVT = MVT::v8i16;
26626 PackedVT = MVT::v16i8;
26628 UnpackedVT = MVT::v4i32;
26629 PackedVT = MVT::v8i16;
26632 // In each iteration, truncate the type by a half size.
26633 auto RegNum = Regs.size();
26634 for (unsigned j = 1, e = InSVT.getSizeInBits() / OutSVT.getSizeInBits();
26635 j < e; j *= 2, RegNum /= 2) {
26636 for (unsigned i = 0; i < RegNum; i++)
26637 Regs[i] = DAG.getNode(ISD::BITCAST, DL, UnpackedVT, Regs[i]);
26638 for (unsigned i = 0; i < RegNum / 2; i++)
26639 Regs[i] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[i * 2],
26643 // If the type of the result is v8i8, we need do one more X86ISD::PACKUS, and
26644 // then extract a subvector as the result since v8i8 is not a legal type.
26645 if (OutVT == MVT::v8i8) {
26646 Regs[0] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[0], Regs[0]);
26647 Regs[0] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, Regs[0],
26648 DAG.getIntPtrConstant(0, DL));
26650 } else if (RegNum > 1) {
26651 Regs.resize(RegNum);
26652 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26657 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
26659 combineVectorTruncationWithPACKSS(SDNode *N, SelectionDAG &DAG,
26660 SmallVector<SDValue, 8> &Regs) {
26661 assert(Regs.size() > 0 && Regs[0].getValueType() == MVT::v4i32);
26662 EVT OutVT = N->getValueType(0);
26665 // Shift left by 16 bits, then arithmetic-shift right by 16 bits.
26666 SDValue ShAmt = DAG.getConstant(16, DL, MVT::i32);
26667 for (auto &Reg : Regs) {
26668 Reg = getTargetVShiftNode(X86ISD::VSHLI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26669 Reg = getTargetVShiftNode(X86ISD::VSRAI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26672 for (unsigned i = 0, e = Regs.size() / 2; i < e; i++)
26673 Regs[i] = DAG.getNode(X86ISD::PACKSS, DL, MVT::v8i16, Regs[i * 2],
26676 if (Regs.size() > 2) {
26677 Regs.resize(Regs.size() / 2);
26678 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26683 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
26684 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
26685 /// legalization the truncation will be translated into a BUILD_VECTOR with each
26686 /// element that is extracted from a vector and then truncated, and it is
26687 /// diffcult to do this optimization based on them.
26688 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
26689 const X86Subtarget *Subtarget) {
26690 EVT OutVT = N->getValueType(0);
26691 if (!OutVT.isVector())
26694 SDValue In = N->getOperand(0);
26695 if (!In.getValueType().isSimple())
26698 EVT InVT = In.getValueType();
26699 unsigned NumElems = OutVT.getVectorNumElements();
26701 // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
26702 // SSE2, and we need to take care of it specially.
26703 // AVX512 provides vpmovdb.
26704 if (!Subtarget->hasSSE2() || Subtarget->hasAVX2())
26707 EVT OutSVT = OutVT.getVectorElementType();
26708 EVT InSVT = InVT.getVectorElementType();
26709 if (!((InSVT == MVT::i32 || InSVT == MVT::i64) &&
26710 (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
26714 // SSSE3's pshufb results in less instructions in the cases below.
26715 if (Subtarget->hasSSSE3() && NumElems == 8 &&
26716 ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
26717 (InSVT == MVT::i32 && OutSVT == MVT::i16)))
26722 // Split a long vector into vectors of legal type.
26723 unsigned RegNum = InVT.getSizeInBits() / 128;
26724 SmallVector<SDValue, 8> SubVec(RegNum);
26725 if (InSVT == MVT::i32) {
26726 for (unsigned i = 0; i < RegNum; i++)
26727 SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
26728 DAG.getIntPtrConstant(i * 4, DL));
26730 for (unsigned i = 0; i < RegNum; i++)
26731 SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
26732 DAG.getIntPtrConstant(i * 2, DL));
26735 // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PAKCUS
26736 // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
26737 // truncate 2 x v4i32 to v8i16.
26738 if (Subtarget->hasSSE41() || OutSVT == MVT::i8)
26739 return combineVectorTruncationWithPACKUS(N, DAG, SubVec);
26740 else if (InSVT == MVT::i32)
26741 return combineVectorTruncationWithPACKSS(N, DAG, SubVec);
26746 static SDValue PerformTRUNCATECombine(SDNode *N, SelectionDAG &DAG,
26747 const X86Subtarget *Subtarget) {
26748 // Try to detect AVG pattern first.
26749 SDValue Avg = detectAVGPattern(N->getOperand(0), N->getValueType(0), DAG,
26750 Subtarget, SDLoc(N));
26754 return combineVectorTruncation(N, DAG, Subtarget);
26757 /// Do target-specific dag combines on floating point negations.
26758 static SDValue PerformFNEGCombine(SDNode *N, SelectionDAG &DAG,
26759 const X86Subtarget *Subtarget) {
26760 EVT VT = N->getValueType(0);
26761 EVT SVT = VT.getScalarType();
26762 SDValue Arg = N->getOperand(0);
26765 // Let legalize expand this if it isn't a legal type yet.
26766 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
26769 // If we're negating a FMUL node on a target with FMA, then we can avoid the
26770 // use of a constant by performing (-0 - A*B) instead.
26771 // FIXME: Check rounding control flags as well once it becomes available.
26772 if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
26773 Arg->getFlags()->hasNoSignedZeros() && Subtarget->hasAnyFMA()) {
26774 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
26775 return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
26776 Arg.getOperand(1), Zero);
26779 // If we're negating a FMA node, then we can adjust the
26780 // instruction to include the extra negation.
26781 if (Arg.hasOneUse()) {
26782 switch (Arg.getOpcode()) {
26783 case X86ISD::FMADD:
26784 return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
26785 Arg.getOperand(1), Arg.getOperand(2));
26786 case X86ISD::FMSUB:
26787 return DAG.getNode(X86ISD::FNMADD, DL, VT, Arg.getOperand(0),
26788 Arg.getOperand(1), Arg.getOperand(2));
26789 case X86ISD::FNMADD:
26790 return DAG.getNode(X86ISD::FMSUB, DL, VT, Arg.getOperand(0),
26791 Arg.getOperand(1), Arg.getOperand(2));
26792 case X86ISD::FNMSUB:
26793 return DAG.getNode(X86ISD::FMADD, DL, VT, Arg.getOperand(0),
26794 Arg.getOperand(1), Arg.getOperand(2));
26800 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
26801 const X86Subtarget *Subtarget) {
26802 EVT VT = N->getValueType(0);
26803 if (VT.is512BitVector() && !Subtarget->hasDQI()) {
26804 // VXORPS, VORPS, VANDPS, VANDNPS are supported only under DQ extention.
26805 // These logic operations may be executed in the integer domain.
26807 MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
26808 MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
26810 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
26811 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
26812 unsigned IntOpcode = 0;
26813 switch (N->getOpcode()) {
26814 default: llvm_unreachable("Unexpected FP logic op");
26815 case X86ISD::FOR: IntOpcode = ISD::OR; break;
26816 case X86ISD::FXOR: IntOpcode = ISD::XOR; break;
26817 case X86ISD::FAND: IntOpcode = ISD::AND; break;
26818 case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
26820 SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
26821 return DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
26825 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
26826 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
26827 const X86Subtarget *Subtarget) {
26828 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
26830 // F[X]OR(0.0, x) -> x
26831 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
26832 if (C->getValueAPF().isPosZero())
26833 return N->getOperand(1);
26835 // F[X]OR(x, 0.0) -> x
26836 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
26837 if (C->getValueAPF().isPosZero())
26838 return N->getOperand(0);
26840 return lowerX86FPLogicOp(N, DAG, Subtarget);
26843 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
26844 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
26845 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
26847 // Only perform optimizations if UnsafeMath is used.
26848 if (!DAG.getTarget().Options.UnsafeFPMath)
26851 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
26852 // into FMINC and FMAXC, which are Commutative operations.
26853 unsigned NewOp = 0;
26854 switch (N->getOpcode()) {
26855 default: llvm_unreachable("unknown opcode");
26856 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
26857 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
26860 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
26861 N->getOperand(0), N->getOperand(1));
26864 static SDValue performFMaxNumCombine(SDNode *N, SelectionDAG &DAG,
26865 const X86Subtarget *Subtarget) {
26866 // This takes at least 3 instructions, so favor a library call when
26867 // minimizing code size.
26868 if (DAG.getMachineFunction().getFunction()->optForMinSize())
26871 EVT VT = N->getValueType(0);
26873 // TODO: Check for global or instruction-level "nnan". In that case, we
26874 // should be able to lower to FMAX/FMIN alone.
26875 // TODO: If an operand is already known to be a NaN or not a NaN, this
26876 // should be an optional swap and FMAX/FMIN.
26877 // TODO: Allow f64, vectors, and fminnum.
26879 if (VT != MVT::f32 || !Subtarget->hasSSE1() || Subtarget->useSoftFloat())
26882 SDValue Op0 = N->getOperand(0);
26883 SDValue Op1 = N->getOperand(1);
26885 EVT SetCCType = DAG.getTargetLoweringInfo().getSetCCResultType(
26886 DAG.getDataLayout(), *DAG.getContext(), VT);
26888 // There are 4 possibilities involving NaN inputs, and these are the required
26892 // ----------------
26893 // Num | Max | Op0 |
26894 // Op0 ----------------
26895 // NaN | Op1 | NaN |
26896 // ----------------
26898 // The SSE FP max/min instructions were not designed for this case, but rather
26900 // Max = Op1 > Op0 ? Op1 : Op0
26902 // So they always return Op0 if either input is a NaN. However, we can still
26903 // use those instructions for fmaxnum by selecting away a NaN input.
26905 // If either operand is NaN, the 2nd source operand (Op0) is passed through.
26906 SDValue Max = DAG.getNode(X86ISD::FMAX, DL, VT, Op1, Op0);
26907 SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType , Op0, Op0, ISD::SETUO);
26909 // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
26910 // are NaN, the NaN value of Op1 is the result.
26911 return DAG.getNode(ISD::SELECT, DL, VT, IsOp0Nan, Op1, Max);
26914 /// Do target-specific dag combines on X86ISD::FAND nodes.
26915 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG,
26916 const X86Subtarget *Subtarget) {
26917 // FAND(0.0, x) -> 0.0
26918 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
26919 if (C->getValueAPF().isPosZero())
26920 return N->getOperand(0);
26922 // FAND(x, 0.0) -> 0.0
26923 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
26924 if (C->getValueAPF().isPosZero())
26925 return N->getOperand(1);
26927 return lowerX86FPLogicOp(N, DAG, Subtarget);
26930 /// Do target-specific dag combines on X86ISD::FANDN nodes
26931 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG,
26932 const X86Subtarget *Subtarget) {
26933 // FANDN(0.0, x) -> x
26934 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
26935 if (C->getValueAPF().isPosZero())
26936 return N->getOperand(1);
26938 // FANDN(x, 0.0) -> 0.0
26939 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
26940 if (C->getValueAPF().isPosZero())
26941 return N->getOperand(1);
26943 return lowerX86FPLogicOp(N, DAG, Subtarget);
26946 static SDValue PerformBTCombine(SDNode *N,
26948 TargetLowering::DAGCombinerInfo &DCI) {
26949 // BT ignores high bits in the bit index operand.
26950 SDValue Op1 = N->getOperand(1);
26951 if (Op1.hasOneUse()) {
26952 unsigned BitWidth = Op1.getValueSizeInBits();
26953 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
26954 APInt KnownZero, KnownOne;
26955 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
26956 !DCI.isBeforeLegalizeOps());
26957 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26958 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
26959 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
26960 DCI.CommitTargetLoweringOpt(TLO);
26965 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
26966 SDValue Op = N->getOperand(0);
26967 if (Op.getOpcode() == ISD::BITCAST)
26968 Op = Op.getOperand(0);
26969 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
26970 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
26971 VT.getVectorElementType().getSizeInBits() ==
26972 OpVT.getVectorElementType().getSizeInBits()) {
26973 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
26978 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
26979 const X86Subtarget *Subtarget) {
26980 EVT VT = N->getValueType(0);
26981 if (!VT.isVector())
26984 SDValue N0 = N->getOperand(0);
26985 SDValue N1 = N->getOperand(1);
26986 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
26989 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
26990 // both SSE and AVX2 since there is no sign-extended shift right
26991 // operation on a vector with 64-bit elements.
26992 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
26993 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
26994 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
26995 N0.getOpcode() == ISD::SIGN_EXTEND)) {
26996 SDValue N00 = N0.getOperand(0);
26998 // EXTLOAD has a better solution on AVX2,
26999 // it may be replaced with X86ISD::VSEXT node.
27000 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
27001 if (!ISD::isNormalLoad(N00.getNode()))
27004 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
27005 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
27007 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
27013 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
27014 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
27015 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
27016 /// eliminate extend, add, and shift instructions.
27017 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
27018 const X86Subtarget *Subtarget) {
27019 // TODO: This should be valid for other integer types.
27020 EVT VT = Sext->getValueType(0);
27021 if (VT != MVT::i64)
27024 // We need an 'add nsw' feeding into the 'sext'.
27025 SDValue Add = Sext->getOperand(0);
27026 if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
27029 // Having a constant operand to the 'add' ensures that we are not increasing
27030 // the instruction count because the constant is extended for free below.
27031 // A constant operand can also become the displacement field of an LEA.
27032 auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
27036 // Don't make the 'add' bigger if there's no hope of combining it with some
27037 // other 'add' or 'shl' instruction.
27038 // TODO: It may be profitable to generate simpler LEA instructions in place
27039 // of single 'add' instructions, but the cost model for selecting an LEA
27040 // currently has a high threshold.
27041 bool HasLEAPotential = false;
27042 for (auto *User : Sext->uses()) {
27043 if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
27044 HasLEAPotential = true;
27048 if (!HasLEAPotential)
27051 // Everything looks good, so pull the 'sext' ahead of the 'add'.
27052 int64_t AddConstant = AddOp1->getSExtValue();
27053 SDValue AddOp0 = Add.getOperand(0);
27054 SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
27055 SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
27057 // The wider add is guaranteed to not wrap because both operands are
27060 Flags.setNoSignedWrap(true);
27061 return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
27064 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
27065 TargetLowering::DAGCombinerInfo &DCI,
27066 const X86Subtarget *Subtarget) {
27067 SDValue N0 = N->getOperand(0);
27068 EVT VT = N->getValueType(0);
27069 EVT SVT = VT.getScalarType();
27070 EVT InVT = N0.getValueType();
27071 EVT InSVT = InVT.getScalarType();
27074 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
27075 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
27076 // This exposes the sext to the sdivrem lowering, so that it directly extends
27077 // from AH (which we otherwise need to do contortions to access).
27078 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
27079 InVT == MVT::i8 && VT == MVT::i32) {
27080 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
27081 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
27082 N0.getOperand(0), N0.getOperand(1));
27083 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
27084 return R.getValue(1);
27087 if (!DCI.isBeforeLegalizeOps()) {
27088 if (InVT == MVT::i1) {
27089 SDValue Zero = DAG.getConstant(0, DL, VT);
27091 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
27092 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
27097 if (VT.isVector() && Subtarget->hasSSE2()) {
27098 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
27099 EVT InVT = N.getValueType();
27100 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
27101 Size / InVT.getScalarSizeInBits());
27102 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
27103 DAG.getUNDEF(InVT));
27105 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
27108 // If target-size is less than 128-bits, extend to a type that would extend
27109 // to 128 bits, extend that and extract the original target vector.
27110 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
27111 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27112 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27113 unsigned Scale = 128 / VT.getSizeInBits();
27115 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
27116 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
27117 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
27118 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
27119 DAG.getIntPtrConstant(0, DL));
27122 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
27123 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
27124 if (VT.getSizeInBits() == 128 &&
27125 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27126 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27127 SDValue ExOp = ExtendVecSize(DL, N0, 128);
27128 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
27131 // On pre-AVX2 targets, split into 128-bit nodes of
27132 // ISD::SIGN_EXTEND_VECTOR_INREG.
27133 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
27134 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27135 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27136 unsigned NumVecs = VT.getSizeInBits() / 128;
27137 unsigned NumSubElts = 128 / SVT.getSizeInBits();
27138 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
27139 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
27141 SmallVector<SDValue, 8> Opnds;
27142 for (unsigned i = 0, Offset = 0; i != NumVecs;
27143 ++i, Offset += NumSubElts) {
27144 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
27145 DAG.getIntPtrConstant(Offset, DL));
27146 SrcVec = ExtendVecSize(DL, SrcVec, 128);
27147 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
27148 Opnds.push_back(SrcVec);
27150 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
27154 if (Subtarget->hasAVX() && VT.is256BitVector())
27155 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27158 if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
27164 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
27165 const X86Subtarget* Subtarget) {
27167 EVT VT = N->getValueType(0);
27169 // Let legalize expand this if it isn't a legal type yet.
27170 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27173 EVT ScalarVT = VT.getScalarType();
27174 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasAnyFMA())
27177 SDValue A = N->getOperand(0);
27178 SDValue B = N->getOperand(1);
27179 SDValue C = N->getOperand(2);
27181 bool NegA = (A.getOpcode() == ISD::FNEG);
27182 bool NegB = (B.getOpcode() == ISD::FNEG);
27183 bool NegC = (C.getOpcode() == ISD::FNEG);
27185 // Negative multiplication when NegA xor NegB
27186 bool NegMul = (NegA != NegB);
27188 A = A.getOperand(0);
27190 B = B.getOperand(0);
27192 C = C.getOperand(0);
27196 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
27198 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
27200 return DAG.getNode(Opcode, dl, VT, A, B, C);
27203 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
27204 TargetLowering::DAGCombinerInfo &DCI,
27205 const X86Subtarget *Subtarget) {
27206 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
27207 // (and (i32 x86isd::setcc_carry), 1)
27208 // This eliminates the zext. This transformation is necessary because
27209 // ISD::SETCC is always legalized to i8.
27211 SDValue N0 = N->getOperand(0);
27212 EVT VT = N->getValueType(0);
27214 if (N0.getOpcode() == ISD::AND &&
27216 N0.getOperand(0).hasOneUse()) {
27217 SDValue N00 = N0.getOperand(0);
27218 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27219 if (!isOneConstant(N0.getOperand(1)))
27221 return DAG.getNode(ISD::AND, dl, VT,
27222 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27223 N00.getOperand(0), N00.getOperand(1)),
27224 DAG.getConstant(1, dl, VT));
27228 if (N0.getOpcode() == ISD::TRUNCATE &&
27230 N0.getOperand(0).hasOneUse()) {
27231 SDValue N00 = N0.getOperand(0);
27232 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27233 return DAG.getNode(ISD::AND, dl, VT,
27234 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27235 N00.getOperand(0), N00.getOperand(1)),
27236 DAG.getConstant(1, dl, VT));
27240 if (VT.is256BitVector())
27241 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27244 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
27245 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
27246 // This exposes the zext to the udivrem lowering, so that it directly extends
27247 // from AH (which we otherwise need to do contortions to access).
27248 if (N0.getOpcode() == ISD::UDIVREM &&
27249 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
27250 (VT == MVT::i32 || VT == MVT::i64)) {
27251 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
27252 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
27253 N0.getOperand(0), N0.getOperand(1));
27254 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
27255 return R.getValue(1);
27261 // Optimize x == -y --> x+y == 0
27262 // x != -y --> x+y != 0
27263 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
27264 const X86Subtarget* Subtarget) {
27265 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
27266 SDValue LHS = N->getOperand(0);
27267 SDValue RHS = N->getOperand(1);
27268 EVT VT = N->getValueType(0);
27271 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
27272 if (isNullConstant(LHS.getOperand(0)) && LHS.hasOneUse()) {
27273 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
27274 LHS.getOperand(1));
27275 return DAG.getSetCC(DL, N->getValueType(0), addV,
27276 DAG.getConstant(0, DL, addV.getValueType()), CC);
27278 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
27279 if (isNullConstant(RHS.getOperand(0)) && RHS.hasOneUse()) {
27280 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
27281 RHS.getOperand(1));
27282 return DAG.getSetCC(DL, N->getValueType(0), addV,
27283 DAG.getConstant(0, DL, addV.getValueType()), CC);
27286 if (VT.getScalarType() == MVT::i1 &&
27287 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
27289 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27290 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27291 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27293 if (!IsSEXT0 || !IsVZero1) {
27294 // Swap the operands and update the condition code.
27295 std::swap(LHS, RHS);
27296 CC = ISD::getSetCCSwappedOperands(CC);
27298 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27299 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27300 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27303 if (IsSEXT0 && IsVZero1) {
27304 assert(VT == LHS.getOperand(0).getValueType() &&
27305 "Uexpected operand type");
27306 if (CC == ISD::SETGT)
27307 return DAG.getConstant(0, DL, VT);
27308 if (CC == ISD::SETLE)
27309 return DAG.getConstant(1, DL, VT);
27310 if (CC == ISD::SETEQ || CC == ISD::SETGE)
27311 return DAG.getNOT(DL, LHS.getOperand(0), VT);
27313 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
27314 "Unexpected condition code!");
27315 return LHS.getOperand(0);
27322 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
27323 SDValue V0 = N->getOperand(0);
27324 SDValue V1 = N->getOperand(1);
27326 EVT VT = N->getValueType(0);
27328 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
27329 // operands and changing the mask to 1. This saves us a bunch of
27330 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
27331 // x86InstrInfo knows how to commute this back after instruction selection
27332 // if it would help register allocation.
27334 // TODO: If optimizing for size or a processor that doesn't suffer from
27335 // partial register update stalls, this should be transformed into a MOVSD
27336 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
27338 if (VT == MVT::v2f64)
27339 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
27340 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
27341 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
27342 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
27348 static SDValue PerformGatherScatterCombine(SDNode *N, SelectionDAG &DAG) {
27350 // Gather and Scatter instructions use k-registers for masks. The type of
27351 // the masks is v*i1. So the mask will be truncated anyway.
27352 // The SIGN_EXTEND_INREG my be dropped.
27353 SDValue Mask = N->getOperand(2);
27354 if (Mask.getOpcode() == ISD::SIGN_EXTEND_INREG) {
27355 SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
27356 NewOps[2] = Mask.getOperand(0);
27357 DAG.UpdateNodeOperands(N, NewOps);
27362 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
27363 // as "sbb reg,reg", since it can be extended without zext and produces
27364 // an all-ones bit which is more useful than 0/1 in some cases.
27365 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
27368 return DAG.getNode(ISD::AND, DL, VT,
27369 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27370 DAG.getConstant(X86::COND_B, DL, MVT::i8),
27372 DAG.getConstant(1, DL, VT));
27373 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
27374 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
27375 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27376 DAG.getConstant(X86::COND_B, DL, MVT::i8),
27380 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
27381 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
27382 TargetLowering::DAGCombinerInfo &DCI,
27383 const X86Subtarget *Subtarget) {
27385 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
27386 SDValue EFLAGS = N->getOperand(1);
27388 if (CC == X86::COND_A) {
27389 // Try to convert COND_A into COND_B in an attempt to facilitate
27390 // materializing "setb reg".
27392 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
27393 // cannot take an immediate as its first operand.
27395 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
27396 EFLAGS.getValueType().isInteger() &&
27397 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
27398 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
27399 EFLAGS.getNode()->getVTList(),
27400 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
27401 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
27402 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
27406 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
27407 // a zext and produces an all-ones bit which is more useful than 0/1 in some
27409 if (CC == X86::COND_B)
27410 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
27412 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27413 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27414 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
27420 // Optimize branch condition evaluation.
27422 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
27423 TargetLowering::DAGCombinerInfo &DCI,
27424 const X86Subtarget *Subtarget) {
27426 SDValue Chain = N->getOperand(0);
27427 SDValue Dest = N->getOperand(1);
27428 SDValue EFLAGS = N->getOperand(3);
27429 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
27431 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27432 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27433 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
27440 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
27441 SelectionDAG &DAG) {
27442 // Take advantage of vector comparisons producing 0 or -1 in each lane to
27443 // optimize away operation when it's from a constant.
27445 // The general transformation is:
27446 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
27447 // AND(VECTOR_CMP(x,y), constant2)
27448 // constant2 = UNARYOP(constant)
27450 // Early exit if this isn't a vector operation, the operand of the
27451 // unary operation isn't a bitwise AND, or if the sizes of the operations
27452 // aren't the same.
27453 EVT VT = N->getValueType(0);
27454 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
27455 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
27456 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
27459 // Now check that the other operand of the AND is a constant. We could
27460 // make the transformation for non-constant splats as well, but it's unclear
27461 // that would be a benefit as it would not eliminate any operations, just
27462 // perform one more step in scalar code before moving to the vector unit.
27463 if (BuildVectorSDNode *BV =
27464 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
27465 // Bail out if the vector isn't a constant.
27466 if (!BV->isConstant())
27469 // Everything checks out. Build up the new and improved node.
27471 EVT IntVT = BV->getValueType(0);
27472 // Create a new constant of the appropriate type for the transformed
27474 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
27475 // The AND node needs bitcasts to/from an integer vector type around it.
27476 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
27477 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
27478 N->getOperand(0)->getOperand(0), MaskConst);
27479 SDValue Res = DAG.getBitcast(VT, NewAnd);
27486 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27487 const X86Subtarget *Subtarget) {
27488 SDValue Op0 = N->getOperand(0);
27489 EVT VT = N->getValueType(0);
27490 EVT InVT = Op0.getValueType();
27491 EVT InSVT = InVT.getScalarType();
27492 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27494 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
27495 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
27496 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27498 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27499 InVT.getVectorNumElements());
27500 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
27502 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
27503 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
27505 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27511 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27512 const X86Subtarget *Subtarget) {
27513 // First try to optimize away the conversion entirely when it's
27514 // conditionally from a constant. Vectors only.
27515 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
27518 // Now move on to more general possibilities.
27519 SDValue Op0 = N->getOperand(0);
27520 EVT VT = N->getValueType(0);
27521 EVT InVT = Op0.getValueType();
27522 EVT InSVT = InVT.getScalarType();
27524 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
27525 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
27526 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27528 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27529 InVT.getVectorNumElements());
27530 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
27531 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27534 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
27535 // a 32-bit target where SSE doesn't support i64->FP operations.
27536 if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
27537 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
27538 EVT LdVT = Ld->getValueType(0);
27540 // This transformation is not supported if the result type is f16
27541 if (VT == MVT::f16)
27544 if (!Ld->isVolatile() && !VT.isVector() &&
27545 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
27546 !Subtarget->is64Bit() && LdVT == MVT::i64) {
27547 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
27548 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
27549 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
27556 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
27557 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
27558 X86TargetLowering::DAGCombinerInfo &DCI) {
27559 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
27560 // the result is either zero or one (depending on the input carry bit).
27561 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
27562 if (X86::isZeroNode(N->getOperand(0)) &&
27563 X86::isZeroNode(N->getOperand(1)) &&
27564 // We don't have a good way to replace an EFLAGS use, so only do this when
27566 SDValue(N, 1).use_empty()) {
27568 EVT VT = N->getValueType(0);
27569 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
27570 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
27571 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
27572 DAG.getConstant(X86::COND_B, DL,
27575 DAG.getConstant(1, DL, VT));
27576 return DCI.CombineTo(N, Res1, CarryOut);
27582 // fold (add Y, (sete X, 0)) -> adc 0, Y
27583 // (add Y, (setne X, 0)) -> sbb -1, Y
27584 // (sub (sete X, 0), Y) -> sbb 0, Y
27585 // (sub (setne X, 0), Y) -> adc -1, Y
27586 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
27589 // Look through ZExts.
27590 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
27591 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
27594 SDValue SetCC = Ext.getOperand(0);
27595 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
27598 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
27599 if (CC != X86::COND_E && CC != X86::COND_NE)
27602 SDValue Cmp = SetCC.getOperand(1);
27603 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
27604 !X86::isZeroNode(Cmp.getOperand(1)) ||
27605 !Cmp.getOperand(0).getValueType().isInteger())
27608 SDValue CmpOp0 = Cmp.getOperand(0);
27609 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
27610 DAG.getConstant(1, DL, CmpOp0.getValueType()));
27612 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
27613 if (CC == X86::COND_NE)
27614 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
27615 DL, OtherVal.getValueType(), OtherVal,
27616 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
27618 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
27619 DL, OtherVal.getValueType(), OtherVal,
27620 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
27623 /// PerformADDCombine - Do target-specific dag combines on integer adds.
27624 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
27625 const X86Subtarget *Subtarget) {
27626 EVT VT = N->getValueType(0);
27627 SDValue Op0 = N->getOperand(0);
27628 SDValue Op1 = N->getOperand(1);
27630 // Try to synthesize horizontal adds from adds of shuffles.
27631 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27632 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27633 isHorizontalBinOp(Op0, Op1, true))
27634 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
27636 return OptimizeConditionalInDecrement(N, DAG);
27639 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
27640 const X86Subtarget *Subtarget) {
27641 SDValue Op0 = N->getOperand(0);
27642 SDValue Op1 = N->getOperand(1);
27644 // X86 can't encode an immediate LHS of a sub. See if we can push the
27645 // negation into a preceding instruction.
27646 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
27647 // If the RHS of the sub is a XOR with one use and a constant, invert the
27648 // immediate. Then add one to the LHS of the sub so we can turn
27649 // X-Y -> X+~Y+1, saving one register.
27650 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
27651 isa<ConstantSDNode>(Op1.getOperand(1))) {
27652 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
27653 EVT VT = Op0.getValueType();
27654 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
27656 DAG.getConstant(~XorC, SDLoc(Op1), VT));
27657 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
27658 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
27662 // Try to synthesize horizontal adds from adds of shuffles.
27663 EVT VT = N->getValueType(0);
27664 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27665 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27666 isHorizontalBinOp(Op0, Op1, true))
27667 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
27669 return OptimizeConditionalInDecrement(N, DAG);
27672 /// performVZEXTCombine - Performs build vector combines
27673 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
27674 TargetLowering::DAGCombinerInfo &DCI,
27675 const X86Subtarget *Subtarget) {
27677 MVT VT = N->getSimpleValueType(0);
27678 SDValue Op = N->getOperand(0);
27679 MVT OpVT = Op.getSimpleValueType();
27680 MVT OpEltVT = OpVT.getVectorElementType();
27681 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
27683 // (vzext (bitcast (vzext (x)) -> (vzext x)
27685 while (V.getOpcode() == ISD::BITCAST)
27686 V = V.getOperand(0);
27688 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
27689 MVT InnerVT = V.getSimpleValueType();
27690 MVT InnerEltVT = InnerVT.getVectorElementType();
27692 // If the element sizes match exactly, we can just do one larger vzext. This
27693 // is always an exact type match as vzext operates on integer types.
27694 if (OpEltVT == InnerEltVT) {
27695 assert(OpVT == InnerVT && "Types must match for vzext!");
27696 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
27699 // The only other way we can combine them is if only a single element of the
27700 // inner vzext is used in the input to the outer vzext.
27701 if (InnerEltVT.getSizeInBits() < InputBits)
27704 // In this case, the inner vzext is completely dead because we're going to
27705 // only look at bits inside of the low element. Just do the outer vzext on
27706 // a bitcast of the input to the inner.
27707 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
27710 // Check if we can bypass extracting and re-inserting an element of an input
27711 // vector. Essentially:
27712 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
27713 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
27714 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
27715 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
27716 SDValue ExtractedV = V.getOperand(0);
27717 SDValue OrigV = ExtractedV.getOperand(0);
27718 if (isNullConstant(ExtractedV.getOperand(1))) {
27719 MVT OrigVT = OrigV.getSimpleValueType();
27720 // Extract a subvector if necessary...
27721 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
27722 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
27723 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
27724 OrigVT.getVectorNumElements() / Ratio);
27725 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
27726 DAG.getIntPtrConstant(0, DL));
27728 Op = DAG.getBitcast(OpVT, OrigV);
27729 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
27736 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
27737 DAGCombinerInfo &DCI) const {
27738 SelectionDAG &DAG = DCI.DAG;
27739 switch (N->getOpcode()) {
27741 case ISD::EXTRACT_VECTOR_ELT:
27742 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
27745 case X86ISD::SHRUNKBLEND:
27746 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
27747 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG, Subtarget);
27748 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
27749 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
27750 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
27751 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
27752 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
27755 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
27756 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
27757 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
27758 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
27759 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
27760 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
27761 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
27762 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
27763 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
27764 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
27765 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
27766 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
27767 case ISD::FNEG: return PerformFNEGCombine(N, DAG, Subtarget);
27768 case ISD::TRUNCATE: return PerformTRUNCATECombine(N, DAG, Subtarget);
27770 case X86ISD::FOR: return PerformFORCombine(N, DAG, Subtarget);
27772 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
27773 case ISD::FMAXNUM: return performFMaxNumCombine(N, DAG, Subtarget);
27774 case X86ISD::FAND: return PerformFANDCombine(N, DAG, Subtarget);
27775 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG, Subtarget);
27776 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
27777 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
27778 case ISD::ANY_EXTEND:
27779 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
27780 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
27781 case ISD::SIGN_EXTEND_INREG:
27782 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
27783 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
27784 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
27785 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
27786 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
27787 case X86ISD::SHUFP: // Handle all target specific shuffles
27788 case X86ISD::PALIGNR:
27789 case X86ISD::UNPCKH:
27790 case X86ISD::UNPCKL:
27791 case X86ISD::MOVHLPS:
27792 case X86ISD::MOVLHPS:
27793 case X86ISD::PSHUFB:
27794 case X86ISD::PSHUFD:
27795 case X86ISD::PSHUFHW:
27796 case X86ISD::PSHUFLW:
27797 case X86ISD::MOVSS:
27798 case X86ISD::MOVSD:
27799 case X86ISD::VPERMILPI:
27800 case X86ISD::VPERM2X128:
27801 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
27802 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
27803 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
27805 case ISD::MSCATTER: return PerformGatherScatterCombine(N, DAG);
27811 /// isTypeDesirableForOp - Return true if the target has native support for
27812 /// the specified value type and it is 'desirable' to use the type for the
27813 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
27814 /// instruction encodings are longer and some i16 instructions are slow.
27815 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
27816 if (!isTypeLegal(VT))
27818 if (VT != MVT::i16)
27825 case ISD::SIGN_EXTEND:
27826 case ISD::ZERO_EXTEND:
27827 case ISD::ANY_EXTEND:
27840 /// IsDesirableToPromoteOp - This method query the target whether it is
27841 /// beneficial for dag combiner to promote the specified node. If true, it
27842 /// should return the desired promotion type by reference.
27843 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
27844 EVT VT = Op.getValueType();
27845 if (VT != MVT::i16)
27848 bool Promote = false;
27849 bool Commute = false;
27850 switch (Op.getOpcode()) {
27853 LoadSDNode *LD = cast<LoadSDNode>(Op);
27854 // If the non-extending load has a single use and it's not live out, then it
27855 // might be folded.
27856 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
27857 Op.hasOneUse()*/) {
27858 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
27859 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
27860 // The only case where we'd want to promote LOAD (rather then it being
27861 // promoted as an operand is when it's only use is liveout.
27862 if (UI->getOpcode() != ISD::CopyToReg)
27869 case ISD::SIGN_EXTEND:
27870 case ISD::ZERO_EXTEND:
27871 case ISD::ANY_EXTEND:
27876 SDValue N0 = Op.getOperand(0);
27877 // Look out for (store (shl (load), x)).
27878 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
27891 SDValue N0 = Op.getOperand(0);
27892 SDValue N1 = Op.getOperand(1);
27893 if (!Commute && MayFoldLoad(N1))
27895 // Avoid disabling potential load folding opportunities.
27896 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
27898 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
27908 //===----------------------------------------------------------------------===//
27909 // X86 Inline Assembly Support
27910 //===----------------------------------------------------------------------===//
27912 // Helper to match a string separated by whitespace.
27913 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
27914 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
27916 for (StringRef Piece : Pieces) {
27917 if (!S.startswith(Piece)) // Check if the piece matches.
27920 S = S.substr(Piece.size());
27921 StringRef::size_type Pos = S.find_first_not_of(" \t");
27922 if (Pos == 0) // We matched a prefix.
27931 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
27933 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
27934 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
27935 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
27936 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
27938 if (AsmPieces.size() == 3)
27940 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
27947 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
27948 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
27950 std::string AsmStr = IA->getAsmString();
27952 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
27953 if (!Ty || Ty->getBitWidth() % 16 != 0)
27956 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
27957 SmallVector<StringRef, 4> AsmPieces;
27958 SplitString(AsmStr, AsmPieces, ";\n");
27960 switch (AsmPieces.size()) {
27961 default: return false;
27963 // FIXME: this should verify that we are targeting a 486 or better. If not,
27964 // we will turn this bswap into something that will be lowered to logical
27965 // ops instead of emitting the bswap asm. For now, we don't support 486 or
27966 // lower so don't worry about this.
27968 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
27969 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
27970 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
27971 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
27972 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
27973 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
27974 // No need to check constraints, nothing other than the equivalent of
27975 // "=r,0" would be valid here.
27976 return IntrinsicLowering::LowerToByteSwap(CI);
27979 // rorw $$8, ${0:w} --> llvm.bswap.i16
27980 if (CI->getType()->isIntegerTy(16) &&
27981 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
27982 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
27983 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
27985 StringRef ConstraintsStr = IA->getConstraintString();
27986 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
27987 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
27988 if (clobbersFlagRegisters(AsmPieces))
27989 return IntrinsicLowering::LowerToByteSwap(CI);
27993 if (CI->getType()->isIntegerTy(32) &&
27994 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
27995 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
27996 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
27997 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
27999 StringRef ConstraintsStr = IA->getConstraintString();
28000 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28001 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28002 if (clobbersFlagRegisters(AsmPieces))
28003 return IntrinsicLowering::LowerToByteSwap(CI);
28006 if (CI->getType()->isIntegerTy(64)) {
28007 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
28008 if (Constraints.size() >= 2 &&
28009 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
28010 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
28011 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
28012 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
28013 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
28014 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
28015 return IntrinsicLowering::LowerToByteSwap(CI);
28023 /// getConstraintType - Given a constraint letter, return the type of
28024 /// constraint it is for this target.
28025 X86TargetLowering::ConstraintType
28026 X86TargetLowering::getConstraintType(StringRef Constraint) const {
28027 if (Constraint.size() == 1) {
28028 switch (Constraint[0]) {
28039 return C_RegisterClass;
28063 return TargetLowering::getConstraintType(Constraint);
28066 /// Examine constraint type and operand type and determine a weight value.
28067 /// This object must already have been set up with the operand type
28068 /// and the current alternative constraint selected.
28069 TargetLowering::ConstraintWeight
28070 X86TargetLowering::getSingleConstraintMatchWeight(
28071 AsmOperandInfo &info, const char *constraint) const {
28072 ConstraintWeight weight = CW_Invalid;
28073 Value *CallOperandVal = info.CallOperandVal;
28074 // If we don't have a value, we can't do a match,
28075 // but allow it at the lowest weight.
28076 if (!CallOperandVal)
28078 Type *type = CallOperandVal->getType();
28079 // Look at the constraint type.
28080 switch (*constraint) {
28082 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
28093 if (CallOperandVal->getType()->isIntegerTy())
28094 weight = CW_SpecificReg;
28099 if (type->isFloatingPointTy())
28100 weight = CW_SpecificReg;
28103 if (type->isX86_MMXTy() && Subtarget->hasMMX())
28104 weight = CW_SpecificReg;
28108 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
28109 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
28110 weight = CW_Register;
28113 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
28114 if (C->getZExtValue() <= 31)
28115 weight = CW_Constant;
28119 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28120 if (C->getZExtValue() <= 63)
28121 weight = CW_Constant;
28125 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28126 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
28127 weight = CW_Constant;
28131 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28132 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
28133 weight = CW_Constant;
28137 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28138 if (C->getZExtValue() <= 3)
28139 weight = CW_Constant;
28143 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28144 if (C->getZExtValue() <= 0xff)
28145 weight = CW_Constant;
28150 if (isa<ConstantFP>(CallOperandVal)) {
28151 weight = CW_Constant;
28155 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28156 if ((C->getSExtValue() >= -0x80000000LL) &&
28157 (C->getSExtValue() <= 0x7fffffffLL))
28158 weight = CW_Constant;
28162 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28163 if (C->getZExtValue() <= 0xffffffff)
28164 weight = CW_Constant;
28171 /// LowerXConstraint - try to replace an X constraint, which matches anything,
28172 /// with another that has more specific requirements based on the type of the
28173 /// corresponding operand.
28174 const char *X86TargetLowering::
28175 LowerXConstraint(EVT ConstraintVT) const {
28176 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
28177 // 'f' like normal targets.
28178 if (ConstraintVT.isFloatingPoint()) {
28179 if (Subtarget->hasSSE2())
28181 if (Subtarget->hasSSE1())
28185 return TargetLowering::LowerXConstraint(ConstraintVT);
28188 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
28189 /// vector. If it is invalid, don't add anything to Ops.
28190 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
28191 std::string &Constraint,
28192 std::vector<SDValue>&Ops,
28193 SelectionDAG &DAG) const {
28196 // Only support length 1 constraints for now.
28197 if (Constraint.length() > 1) return;
28199 char ConstraintLetter = Constraint[0];
28200 switch (ConstraintLetter) {
28203 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28204 if (C->getZExtValue() <= 31) {
28205 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28206 Op.getValueType());
28212 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28213 if (C->getZExtValue() <= 63) {
28214 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28215 Op.getValueType());
28221 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28222 if (isInt<8>(C->getSExtValue())) {
28223 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28224 Op.getValueType());
28230 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28231 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
28232 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
28233 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
28234 Op.getValueType());
28240 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28241 if (C->getZExtValue() <= 3) {
28242 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28243 Op.getValueType());
28249 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28250 if (C->getZExtValue() <= 255) {
28251 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28252 Op.getValueType());
28258 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28259 if (C->getZExtValue() <= 127) {
28260 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28261 Op.getValueType());
28267 // 32-bit signed value
28268 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28269 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28270 C->getSExtValue())) {
28271 // Widen to 64 bits here to get it sign extended.
28272 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
28275 // FIXME gcc accepts some relocatable values here too, but only in certain
28276 // memory models; it's complicated.
28281 // 32-bit unsigned value
28282 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28283 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28284 C->getZExtValue())) {
28285 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28286 Op.getValueType());
28290 // FIXME gcc accepts some relocatable values here too, but only in certain
28291 // memory models; it's complicated.
28295 // Literal immediates are always ok.
28296 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
28297 // Widen to 64 bits here to get it sign extended.
28298 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
28302 // In any sort of PIC mode addresses need to be computed at runtime by
28303 // adding in a register or some sort of table lookup. These can't
28304 // be used as immediates.
28305 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
28308 // If we are in non-pic codegen mode, we allow the address of a global (with
28309 // an optional displacement) to be used with 'i'.
28310 GlobalAddressSDNode *GA = nullptr;
28311 int64_t Offset = 0;
28313 // Match either (GA), (GA+C), (GA+C1+C2), etc.
28315 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
28316 Offset += GA->getOffset();
28318 } else if (Op.getOpcode() == ISD::ADD) {
28319 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28320 Offset += C->getZExtValue();
28321 Op = Op.getOperand(0);
28324 } else if (Op.getOpcode() == ISD::SUB) {
28325 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28326 Offset += -C->getZExtValue();
28327 Op = Op.getOperand(0);
28332 // Otherwise, this isn't something we can handle, reject it.
28336 const GlobalValue *GV = GA->getGlobal();
28337 // If we require an extra load to get this address, as in PIC mode, we
28338 // can't accept it.
28339 if (isGlobalStubReference(
28340 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
28343 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
28344 GA->getValueType(0), Offset);
28349 if (Result.getNode()) {
28350 Ops.push_back(Result);
28353 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
28356 std::pair<unsigned, const TargetRegisterClass *>
28357 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
28358 StringRef Constraint,
28360 // First, see if this is a constraint that directly corresponds to an LLVM
28362 if (Constraint.size() == 1) {
28363 // GCC Constraint Letters
28364 switch (Constraint[0]) {
28366 // TODO: Slight differences here in allocation order and leaving
28367 // RIP in the class. Do they matter any more here than they do
28368 // in the normal allocation?
28369 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
28370 if (Subtarget->is64Bit()) {
28371 if (VT == MVT::i32 || VT == MVT::f32)
28372 return std::make_pair(0U, &X86::GR32RegClass);
28373 if (VT == MVT::i16)
28374 return std::make_pair(0U, &X86::GR16RegClass);
28375 if (VT == MVT::i8 || VT == MVT::i1)
28376 return std::make_pair(0U, &X86::GR8RegClass);
28377 if (VT == MVT::i64 || VT == MVT::f64)
28378 return std::make_pair(0U, &X86::GR64RegClass);
28381 // 32-bit fallthrough
28382 case 'Q': // Q_REGS
28383 if (VT == MVT::i32 || VT == MVT::f32)
28384 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
28385 if (VT == MVT::i16)
28386 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
28387 if (VT == MVT::i8 || VT == MVT::i1)
28388 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
28389 if (VT == MVT::i64)
28390 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
28392 case 'r': // GENERAL_REGS
28393 case 'l': // INDEX_REGS
28394 if (VT == MVT::i8 || VT == MVT::i1)
28395 return std::make_pair(0U, &X86::GR8RegClass);
28396 if (VT == MVT::i16)
28397 return std::make_pair(0U, &X86::GR16RegClass);
28398 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
28399 return std::make_pair(0U, &X86::GR32RegClass);
28400 return std::make_pair(0U, &X86::GR64RegClass);
28401 case 'R': // LEGACY_REGS
28402 if (VT == MVT::i8 || VT == MVT::i1)
28403 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
28404 if (VT == MVT::i16)
28405 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
28406 if (VT == MVT::i32 || !Subtarget->is64Bit())
28407 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
28408 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
28409 case 'f': // FP Stack registers.
28410 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
28411 // value to the correct fpstack register class.
28412 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
28413 return std::make_pair(0U, &X86::RFP32RegClass);
28414 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
28415 return std::make_pair(0U, &X86::RFP64RegClass);
28416 return std::make_pair(0U, &X86::RFP80RegClass);
28417 case 'y': // MMX_REGS if MMX allowed.
28418 if (!Subtarget->hasMMX()) break;
28419 return std::make_pair(0U, &X86::VR64RegClass);
28420 case 'Y': // SSE_REGS if SSE2 allowed
28421 if (!Subtarget->hasSSE2()) break;
28423 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
28424 if (!Subtarget->hasSSE1()) break;
28426 switch (VT.SimpleTy) {
28428 // Scalar SSE types.
28431 return std::make_pair(0U, &X86::FR32RegClass);
28434 return std::make_pair(0U, &X86::FR64RegClass);
28435 // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28443 return std::make_pair(0U, &X86::VR128RegClass);
28451 return std::make_pair(0U, &X86::VR256RegClass);
28456 return std::make_pair(0U, &X86::VR512RegClass);
28462 // Use the default implementation in TargetLowering to convert the register
28463 // constraint into a member of a register class.
28464 std::pair<unsigned, const TargetRegisterClass*> Res;
28465 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
28467 // Not found as a standard register?
28469 // Map st(0) -> st(7) -> ST0
28470 if (Constraint.size() == 7 && Constraint[0] == '{' &&
28471 tolower(Constraint[1]) == 's' &&
28472 tolower(Constraint[2]) == 't' &&
28473 Constraint[3] == '(' &&
28474 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
28475 Constraint[5] == ')' &&
28476 Constraint[6] == '}') {
28478 Res.first = X86::FP0+Constraint[4]-'0';
28479 Res.second = &X86::RFP80RegClass;
28483 // GCC allows "st(0)" to be called just plain "st".
28484 if (StringRef("{st}").equals_lower(Constraint)) {
28485 Res.first = X86::FP0;
28486 Res.second = &X86::RFP80RegClass;
28491 if (StringRef("{flags}").equals_lower(Constraint)) {
28492 Res.first = X86::EFLAGS;
28493 Res.second = &X86::CCRRegClass;
28497 // 'A' means EAX + EDX.
28498 if (Constraint == "A") {
28499 Res.first = X86::EAX;
28500 Res.second = &X86::GR32_ADRegClass;
28506 // Otherwise, check to see if this is a register class of the wrong value
28507 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
28508 // turn into {ax},{dx}.
28509 // MVT::Other is used to specify clobber names.
28510 if (Res.second->hasType(VT) || VT == MVT::Other)
28511 return Res; // Correct type already, nothing to do.
28513 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
28514 // return "eax". This should even work for things like getting 64bit integer
28515 // registers when given an f64 type.
28516 const TargetRegisterClass *Class = Res.second;
28517 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
28518 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
28519 unsigned Size = VT.getSizeInBits();
28520 MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
28521 : Size == 16 ? MVT::i16
28522 : Size == 32 ? MVT::i32
28523 : Size == 64 ? MVT::i64
28525 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
28527 Res.first = DestReg;
28528 Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
28529 : SimpleTy == MVT::i16 ? &X86::GR16RegClass
28530 : SimpleTy == MVT::i32 ? &X86::GR32RegClass
28531 : &X86::GR64RegClass;
28532 assert(Res.second->contains(Res.first) && "Register in register class");
28534 // No register found/type mismatch.
28536 Res.second = nullptr;
28538 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
28539 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
28540 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
28541 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
28542 Class == &X86::VR512RegClass) {
28543 // Handle references to XMM physical registers that got mapped into the
28544 // wrong class. This can happen with constraints like {xmm0} where the
28545 // target independent register mapper will just pick the first match it can
28546 // find, ignoring the required type.
28548 // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28549 if (VT == MVT::f32 || VT == MVT::i32)
28550 Res.second = &X86::FR32RegClass;
28551 else if (VT == MVT::f64 || VT == MVT::i64)
28552 Res.second = &X86::FR64RegClass;
28553 else if (X86::VR128RegClass.hasType(VT))
28554 Res.second = &X86::VR128RegClass;
28555 else if (X86::VR256RegClass.hasType(VT))
28556 Res.second = &X86::VR256RegClass;
28557 else if (X86::VR512RegClass.hasType(VT))
28558 Res.second = &X86::VR512RegClass;
28560 // Type mismatch and not a clobber: Return an error;
28562 Res.second = nullptr;
28569 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
28570 const AddrMode &AM, Type *Ty,
28571 unsigned AS) const {
28572 // Scaling factors are not free at all.
28573 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
28574 // will take 2 allocations in the out of order engine instead of 1
28575 // for plain addressing mode, i.e. inst (reg1).
28577 // vaddps (%rsi,%drx), %ymm0, %ymm1
28578 // Requires two allocations (one for the load, one for the computation)
28580 // vaddps (%rsi), %ymm0, %ymm1
28581 // Requires just 1 allocation, i.e., freeing allocations for other operations
28582 // and having less micro operations to execute.
28584 // For some X86 architectures, this is even worse because for instance for
28585 // stores, the complex addressing mode forces the instruction to use the
28586 // "load" ports instead of the dedicated "store" port.
28587 // E.g., on Haswell:
28588 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
28589 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
28590 if (isLegalAddressingMode(DL, AM, Ty, AS))
28591 // Scale represents reg2 * scale, thus account for 1
28592 // as soon as we use a second register.
28593 return AM.Scale != 0;
28597 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
28598 // Integer division on x86 is expensive. However, when aggressively optimizing
28599 // for code size, we prefer to use a div instruction, as it is usually smaller
28600 // than the alternative sequence.
28601 // The exception to this is vector division. Since x86 doesn't have vector
28602 // integer division, leaving the division as-is is a loss even in terms of
28603 // size, because it will have to be scalarized, while the alternative code
28604 // sequence can be performed in vector form.
28605 bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
28606 Attribute::MinSize);
28607 return OptSize && !VT.isVector();
28610 void X86TargetLowering::markInRegArguments(SelectionDAG &DAG,
28611 TargetLowering::ArgListTy& Args) const {
28612 // The MCU psABI requires some arguments to be passed in-register.
28613 // For regular calls, the inreg arguments are marked by the front-end.
28614 // However, for compiler generated library calls, we have to patch this
28616 if (!Subtarget->isTargetMCU() || !Args.size())
28619 unsigned FreeRegs = 3;
28620 for (auto &Arg : Args) {
28621 // For library functions, we do not expect any fancy types.
28622 unsigned Size = DAG.getDataLayout().getTypeSizeInBits(Arg.Ty);
28623 unsigned SizeInRegs = (Size + 31) / 32;
28624 if (SizeInRegs > 2 || SizeInRegs > FreeRegs)
28627 Arg.isInReg = true;
28628 FreeRegs -= SizeInRegs;